Compare commits

...
2 Commits
Author SHA1 Message Date
Denozordec be1cb6381a fix(ix): восстановить применение и подключение клиентов
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m17s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 2m10s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 10s
2026-11-23 10:22:45 +07:00
Denozordec 4900101b5e fix(ui): обновить раздел точек обмена и выбор типа узла
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 3s
Docker images / backend-image (push) Successful in 16s
Docker images / frontend-image (push) Successful in 3m34s
Docker images / updater-image (push) Successful in 2m36s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-23 02:07:56 +07:00
16 changed files with 1393 additions and 239 deletions

No files matched your search

+228
View File
@@ -0,0 +1,228 @@
"use client"
import { useId, type ReactNode } from "react"
import Link from "next/link"
import { PlusIcon, XIcon } from "lucide-react"
import type { IxSite } from "@mmapp/contracts/internet-exchange"
import { Button } from "@/components/ui/button"
import { Field, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"
import { Textarea } from "@/components/ui/textarea"
type Binding = IxSite["interfaces"][number]
type Group = IxSite["groups"][number]
type Path = Group["primary"]
type Peer = IxSite["neighbors"][number]
type Choice = { value: string; label: string }
function TextField({ label, value, edit, numeric, placeholder }: {
label: string; value: string | number; edit: (value: string) => void; numeric?: boolean; placeholder?: string
}) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Input id={id} value={value} inputMode={numeric ? "numeric" : undefined} placeholder={placeholder}
onChange={event => { if (!numeric || /^\d*$/.test(event.target.value)) edit(event.target.value) }} />
</Field>
}
function Pick<T extends string>({ label, value, options, edit, disabled }: {
label: string; value?: T; options: readonly { value: T; label: string }[]; edit: (value: T) => void; disabled: boolean
}) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Select value={value ?? null} items={options} disabled={disabled}
onValueChange={next => { if (next !== null) edit(next) }}>
<SelectTrigger className="w-full" id={id}><SelectValue placeholder="Выберите значение" /></SelectTrigger>
<SelectContent>{options.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
</Select>
</Field>
}
function Flag({ label, checked, edit, disabled }: {
label: string; checked: boolean; edit: (value: boolean) => void; disabled: boolean
}) {
const id = useId()
return <Field orientation="horizontal" className="w-fit">
<Checkbox id={id} checked={checked} onCheckedChange={edit} disabled={disabled} />
<FieldLabel htmlFor={id}>{label}</FieldLabel>
</Field>
}
function Lines({ label, value, edit }: { label: string; value: string[]; edit: (value: string[]) => void }) {
const id = useId()
return <Field className="min-w-0">
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Textarea id={id} value={value.join("\n")} rows={2} placeholder="По одному префиксу на строку"
onChange={event => edit(event.target.value.split("\n"))}
onBlur={event => edit(event.target.value.split("\n").map(line => line.trim()).filter(Boolean))} />
</Field>
}
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children }: {
title: string; items: T[]; edit: (items: T[]) => void; make: () => T
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
}) {
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>}
</div>
</details>
}
const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
const none = {value: "", label: "Нет"}
const emptyPath = (name: string): Path => ({ interface: name, nextHop: "", probe: "" })
const emptyWireGuard = { peerPublicKey: "", listenPort: 51820, localAddress: "", peerAddress: "" }
const kinds = [
{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec" }, { value: "uplink", label: "Аплинк" },
] as const
function InterfaceFields({ value, edit, peers, readOnly, segmentName }: {
value: Binding; edit: (value: Binding) => void; peers: Choice[]; readOnly: boolean; segmentName: string
}) {
const wireGuard = value.provisionWireguard
return <>
<div className={columns}>
<TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
<Pick label="Тип подключения" value={value.kind} options={kinds} disabled={readOnly}
edit={kind => edit({ ...value, kind, ...(kind !== "wireguard" && {provisionWireguard: undefined}), ...(kind !== "uplink" && {natIpv4: undefined}) })} />
<Pick label="Удалённый узел" value={value.peerServerId ? String(value.peerServerId) : ""} options={[{ value: "", label: "Внешний сервер" }, ...peers]} disabled={readOnly}
edit={id => edit({ ...value, peerServerId: id ? Number(id) : undefined })} />
<TextField label="Локальный внешний адрес" value={value.localEndpoint ?? ""} edit={address => edit({ ...value, localEndpoint: address || undefined })} />
<TextField label="Удалённый внешний адрес" value={value.endpoint ?? ""} edit={address => edit({ ...value, endpoint: address || undefined })} />
</div>
<Lines label="Префиксы подключения" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
{value.kind === "gre-ipsec" && <p className="text-sm text-muted-foreground">
Создайте выделенный туннель в разделе <Link className="underline" href="/gre">GRE-туннели</Link>.
Укажите комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>, включите IPsec и отключите FastPath.
IX проверит обязательную транспортную политику GRE между указанными IPv4-адресами.
</p>}
{(value.kind === "uplink" || (value.kind === "wireguard" && !wireGuard)) && <p className="text-sm text-muted-foreground">
Для подключения существующего интерфейса выделите его под этот сегмент и задайте комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>.
</p>}
{value.kind === "uplink" && <Flag label="NAT IPv4" checked={!!value.natIpv4} disabled={readOnly} edit={natIpv4 => edit({ ...value, natIpv4 })} />}
{value.kind === "wireguard" && <Flag label="Создать интерфейс и пир WireGuard на узле IX" checked={!!wireGuard} disabled={readOnly}
edit={enabled => edit({ ...value, provisionWireguard: enabled ? { ...emptyWireGuard } : undefined })} />}
{wireGuard && <div className={columns}>
<TextField label="Публичный ключ пира" value={wireGuard.peerPublicKey} edit={peerPublicKey => edit({ ...value, provisionWireguard: { ...wireGuard, peerPublicKey } })} />
<TextField label="Порт WireGuard на IX" numeric value={wireGuard.listenPort || ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, listenPort: Number(port) } })} />
<TextField label="Локальный адрес туннеля (CIDR)" value={wireGuard.localAddress} edit={localAddress => edit({ ...value, provisionWireguard: { ...wireGuard, localAddress } })} />
<TextField label="Адрес пира в туннеле" value={wireGuard.peerAddress} edit={peerAddress => edit({ ...value, provisionWireguard: { ...wireGuard, peerAddress } })} />
<TextField label="Внешний адрес IX для шаблона Linux" value={wireGuard.hubEndpoint ?? ""} edit={address => edit({ ...value, provisionWireguard: { ...wireGuard, hubEndpoint: address || undefined } })} />
<TextField label="Порт удалённого WireGuard" numeric value={wireGuard.endpointPort ?? ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, endpointPort: port ? Number(port) : undefined } })} />
</div>}
</>
}
function PathFields({ title, value, edit, interfaces, readOnly }: {
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; readOnly: boolean
}) {
return <fieldset className="grid min-w-0 gap-3 rounded-md border p-3 sm:grid-cols-3">
<legend className="px-1 text-sm font-medium">{title}</legend>
<Pick label="Интерфейс пути" value={value.interface} options={interfaces} edit={name => edit({ ...value, interface: name })} disabled={readOnly} />
<TextField label="Адрес следующего шлюза" value={value.nextHop} edit={nextHop => edit({ ...value, nextHop })} />
<TextField label="Контрольный адрес" value={value.probe} edit={probe => edit({ ...value, probe })} />
</fieldset>
}
function GroupFields({ value, edit, interfaces, readOnly }: {
value: Group; edit: (value: Group) => void; interfaces: Choice[]; readOnly: boolean
}) {
return <>
<div className={columns}>
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
<Pick label="Если оба пути недоступны" value={value.onFailure} disabled={readOnly} options={[
{value: "block", label: "Отбрасывать трафик"}, {value: "segment-exit", label: "Использовать выход сегмента"},
]} edit={onFailure => edit({ ...value, onFailure })} />
</div>
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} 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 && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
</>
}
function PeerFields({ value, edit, interfaces, groups, readOnly }: {
value: Peer; edit: (value: Peer) => void; interfaces: Choice[]; groups: Choice[]; readOnly: boolean
}) {
const publicFeed = value.type === "public-feed"
return <>
<div className={columns}>
<TextField label="Имя BGP-соседа" value={value.id} edit={id => edit({ ...value, id })} />
<Pick label="Тип BGP-соседа" value={value.type} disabled={readOnly} options={[
{value: "member", label: "Участник IX"}, {value: "exchange", label: "Вторая площадка"}, {value: "public-feed", label: "Публичный фид"},
]} edit={type => edit({ ...value, type, ...(type === "public-feed" ? { group: undefined, exportPrefixes: [] } : { rules: [] }) })} />
<TextField label="Адрес BGP-соседа" value={value.address} edit={address => edit({ ...value, address })} />
<TextField label="Локальный адрес BGP" value={value.localAddress} edit={localAddress => edit({ ...value, localAddress })} />
<TextField label="ASN соседа" numeric value={value.remoteAs || ""} edit={asn => edit({ ...value, remoteAs: Number(asn) })} />
<Pick label="Интерфейс BGP" value={value.binding} options={interfaces} disabled={readOnly} edit={binding => edit({ ...value, binding })} />
<Pick label="Лимит префиксов" value={String(value.limit)} options={[10, 100, 1000, 10000].map(limit => ({value: String(limit), label: String(limit)}))}
disabled={readOnly} edit={limit => edit({ ...value, limit: Number(limit) as Peer["limit"] })} />
{!publicFeed && <Pick label="Группа шлюзов для импорта" value={value.group} options={groups} disabled={readOnly} edit={group => edit({ ...value, group })} />}
</div>
<Lines label="Префиксы импорта" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
{publicFeed
? <Entries title="Правила по BGP community" items={value.rules} edit={rules => edit({ ...value, rules })}
make={() => ({ community: "", group: groups[0]?.value ?? "" })} max={100} addLabel="Добавить правило" readOnly={readOnly}>
{(rule, update) => <div className={columns}>
<TextField label="BGP community" value={rule.community} placeholder="65000:10" edit={community => update({ ...rule, community })} />
<Pick label="Группа шлюзов правила" value={rule.group} options={groups} edit={group => update({ ...rule, group })} disabled={readOnly} />
</div>}
</Entries>
: <Lines label="Префиксы экспорта" value={value.exportPrefixes} edit={exportPrefixes => edit({ ...value, exportPrefixes })} />}
</>
}
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName }: {
site: IxSite; edit: (fields: Partial<IxSite>) => void; peers: Choice[]; readOnly: boolean; segmentName: string
}) {
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={20} addLabel="Добавить подключение" readOnly={readOnly}>
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} />}
</Entries>
<Entries<Group> title="Группы шлюзов" 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} readOnly={readOnly} />}
</Entries>
<Entries title="Статические маршруты" 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}
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">
{[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>
</details>
</fieldset>
}
+154
View File
@@ -0,0 +1,154 @@
"use client"
import { useMemo } from "react"
import { type ColumnDef, useTable } from "@tanstack/react-table"
import { FileTextIcon, PlusIcon, XIcon } from "lucide-react"
import type { IxConfiguration, IxSegment, IxSite, IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import { EmptyState } from "@/components/empty-state"
import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { Frame, FrameDescription, 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"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { IxSiteEditor } from "./ix-site-editor"
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean }
type Route = IxSiteObservation["routes"][number]
export const nodeLabel = (nodes: readonly IxNode[], id: number) => nodes.find(node => node.id === id)?.name || `Узел ${id}`
export const newSite = (): IxSite => ({
serverId: 0, autonomousSystem: 64512, routerId: "",
interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [],
})
export function SegmentStatus({ segment }: { segment: IxSegment }) {
return segment.revision === segment.appliedRevision
? <Badge variant="success-light">Применена</Badge>
: <Badge variant="warning-light">{segment.appliedRevision ? "Есть черновик" : "Черновик"}</Badge>
}
export function SegmentGrid({ rows, nodes, loading, open, empty }: {
rows: IxSegment[]; nodes: IxNode[]; loading: boolean; open: (segment: IxSegment) => void; empty: React.ReactNode
}) {
const columns = useMemo<ColumnDef<DataGridFeatures, IxSegment>[]>(() => [
{ id: "name", header: "Сегмент", size: 210, cell: ({ row }) => (
<Button type="button" variant="link" size="sm" className="max-w-full justify-start" onClick={() => open(row.original)}>
<span className="truncate">{row.original.configuration.name}</span>
</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: "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 })
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
}
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change }: {
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
}) {
function updateSite(index: number, fields: Partial<IxSite>) {
change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) })
}
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">
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
<FramePanel>
<Field className="max-w-md">
<FieldLabel htmlFor="ix-name">Имя сегмента</FieldLabel>
<Input id="ix-name" placeholder="ix-central" value={configuration.name} readOnly={readOnly}
onChange={event => change({ ...configuration, name: event.target.value })} />
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
</Field>
</FramePanel>
</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>}
</div>
{!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 />
</Button>}
</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">
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
<Select
value={site.serverId ? String(site.serverId) : null}
items={choices.map(node => ({ value: String(node.id), label: node.name }))}
disabled={readOnly}
onValueChange={value => { if (value) updateSite(index, { serverId: Number(value) }) }}
>
<SelectTrigger id={fieldId} className="w-full"><SelectValue placeholder="Выберите узел" /></SelectTrigger>
<SelectContent>
{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">
<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>
<Field className="min-w-0">
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
<Input id={fieldId + "-router"} placeholder="192.0.2.10" value={site.routerId} readOnly={readOnly}
onChange={event => updateSite(index, { routerId: event.target.value })} />
</Field>
</div>
<IxSiteEditor site={site} segmentName={configuration.name} readOnly={readOnly} 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 }))} />
</FramePanel>
</Frame>
})}
{!readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
<PlusIcon aria-hidden />Добавить площадку
</Button>}
</div>
}
const routeColumns: ColumnDef<DataGridFeatures, Route>[] = [
{ id: "prefix", header: "Префикс", size: 160, cell: ({ row }) => <span className="font-mono">{row.original.prefix}</span> },
{ id: "gateway", header: "Шлюз", size: 140, cell: ({ row }) => row.original.gateway || "—" },
{ id: "immediate", header: "Фактический next hop", size: 200, cell: ({ row }) => row.original.immediateGateway ?? "—" },
{ id: "active", header: "Состояние", size: 112, cell: ({ row }) => row.original.active
? <Badge variant="success-light">Активен</Badge>
: <Badge variant="secondary">Неактивен</Badge> },
]
export function RouteGrid({ observation, nodes }: { observation: IxSiteObservation; nodes: IxNode[] }) {
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: observation.routes, columns: routeColumns })
return <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<FrameTitle className="wrap-anywhere">{nodeLabel(nodes, observation.serverId)}</FrameTitle>
<FrameDescription>{new Date(observation.observedAt).toLocaleString("ru-RU")}</FrameDescription>
</div>
{observation.available ? <Badge variant="info-light">
BGP {observation.neighbors.filter(peer => peer.established).length} из {observation.neighbors.length}
</Badge> : <Badge variant="warning-light">Состояние недоступно</Badge>}
</FrameHeader>
{observation.available && <FramePanel className="min-w-0 p-0">
<div className="overflow-x-auto">
<DataGridShell table={table} recordCount={observation.routes.length}
emptyMessage={<EmptyState icon={<FileTextIcon />} title="Маршруты не найдены" className="py-8" />} />
</div>
</FramePanel>}
</Frame>
}
+327 -185
View File
@@ -1,250 +1,392 @@
"use client"
import { useEffect, useMemo, useState } from "react"
import { useEffect, useRef, useState } from "react"
import Link from "next/link"
import { NetworkIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import { type ColumnDef, useTable } from "@tanstack/react-table"
import { ixSegmentConfigurationSchema, type IxChange, type IxRouterObject, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { Badge } from "@/components/reui/badge"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { EmptyState } from "@/components/empty-state"
import { PageHeader } from "@/components/page-header"
import { Button, buttonVariants } from "@/components/ui/button"
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea"
import { can, ensureAuthConfig } from "@/lib/auth"
import { useDataSource } from "@/lib/data-source"
import { requestJson } from "@/shared/api/http-client"
import { mcpApi } from "@/shared/api/mcp"
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
type Node = { id: number; name: string; site: string; country: string; enabled: boolean }
type Connection = { id: string; name: string }
type Plan = { planId: string; state: string }
type Tab = "configuration" | "routes" | "changes" | "linux"
const title = "Точки обмена трафиком"
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
const json = (value: unknown) => JSON.stringify(value, null, 2)
const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) })
function SegmentGrid({ rows, open }: { rows: IxSegment[]; open: (segment: IxSegment) => void }) {
const columns: ColumnDef<DataGridFeatures, IxSegment>[] = [
{ id: "name", header: "Сегмент", cell: ({ row }) => <Button variant="ghost" size="sm" onClick={() => open(row.original)}>{row.original.configuration.name}</Button> },
{ id: "sites", header: "Площадки", cell: ({ row }) => row.original.configuration.sites.length },
{ id: "neighbors", header: "BGP-соседи", cell: ({ row }) => row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0) },
{ id: "state", header: "Состояние конфигурации", cell: ({ row }) => row.original.revision === row.original.appliedRevision
? <Badge variant="success-light">Применена</Badge>
: <Badge variant="warning-light">Черновик</Badge> },
]
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
return <DataGridShell table={table} recordCount={rows.length} />
}
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
export default function IxPage() {
const { backendUrl, mode, prefsHydrated } = useDataSource()
const [segments, setSegments] = useState<IxSegment[]>([])
const [nodes, setNodes] = useState<Node[]>([])
const [connections, setConnections] = useState<Connection[]>([])
const [connectionId, setConnectionId] = useState("")
const [nodes, setNodes] = useState<IxNode[]>([])
const [peers, setPeers] = useState<IxNode[]>([])
const [selected, setSelected] = useState<IxSegment | null>(null)
const [editing, setEditing] = useState(false)
const [body, setBody] = useState("")
const [draft, setDraft] = useState<IxConfiguration | null>(null)
const [advanced, setAdvanced] = useState<string | null>(null)
const [filter, setFilter] = useState("")
const [nodeId, setNodeId] = useState("")
const [name, setName] = useState("")
const [asn, setAsn] = useState("64512")
const [routerId, setRouterId] = useState("")
const [observations, setObservations] = useState<IxSiteObservation[]>([])
const [preview, setPreview] = useState<IxRouterObject[] | null>(null)
const [linux, setLinux] = useState("")
const [plan, setPlan] = useState<Plan | null>(null)
const [tab, setTab] = useState<"configuration" | "routes" | "changes">("configuration")
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
const [plan, setPlan] = useState<IxWebPlan | null>(null)
const [tab, setTab] = useState<Tab>("configuration")
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
const [notice, setNotice] = useState("")
const [write, setWrite] = useState(false)
const [approve, setApprove] = useState(false)
const heading = useRef<HTMLHeadingElement>(null)
const focusAfterNavigation = useRef(false)
const inDetail = draft !== null
async function load(signal?: AbortSignal) {
const options = { signal }
if (signal?.aborted) return
setWrite(can("mm:network:write"))
const [segmentsResult, nodesResult] = await Promise.all([
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", options),
requestJson<{ items: Node[] }>(backendUrl, "/api/ix/nodes", options),
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }),
requestJson<{ items: IxNode[]; peers?: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }),
])
if (signal?.aborted) return
setSegments(segmentsResult.items)
setNodes(nodesResult.items)
if (can("mm:mcp:read")) {
const { connections } = await mcpApi(backendUrl).connections(signal)
setConnections(connections.filter(connection => connection.policy.status === "active" &&
connection.policy.scope.operationIds.includes("network.ix.configure")).map(connection => ({ id: connection.id, name: connection.name })))
}
setPeers(nodesResult.peers ?? nodesResult.items)
}
useEffect(() => {
if (!prefsHydrated || mode !== "live") return
const controller = new AbortController()
void ensureAuthConfig().then(async () => {
void ensureAuthConfig().then(() => {
if (controller.signal.aborted) return
setWrite(can("mm:network:write"))
setApprove(can("mm:mcp:approve"))
await load(controller.signal)
}).catch(error => { if (!controller.signal.aborted) setError(describe(error)) })
setLoading(true)
setError("")
return load(controller.signal)
})
.catch(error => { if (!controller.signal.aborted) setError(describe(error)) })
.finally(() => { if (!controller.signal.aborted) setLoading(false) })
return () => controller.abort()
// Load only when the project source changes.
// Reload when the project data source changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [backendUrl, mode, prefsHydrated])
const rows = useMemo(() => segments.filter(segment => segment.configuration.name.includes(filter.toLowerCase().trim())), [filter, segments])
function open(segment: IxSegment | null) {
setSelected(segment)
setBody(segment ? json(segment.configuration) : "")
setPreview(null)
useEffect(() => {
if (focusAfterNavigation.current) {
focusAfterNavigation.current = false
heading.current?.focus()
}
}, [inDetail])
const rows = segments.filter(segment => segment.configuration.name.includes(filter.trim().toLowerCase()))
const enabledNodes = nodes.filter(node => node.enabled)
const live = prefsHydrated && mode === "live"
const canCreate = live && write && !loading && enabledNodes.length > 0
const savedConfiguration = selected ? json(selected.configuration) : null
const dirty = (advanced ?? json(draft)) !== savedConfiguration
const canPlan = live && write && selected !== null && selected.appliedRevision !== selected.revision && !dirty
function invalidateReview() {
setPlan(null)
setObservations([])
setLinux("")
setNotice("")
}
function open(segment: IxSegment | null) {
focusAfterNavigation.current = !inDetail
setSelected(segment)
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
setAdvanced(null)
setObservations(null)
setLinux(null)
setLinuxBindings([])
setTab("configuration")
setError("")
setEditing(true)
invalidateReview()
}
function close() {
focusAfterNavigation.current = true
setDraft(null)
setError("")
setNotice("")
}
function change(): IxChange {
const configuration = ixSegmentConfigurationSchema.parse(JSON.parse(body))
const configuration = ixSegmentConfigurationSchema.parse(advanced === null ? draft : JSON.parse(advanced))
return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration }
}
async function perform(work: () => Promise<void>) {
setBusy(true)
setError("")
setNotice("")
try { await work() } catch (error) { setError(describe(error)) }
finally { setBusy(false) }
}
async function save() {
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
open(segment)
await load()
}
async function observe() {
if (!selected) return
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
setObservations(sites)
setTab("routes")
setSegments(current => current.some(item => item.id === segment.id)
? current.map(item => item.id === segment.id ? segment : item)
: [segment, ...current])
setNotice("Черновик сохранён")
}
async function prepare() {
if (!selected || !canPlan) return
setPlan(null)
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/plan", post({ revision: selected.revision })))
}
async function apply() {
if (!selected || !plan || !canPlan) return
setPlan(null)
try {
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest }))
setSelected(segment)
setDraft(segment.configuration)
setAdvanced(null)
setObservations(null)
setLinux(null)
setLinuxBindings([])
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
setNotice("Конфигурация IX применена")
} catch (error) {
throw new Error(describe(error) + " Проверьте состояние сегмента перед повторным применением.")
}
}
async function observe() {
if (!selected?.appliedRevision) return
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
setObservations(sites)
}
async function loadLinuxBindings() {
if (!selected) return
setLinux(null)
setLinuxBindings([])
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${selected.id}/linux`)
setLinuxBindings(items)
}
async function exportLinux(binding: IxLinuxBinding) {
if (!selected) return
setLinux(null)
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
setLinux({ ...binding, ...access })
}
function showTab(next: Tab) {
if (next === tab || busy) return
setError("")
setTab(next)
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
}
const listEmpty = error ? "Не удалось загрузить список" :
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
!live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node."
return <>
<PageHeader crumbs={[{ label: "Сеть" }, { label: "Точки обмена трафиком" }]} />
<div className="mx-auto flex w-full max-w-6xl flex-1 flex-col gap-6 p-4 md:p-6">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-2xl font-semibold tracking-tight">Точки обмена трафиком</h1>
<p className="mt-1 text-sm text-muted-foreground">IX-сегменты, маршруты и BGP-политики в отдельных VRF.</p>
</div>
<div className="flex gap-2">
<Button variant="outline" size="icon" disabled={busy || mode !== "live"} aria-label="Обновить список" onClick={() => void perform(() => load())}><RefreshCwIcon /></Button>
{write && <Button onClick={() => open(null)} disabled={busy}><PlusIcon />Добавить сегмент</Button>}
</div>
</div>
{error && <p role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{error}</p>}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
{[{ name: "Узлы IX", count: nodes.length }, { name: "Сегменты", count: segments.length }, { name: "Применённые ревизии", count: segments.filter(segment => segment.appliedRevision === segment.revision).length }].map(item =>
<div key={item.name} className="rounded-lg border bg-card p-4">
<div className="text-sm text-muted-foreground">{item.name}</div>
<div className="mt-1 text-2xl font-semibold tabular-nums">{item.count}</div>
</div>
)}
</div>
<section className="flex flex-col gap-3" aria-label="IX-сегменты">
<Input aria-label="Поиск сегментов" placeholder="Найти сегмент" className="max-w-xs" value={filter} onChange={event => setFilter(event.target.value)} />
{rows.length ? <SegmentGrid rows={rows} open={open} /> :
<EmptyState icon={<NetworkIcon className="size-4" />} title={filter ? "Сегменты не найдены" : "Нет IX-сегментов"}
description={mode !== "live" ? "Сегменты доступны при подключении к серверу." : "Добавьте сервер типа IX Node, чтобы создать сегмент."} />}
</section>
{editing && <section className="flex flex-col gap-4 rounded-lg border bg-card p-4" aria-label="Карточка IX">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold">{selected?.configuration.name ?? "Новый сегмент"}</h2>
<Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Закрыть</Button>
</div>
<div className="flex flex-wrap gap-2">
<Button size="sm" variant={tab === "configuration" ? "secondary" : "ghost"} onClick={() => setTab("configuration")}>Конфигурация</Button>
<Button size="sm" variant={tab === "routes" ? "secondary" : "ghost"} disabled={!selected?.appliedRevision || busy} onClick={() => void perform(observe)}>Маршруты и BGP</Button>
<Button size="sm" variant={tab === "changes" ? "secondary" : "ghost"} disabled={!preview && !plan} onClick={() => setTab("changes")}>Изменения</Button>
</div>
{tab === "configuration" && <>
{!body && <div className="grid gap-3 sm:grid-cols-2">
<div className="grid gap-2"><Label htmlFor="ix-name">Имя сегмента</Label><Input id="ix-name" placeholder="compute" value={name} onChange={event => setName(event.target.value)} /></div>
<div className="grid gap-2"><Label htmlFor="ix-site">Площадка</Label><select id="ix-site" className="h-9 rounded-md border bg-background px-3 text-sm" value={nodeId} onChange={event => setNodeId(event.target.value)}>
<option value="">Выберите IX Node</option>
{nodes.filter(node => node.enabled).map(node => <option key={node.id} value={node.id}>{node.name || node.id}</option>)}
</select></div>
<div className="grid gap-2"><Label htmlFor="ix-asn">Локальный ASN</Label><Input id="ix-asn" inputMode="numeric" value={asn} onChange={event => setAsn(event.target.value)} /></div>
<div className="grid gap-2"><Label htmlFor="ix-router-id">Router ID</Label><Input id="ix-router-id" placeholder="192.0.2.10" value={routerId} onChange={event => setRouterId(event.target.value)} /></div>
<Button variant="outline" disabled={!nodeId || !name || !routerId} onClick={() => void perform(async () => {
setBody(json(ixSegmentConfigurationSchema.parse({ name, sites: [{ serverId: Number(nodeId), autonomousSystem: Number(asn), routerId }] })))
})}>Подготовить конфигурацию</Button>
<Link className={buttonVariants({ variant: "link" })} href="/servers">Открыть каталог серверов</Link>
</div>}
{body && <div className="grid gap-2">
<Label htmlFor="ix-configuration">Конфигурация сегмента</Label>
<Textarea id="ix-configuration" spellCheck={false} readOnly={!write} rows={13} className="font-mono" value={body} onChange={event => {
setBody(event.target.value); setPlan(null); setPreview(null)
}} />
</div>}
{body && write && <div className="flex flex-wrap items-end gap-2">
<Button onClick={() => void perform(save)} disabled={busy}>Сохранить черновик</Button>
<Button variant="outline" disabled={busy} onClick={() => void perform(async () => {
const result = await requestJson<{ objects: IxRouterObject[] }>(backendUrl, "/api/ix/preview", post(change()))
setPreview(result.objects); setTab("changes")
})}>Предпросмотр</Button>
<div className="grid gap-2"><Label htmlFor="ix-connection">Подключение MCP</Label><select id="ix-connection" className="h-9 rounded-md border bg-background px-3 text-sm" value={connectionId} onChange={event => setConnectionId(event.target.value)}>
<option value="">Выберите подключение</option>
{connections.map(connection => <option key={connection.id} value={connection.id}>{connection.name}</option>)}
</select></div>
<Button variant="outline" disabled={!connectionId || busy} onClick={() => void perform(async () => {
setPlan(await requestJson<Plan>(backendUrl, "/api/mcp/ix/plan", post({ connectionId, change: change() })))
setTab("changes")
})}>Подготовить план MCP</Button>
</div>}
</>}
{tab === "changes" && <>
{preview && <div className="grid gap-2"><p className="text-sm">{preview.length} объектов в желаемой конфигурации</p>
<pre className="max-h-96 overflow-auto rounded-md border bg-muted/30 p-3 text-sm">{json(preview)}</pre></div>}
{plan && <div className="flex flex-wrap items-center gap-2">
<Badge variant="info-light">{plan.state}</Badge>
<span className="text-sm text-muted-foreground">{plan.planId}</span>
<Link className={buttonVariants({ variant: "link" })} href="/mcp">Планы и операции</Link>
{plan.state === "awaiting-approval" && approve && <Button variant="outline" disabled={busy} onClick={() => void perform(async () => {
await mcpApi(backendUrl).decision(plan.planId, true)
setPlan({ ...plan, state: "approved" })
})}>Подтвердить</Button>}
{["draft", "approved"].includes(plan.state) && <Button disabled={busy} onClick={() => void perform(async () => {
const result = await mcpApi(backendUrl).apply(plan.planId)
setPlan({ ...plan, state: result.state })
})}>Применить план</Button>}
</div>}
</>}
{tab === "routes" && <div className="grid gap-4">
{selected?.configuration.sites.flatMap(site => site.interfaces.filter(binding => binding.provisionWireguard?.hubEndpoint).map(binding =>
<Button key={site.serverId + ":" + binding.name} size="sm" variant="outline" className="w-fit" disabled={busy} onClick={() => void perform(async () => {
const query = new URLSearchParams({ serverId: String(site.serverId), interfaceName: binding.name })
const result = await requestJson<{ template: string }>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
setLinux(result.template)
})}>Конфигурация Linux · {binding.name}</Button>
))}
{linux && <pre className="overflow-auto rounded-md border bg-muted/30 p-3 text-sm">{linux}</pre>}
{observations.map(site => <div key={site.serverId} className="grid gap-2">
<div className="flex flex-wrap justify-between gap-2 text-sm">
<span className="font-medium">{nodes.find(node => node.id === site.serverId)?.name || site.serverId}</span>
<span className="text-muted-foreground">{new Date(site.observedAt).toLocaleString()}</span>
<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} />
<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}>
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
<ArrowLeftIcon aria-hidden />Все сегменты
</Button>}
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h1 ref={heading} tabIndex={-1} className="text-xl font-semibold tracking-tight wrap-anywhere md:text-2xl">
{inDetail ? selected?.configuration.name ?? "Новый сегмент" : title}
</h1>
{inDetail && selected && <SegmentStatus segment={selected} />}
</div>
{site.available ? <>
<p className="text-sm text-muted-foreground">Активные BGP-сессии {site.neighbors.filter(peer => peer.established).length} из {site.neighbors.length}</p>
<div className="overflow-x-auto"><table className="w-full text-left text-sm">
<thead><tr className="border-b"><th className="p-2">Префикс</th><th className="p-2">Шлюз</th><th className="p-2">Фактический next hop</th><th className="p-2">Активен</th></tr></thead>
<tbody>{site.routes.map((route, index) => <tr key={route.prefix + ":" + index} className="border-b">
<td className="p-2 font-mono">{route.prefix}</td><td className="p-2">{route.gateway || "—"}</td>
<td className="p-2">{route.immediateGateway ?? "Не подтверждён"}</td><td className="p-2">{route.active ? "Да" : "Нет"}</td>
</tr>)}</tbody>
</table></div>
</> : <Badge variant="warning-light">Состояние недоступно</Badge>}
</div>)}
</div>}
</section>}
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
</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>
{canCreate && <Button type="button" size="sm" onClick={() => open(null)} disabled={busy}><PlusIcon aria-hidden />Добавить сегмент</Button>}
</div>}
</div>
{error && <Alert variant="destructive"><CircleAlertIcon aria-hidden /><AlertTitle>Ошибка IX</AlertTitle><AlertDescription className="wrap-anywhere">{error}</AlertDescription></Alert>}
{notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
{!draft ? <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<div><FrameTitle>Сегменты</FrameTitle><FrameDescription>{live && !loading ? `Найдено: ${rows.length}` : ""}</FrameDescription></div>
<Input type="search" aria-label="Поиск сегментов" placeholder="Найти сегмент" className="w-full sm:w-56"
value={filter} onChange={event => setFilter(event.target.value)} />
</FrameHeader>
<FramePanel className="min-w-0 p-0">
<div className="overflow-x-auto">
<SegmentGrid rows={rows} nodes={nodes} loading={!prefsHydrated || (live && loading)} open={open} empty={
<EmptyState icon={<NetworkIcon aria-hidden />} title={listEmpty} description={listDescription}
action={live && !filter.trim() && !error && enabledNodes.length === 0 ? <Button render={<Link href="/servers" />} nativeButton={false} size="sm" variant="outline">Открыть серверы</Button> : undefined} />
} />
</div>
</FramePanel>
</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="routes">Маршруты и BGP</TabsTrigger>
<TabsTrigger value="changes">План изменений</TabsTrigger>
</TabsList>
</div>
<TabsContent value="configuration" className="grid min-w-0 gap-3">
{advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} peers={peers} readOnly={!live || !write || busy}
change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm">
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
<FramePanel>
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
className="font-mono" value={advanced} onChange={event => { setAdvanced(event.target.value); invalidateReview() }} />
</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 () => {
setDraft(change().configuration)
setAdvanced(null)
})}>К форме</Button>}
</div>
</TabsContent>
<TabsContent value="routes" className="grid min-w-0 gap-3">
{!selected?.appliedRevision ? <EmptyState title="Конфигурация ещё не применена"
description="Маршруты и BGP-сессии появятся после применения плана." className="py-8" /> : <>
<div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
<RefreshCwIcon aria-hidden />Обновить состояние
</Button>
</div>
{busy && observations === null && <Skeleton className="h-28 w-full" role="status" aria-label="Загрузка маршрутов" />}
{observations?.map(site => <RouteGrid key={site.serverId} observation={site} nodes={nodes} />)}
</>}
</TabsContent>
<TabsContent value="linux" className="grid min-w-0 gap-3">
<Frame spacing="sm">
<FrameHeader>
<FrameTitle>Доступ для Linux-серверов</FrameTitle>
<FrameDescription>Выдайте каждому серверу отдельное подключение из применённой ревизии сегмента.</FrameDescription>
</FrameHeader>
<FramePanel className="grid min-w-0 gap-3">
{write && <div className="grid gap-2 text-sm text-muted-foreground">
<p>В «Конфигурации» добавьте подключение на нужной площадке и выберите «Внешний сервер» в поле «Удалённый узел».</p>
<p>Для WireGuard включите создание пира и укажите публичный ключ Linux, адреса, внешний адрес IX и разрешённые префиксы. Для GRE привяжите выделенный туннель с IKEv2/IPsec и отдельным PSK.</p>
<Button type="button" variant="outline" size="sm" className="w-fit" disabled={busy}
onClick={() => showTab("configuration")}>Открыть подключения</Button>
</div>}
{busy && linuxBindings.length === 0 ? <Skeleton className="h-12 w-full" role="status" aria-label="Загрузка Linux-клиентов" />
: !error && linuxBindings.length === 0 ? <p className="text-sm text-muted-foreground">В применённой ревизии пока нет подключений Linux.</p>
: linuxBindings.map(binding => <div key={binding.serverId + ":" + binding.interfaceName}
className="flex min-w-0 flex-wrap items-center justify-between gap-2 border-t pt-2">
<div className="min-w-0 text-sm">
<p className="wrap-anywhere font-medium">{binding.interfaceName}</p>
<p className="wrap-anywhere text-muted-foreground">{binding.kind === "wireguard" ? "WireGuard" : "GRE/IPsec"} · {nodeLabel(nodes, binding.serverId)}</p>
</div>
<Button type="button" size="sm" variant="outline" disabled={busy}
aria-label={"Получить конфиг " + binding.interfaceName} onClick={() => void perform(() => exportLinux(binding))}>Получить конфиг</Button>
</div>)}
</FramePanel>
</Frame>
{linux && <Frame spacing="sm">
<FrameHeader>
<FrameTitle>Конфигурация Linux · {linux.interfaceName}</FrameTitle>
<FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription>
</FrameHeader>
<FramePanel className="grid min-w-0 gap-3">
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard"
? "Подставьте приватный ключ, сгенерированный на Linux. Шаблон wg-quick оставляет управление маршрутами на стороне Linux."
: "Подставьте PSK этого клиента и подключите файл к конфигурации strongSwan. Сверьте параметры IKE с подготовленным узлом IX."}</p>
<pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>
<a className={buttonVariants({ variant: "outline", size: "sm", className: "w-fit" })}
href={"data:text/plain;charset=utf-8," + encodeURIComponent(linux.template)} download={linux.filename}>Скачать {linux.filename}</a>
{linux.setup && <pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>}
{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}
{linux.bgp.advertisedPrefixes.length > 0 && <> · анонсы Linux {linux.bgp.advertisedPrefixes.join(", ")}</>}
</p>}
</FramePanel>
</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>
: <Button type="button" size="sm" variant="outline" className="w-fit" disabled={!canPlan || busy}
onClick={() => void perform(prepare)}>Построить предпросмотр</Button>}
{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>}
{plan.changes.length > 0 && <ul className="max-h-80 min-w-0 divide-y overflow-auto rounded-md border">
{plan.changes.map((operation, index) => <li key={index} className="min-w-0 p-2.5 text-sm">
<details className="min-w-0">
<summary className="cursor-pointer wrap-anywhere">{actionLabels[operation.action]} · {nodeLabel(nodes, operation.serverId)} · <code>{operation.path}</code>
{operation.target && <> · <code>{operation.target}</code></>}
</summary>
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 py-2 text-xs">
{operation.placeBefore && <><dt className="text-muted-foreground">Перед объектом</dt><dd className="font-mono">{operation.placeBefore}</dd></>}
{Object.entries(operation.fields).map(([key, value]) => <div key={key} className="contents">
<dt className="max-w-32 wrap-anywhere text-muted-foreground">{key}</dt>
<dd className="wrap-anywhere font-mono">{value}</dd>
</div>)}
</dl>
</details>
</li>)}
</ul>}
<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>}
</div>
</div>
</>
}
+25 -13
View File
@@ -38,6 +38,8 @@ import { cn } from "@/lib/utils"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { DataPageCard } from "@/components/data-page-card"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import { Field, FieldTitle } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Sheet, SheetContent, SheetHeader, SheetTitle,
@@ -772,19 +774,29 @@ function ServersPageContent() {
value={form.name} onChange={e => set("name", e.target.value)} />
</FormField>
<FormField label="Тип узла" required>
<SegmentedControl
className="max-w-full flex-wrap"
value={form.type}
onChange={v => set("type", v)}
options={[
{ value: "home-router", label: "Home Router" },
{ value: "jump-host", label: "JumpHost" },
{ value: "exit-node", label: "Exit Node" },
{ value: "ix-node", label: "IX Node" },
]}
/>
</FormField>
<Field>
<FieldTitle id="server-node-type-label">Тип узла <span aria-hidden className="text-destructive">*</span></FieldTitle>
<ButtonGroup aria-labelledby="server-node-type-label" className="max-w-full">
{([
["home-router", "Home Router"],
["jump-host", "JumpHost"],
["exit-node", "Exit Node"],
["ix-node", "IX Node"],
] as const).map(([value, label]) => (
<Button
key={value}
type="button"
variant={form.type === value ? "default" : "outline"}
size="sm"
aria-pressed={form.type === value}
className="h-auto min-h-7 min-w-0 flex-auto shrink whitespace-normal py-1"
onClick={() => set("type", value)}
>
{label}
</Button>
))}
</ButtonGroup>
</Field>
<div className="grid grid-cols-2 gap-3">
<FormField label="Площадка" required hint="MSK, SPB, FRA…">
+14
View File
@@ -1604,6 +1604,20 @@
"operations": [],
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/plan",
"status": "mediated",
"operations": ["network.ix.configure"],
"reason": "Предпросмотр сохранённой ревизии для оператора. MCP строит отдельный план через общий сервис IX."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/apply",
"status": "mediated",
"operations": ["network.ix.configure"],
"reason": "Пользователь WebUI подтверждает просмотренную ревизию. MCP применяет свой подтверждённый план через общий исполнитель IX."
},
{
"method": "POST",
"path": "/api/ix/segments",
+171
View File
@@ -0,0 +1,171 @@
import assert from "node:assert/strict"
import { randomBytes, randomUUID } from "node:crypto"
import { mkdtemp } from "node:fs/promises"
import { createServer } from "node:http"
import { tmpdir } from "node:os"
import { join } from "node:path"
import EmbeddedPostgres from "embedded-postgres"
const dir = await mkdtemp(join(tmpdir(), "mm-ix-web-"))
const socket = createServer()
await new Promise<void>(resolve => socket.listen(0, "127.0.0.1", resolve))
const pgPort = (socket.address() as { port: number }).port
await new Promise<void>(resolve => socket.close(() => resolve()))
const password = randomBytes(24).toString("hex")
const pg = new EmbeddedPostgres({ databaseDir: join(dir, "pg"), user: "ixlab", password,
port: pgPort, persistent: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], onLog() {} })
Object.assign(process.env, {
NODE_ENV: "test", DATABASE_URL: `postgres://ixlab:${password}@127.0.0.1:${pgPort}/postgres`,
MCP_STATE_DIR: join(dir, "state"), AUTH_REQUIRED: "true", AUTH_JWT_SECRET: randomBytes(32).toString("hex"),
DATABASE_PATH: join(dir, "no-legacy.sqlite"),
})
await pg.initialise()
await pg.start()
const rows: Record<string, Record<string, string>[]> = {
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }],
"/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }],
"/ip/ipsec/policy": [{ ".id": "*A1", "src-address": "192.0.2.20/32", "dst-address": "192.0.2.21/32",
protocol: "gre", action: "encrypt", level: "require", tunnel: "false", disabled: "false" }],
}
let writes = 0
const router = createServer(async (request, response) => {
try {
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
let result: unknown
if (request.method === "GET") result = rows[path] ?? []
else if (request.method === "PUT") {
let raw = ""
for await (const chunk of request) raw += chunk
const { "place-before": place, ...fields } = JSON.parse(raw)
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": "B".repeat(43) + "=" }),
".id": "*" + (++writes + 1).toString(16).toUpperCase() }
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") {
rows["/interface"].push({ ".id": row[".id"], name: row.name,
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
}
result = row
} else throw Error("Unexpected native verb: " + request.method)
response.setHeader("content-type", "application/json")
response.end(JSON.stringify(result))
} catch (error) {
response.statusCode = 500
response.end(JSON.stringify({ error: String(error) }))
}
})
const { initDatabase } = await import("../../src/db/bootstrap.js")
const { pool } = await import("../../src/db/index.js")
let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined
try {
await initDatabase()
assert.equal((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled, false)
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
const port = (router.address() as { port: number }).port
const { rows: [server] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-ix','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`, [port])
const { buildApp } = await import("../../src/index.js")
const { env } = await import("../../src/config.js")
app = await buildApp({ logger: false, startScheduler: false })
const origin = await app.listen({ host: "127.0.0.1", port: 0 })
const token = (owner: string, permission: string) => app!.jwt.sign({ iss: env.authIssuer, sub: owner,
apps: ["mm"], permissions: [permission], iat: Math.floor(Date.now() / 1000) - 1, exp: Math.floor(Date.now() / 1000) + 600 })
const writer = token("ix-web-owner", "mm:network:write")
const reader = token("ix-web-reader", "mm:network:read")
const otherWriter = token("ix-web-other-owner", "mm:network:write")
async function post(path: string, payload: object, status: number, jwt = writer) {
const reply = await fetch(origin + "/api/ix/segments" + path, { method: "POST",
headers: { "content-type": "application/json", ...(jwt ? { authorization: "Bearer " + jwt } : {}) },
body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000) })
const data = await reply.json()
assert.equal(reply.status, status, JSON.stringify(data))
return data
}
const configuration = { name: "ix-web-fixture", sites: [{ serverId: Number(server.id),
autonomousSystem: 64512, routerId: "192.0.2.5", interfaces: [{ name: "wg-ix-web", kind: "wireguard",
prefixes: ["2001:db8:12::/48"], provisionWireguard: { peerPublicKey: "A".repeat(43) + "=",
listenPort: 51820, localAddress: "10.20.30.1/30", peerAddress: "10.20.30.2", hubEndpoint: "192.0.2.20" } },
{ name: "gre-client", kind: "gre-ipsec", localEndpoint: "192.0.2.20", endpoint: "192.0.2.21" }] }] }
const { segment } = await post("", { revision: 0, configuration }, 200)
assert.equal(segment.revision, 1)
assert.equal(segment.appliedRevision, null)
const path = "/" + segment.id
const linux = async (name?: string, status = 200) => {
const query = name ? "?" + new URLSearchParams({ serverId: String(server.id), interfaceName: name }) : ""
const response = await fetch(origin + "/api/ix/segments" + path + "/linux" + query, { headers: { authorization: "Bearer " + reader } })
const body = await response.json()
assert.equal(response.status, status, JSON.stringify(body))
return body
}
assert.deepEqual(await linux(), { revision: null, items: [] })
const { digest, changes } = await post(path + "/plan", { revision: 1 }, 200)
assert(changes.some((step: { path: string }) => step.path === "/interface/wireguard/peers"))
await post(path + "/apply", { revision: 1, digest }, 401, "")
await post(path + "/apply", { revision: 1, digest }, 403, reader)
await post(path + "/apply", { revision: 1, digest }, 409, otherWriter)
await post(path + "/apply", { revision: 1, digest: "0".repeat(64) }, 409)
rows["/interface"].push({ ".id": "*F0", name: "test-drift", type: "ether" })
await post(path + "/apply", { revision: 1, digest }, 409)
assert.equal(writes, 0)
const fresh = await post(path + "/plan", { revision: 1 }, 200)
const protectionId = randomUUID()
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES ($1,$2,'ix-web-owner')",
[protectionId, { kind: "server", id: String(server.id), protection: "deny" }])
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
assert.equal(writes, 0)
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protectionId])
const applied = await post(path + "/apply", { revision: 1, digest: fresh.digest }, 200)
assert.equal(applied.segment.appliedRevision, 2)
assert.equal(applied.result.configurationVerified, true)
assert.equal(applied.result.forwardingVerified, false)
const resultWrites = writes
assert.equal(resultWrites, changes.length)
const clients = await linux()
assert.equal(clients.revision, 2)
assert.deepEqual(clients.items.map((item: { kind: string }) => item.kind), ["wireguard", "gre-ipsec"])
const wg = await linux("wg-ix-web")
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
assert.match(wg.template, /Table = off/)
assert(!wg.template.includes("A".repeat(43)))
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\]/)
assert.match(gre.template, /mode = transport/)
assert.match(gre.setup, /mode gre local 192\.0\.2\.21 remote 192\.0\.2\.20/)
rows["/ip/ipsec/policy"][0].disabled = "true"
await linux("gre-client", 409)
rows["/ip/ipsec/policy"][0].disabled = "false"
rows["/interface/wireguard/peers"][0].disabled = "true"
await linux("wg-ix-web", 409)
delete rows["/interface/wireguard/peers"][0].disabled
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
assert.equal(writes, resultWrites)
const next = await post("", { id: segment.id, revision: 2, configuration: { ...configuration,
sites: [{ ...configuration.sites[0], discardNetworks: ["2001:db8:ff::/48"] }] } }, 200)
assert.equal(next.segment.appliedRevision, 2)
assert.equal((await linux("wg-ix-web")).revision, 2)
const members = rows["/interface/list/member"]
members.push({ ".id": "*FE", list: rows["/interface/list"][0].name, interface: "test-drift" })
const foreign = await post(path + "/plan", { revision: 3 }, 409)
assert.match(foreign.error, /посторонний интерфейс/)
members.pop()
const nextPlan = await post(path + "/plan", { revision: 3 }, 200)
await post(path + "/apply", { revision: 3, digest: nextPlan.digest }, 200)
assert(rows["/ipv6/route"].some(row => row["dst-address"] === "2001:db8:ff::/48"))
const { rows: [audit] } = await pool.query(`SELECT count(*)::int AS n FROM mcp_audit
WHERE actor_id='ix-web-owner' AND action='configuration.acknowledged' AND connection_id IS NULL`)
assert.equal(audit.n, writes)
const { rows: [connections] } = await pool.query("SELECT count(*)::int AS n FROM mcp_connections")
assert.equal(connections.n, 0)
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 }))
} finally {
await app?.close()
await new Promise<void>(resolve => router.close(() => resolve()))
await pool.end()
await pg.stop()
}
+65 -7
View File
@@ -1,9 +1,12 @@
import { randomUUID } from "node:crypto"
import type { FastifyPluginAsync } from "fastify"
import { z } from "zod"
import { ixChangeSchema } from "@mmapp/contracts/internet-exchange"
import { ixChangeSchema, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
import { fingerprint, McpError } from "../modules/mcp/security.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
import { withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { observeIxSegment, readIxLinuxClient } from "../services/internet-exchange-execution.js"
import { withConfigurationActor } from "../services/config-mutation-policy.js"
import { applyIxChange, listIxLinuxClients, observeIxSegment, prepareIxChange, readIxLinuxClient } from "../services/internet-exchange-execution.js"
import { compileIxConfiguration, IxConflict } from "../services/internet-exchange-plan.js"
import { assertIxRevision, listIxSegments, readIxSegment, writeIxRevision } from "../services/internet-exchange-store.js"
@@ -11,13 +14,33 @@ const paging = z.object({
limit: z.coerce.number().int().min(1).max(100).default(25),
offset: z.coerce.number().int().min(0).max(1000000).default(0),
}).strict()
const segmentParams = z.object({ id: z.string().uuid() })
const planRequest = z.object({ revision: z.number().int().positive() }).strict()
const applyRequest = planRequest.extend({ digest: z.string().regex(/^[a-f0-9]{64}$/) })
async function prepareSavedRevision(id: string, revision: number) {
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(segment, revision)
if (segment.appliedRevision === revision) throw new IxConflict("Эта ревизия IX уже применена")
return prepareIxChange({ id, revision, configuration: segment.configuration })
}
function reviewDigest(prepared: Awaited<ReturnType<typeof prepareSavedRevision>>, actorId: string) {
return fingerprint({ operation: "ix.web.apply", actorId, change: prepared.change, before: prepared.before, tasks: prepared.native.tasks })
}
const ixRoutes: FastifyPluginAsync = async app => {
app.setErrorHandler((error, request, reply) => {
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message })
if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" })
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
return reply.code(503).send({ error: "Хранилище IX недоступно" })
const errorMessage = request.routeOptions.url?.endsWith("/apply")
? "Результат применения IX не подтверждён"
: "Не удалось получить данные для операции IX"
return reply.code(503).send({ error: errorMessage })
})
app.get("/ix/segments", async request => {
const input = paging.parse(request.query)
@@ -25,8 +48,11 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.get("/ix/nodes", async () => {
const { pool } = await import("../db/index.js")
const { rows } = await pool.query("SELECT id,name,site,country,enabled FROM servers WHERE type='ix-node' ORDER BY name,id LIMIT 500")
return { items: rows }
const [nodes, peers] = await Promise.all([
pool.query("SELECT id,name,site,country,enabled FROM servers WHERE type='ix-node' ORDER BY name,id LIMIT 500"),
pool.query("SELECT id,name,site,country,enabled FROM servers ORDER BY name,id LIMIT 1000"),
])
return { items: nodes.rows, peers: peers.rows }
})
app.get("/ix/topology", async () => {
const segments = await listIxSegments(100, 0)
@@ -44,10 +70,13 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.get("/ix/segments/:id/linux", async request => {
const { id } = z.object({ id: z.string().uuid() }).parse(request.params)
const { serverId, interfaceName } = z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict().parse(request.query)
const query = z.union([
z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(),
z.object({}).strict(),
]).parse(request.query)
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return readIxLinuxClient(segment, serverId, interfaceName)
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName) : listIxLinuxClients(segment)
})
app.post("/ix/segments", async request => {
const input = ixChangeSchema.parse(request.body)
@@ -65,6 +94,35 @@ const ixRoutes: FastifyPluginAsync = async app => {
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
return { id, objects: compileIxConfiguration(id, input.configuration) }
})
app.post("/ix/segments/:id/plan", async (request): Promise<IxWebPlan> => {
const { id } = segmentParams.parse(request.params)
const { revision } = planRequest.parse(request.body)
const prepared = await prepareSavedRevision(id, revision)
return {
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator"),
changes: prepared.native.tasks.map(task => ({
serverId: task.serverId, path: task.path,
action: task.fields ? task.rosId ? "update" : "create" : "delete",
target: task.before?.name ?? task.before?.comment ?? task.fields?.name ?? task.fields?.comment ?? task.rosId,
placeBefore: task.placeBefore,
fields: task.fields ?? Object.fromEntries(Object.entries(task.before ?? {}).filter(([key]) => ["name", "comment", "dst-address", "chain"].includes(key))),
})),
}
})
app.post("/ix/segments/:id/apply", async request => {
const { id } = segmentParams.parse(request.params)
const { revision, digest } = applyRequest.parse(request.body)
const scope = { deadlineAt: Date.now() + 180_000 }
const token = await captureVerifiedRestRequest(request, scope)
const inspect = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = await inspect()
const prepared = await prepareSavedRevision(id, revision)
if (digest !== reviewDigest(prepared, ownerId)) throw new IxConflict("План IX устарел. Постройте новый предпросмотр")
const result = await withConfigurationActor(ownerId, () => applyIxChange(id, prepared.change, prepared.before, ownerId, async () => { await inspect() }))
return { segment: await readIxSegment(result.segmentId), result }
})
}
export default ixRoutes
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto"
import { isIP } from "node:net"
import type { IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
@@ -5,6 +6,16 @@ import { IxConflict } from "./internet-exchange-plan.js"
type Binding = IxSite["interfaces"][number]
export function ixLinuxBindingKind(binding: Binding) {
if (binding.kind === "wireguard" && binding.provisionWireguard?.hubEndpoint) return "wireguard"
if (binding.kind === "gre-ipsec" && binding.localEndpoint && binding.endpoint) return "gre-ipsec"
return null
}
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Binding) {
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
}
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[]) {
const config = binding.provisionWireguard
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
@@ -28,3 +39,62 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
"",
].join("\n")
}
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }) {
const hub = binding.localEndpoint
const client = binding.endpoint
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
throw new IxConflict("Для Linux GRE/IPsec нужны два разных внешних IPv4-адреса")
}
const id = ixLinuxInterfaceName("ixg", serverId, binding)
const hostMask = bgp && isIP(bgp.address) === 6 ? "/128" : "/32"
return {
filename: id + ".conf",
template: [
"# Сверьте предложения и идентификаторы IKE с профилем узла IX.",
"connections {",
" " + id + " {",
" version = 2",
" local_addrs = " + client,
" remote_addrs = " + hub,
" proposals = aes256-sha256-modp2048",
" mobike = no",
" local {",
" auth = psk",
" id = " + client,
" }",
" remote {",
" auth = psk",
" id = " + hub,
" }",
" children {",
" " + id + " {",
" local_ts = " + client + "/32[47]",
" remote_ts = " + hub + "/32[47]",
" mode = transport",
" esp_proposals = aes256-sha256-modp2048",
" start_action = trap",
" }",
" }",
" }",
"}",
"secrets {",
" ike-" + id + " {",
" id-1 = " + client,
" id-2 = " + hub,
' secret = "<PSK этого клиента>"',
" }",
"}",
"",
].join("\n"),
setup: [
"swanctl --load-all",
"swanctl --initiate --child " + id,
"# Создайте GRE после успешного установления IPsec.",
"ip tunnel add " + id + " mode gre local " + client + " remote " + hub,
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
"ip link set " + id + " up",
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
].join("\n"),
}
}
@@ -55,3 +55,31 @@ test("RouterOS REST host matches allow only the equivalent explicit host length"
assert.throws(() => planIxNative(id, [rule], [rule], rows(address + "/" + wider)), /изменён вне операции/)
}
})
test("RouterOS REST encodes an enabled blackhole route as a present empty flag", () => {
const fields = { comment: name + ":default-discard-4", "routing-table": name, "dst-address": "0.0.0.0/0", blackhole: "yes" }
const discard = { ...route, fields }
const { blackhole: _blackhole, ...unflagged } = fields
const observed = (fields: Record<string, string>) => device({ "/ip/route": [{ ".id": "*B", ...fields }] })
assert.deepEqual(planIxNative(id, [discard], [discard], observed({ ...fields, blackhole: "" })), [])
assert.throws(() => planIxNative(id, [discard], [discard], observed(unflagged)), /изменён вне операции/)
assert.throws(() => planIxNative(id, [discard], [discard], observed({ ...fields, blackhole: "false" })), /изменён вне операции/)
})
test("the complete member filter can be added to a legacy applied segment", () => {
const path = "/ip/firewall/filter"
const object = (suffix: string, fields: Record<string, string>) => ({
serverId: 17, path, fields: { comment: name + ":" + suffix, chain: "forward", ...fields },
})
const boundary = object("deny-outside-4", { action: "drop", "in-interface": name })
const allow = object("egress-allow-4", { action: "accept", "in-interface": name, "out-interface-list": name })
const deny = object("egress-deny-4", { action: "drop", "out-interface-list": name })
const objects = [allow, boundary, deny]
const legacy = { ".id": "*B", ...boundary.fields }
assert.deepEqual(planIxNative(id, objects, objects, device({ [path]: [legacy] })).map(task => [task.fields, task.placeBefore]),
[[allow.fields, "*B"], [deny.fields, "*B"]])
assert.throws(() => planIxNative(id, objects, objects, device({ [path]: [{ ".id": "*C", ...allow.fields }, legacy] })),
/предыдущей ревизии IX исчез/)
})
@@ -1,15 +1,15 @@
import { randomUUID } from "node:crypto"
import { isIP } from "node:net"
import { setTimeout as delay } from "node:timers/promises"
import { ixChangeSchema, type IxChange, type IxConfiguration, type IxRouterObject, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { ixChangeSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxRouterObject, type IxSegment, type IxSite, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
import { fingerprint } from "../modules/mcp/security.js"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
import { compileIxConfiguration, IxConflict, ixDeviceIds, ixDiscardInterface, ixNamespace } from "./internet-exchange-plan.js"
import { compileIxConfiguration, IxConflict, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
import { assertIxName, assertIxRevision, assertIxSites, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { MikrotikClient } from "./mikrotik.js"
import { ixWireguardClientTemplate } from "./internet-exchange-client.js"
import { ixGreClientTemplate, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
type NativeRow = Record<string, string>
type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete">
@@ -25,6 +25,8 @@ interface IxNativeChange {
tasks: Task[]
}
const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks })
const routerId = /^\*[a-z\d]+$/i
const marker = (path: string, comment: string) => path + "\0" + comment
const objectMarker = (object: IxRouterObject) => marker(object.path, object.fields.comment)
@@ -32,8 +34,11 @@ const deviceMarker = (object: IxRouterObject) => object.serverId + "\0" + object
const isTrue = (value: unknown) => value === true || value === "true" || value === "yes"
const columns = [".id", "comment", "name", "type", "disabled", "dynamic", "builtin", "interfaces", "routing-table", "dst-address", "gateway", "chain"]
const filterPath = (path: string) => /^\/(ip|ipv6)\/firewall\/(filter|nat)$/.test(path)
const greColumns = [".id", "name", "local-address", "remote-address", "allow-fast-path"]
const ipsecPolicyColumns = [".id", "action", "level", "tunnel", "protocol", "src-address", "dst-address", "disabled", "template"]
function normalize(field: string, value: string | undefined) {
if (field === "blackhole" && value === "") return "yes"
if (["disabled", "advertise", "blackhole", "multihop"].includes(field)) return value === undefined ? null : isTrue(value) ? "yes" : "no"
if (field === "rule") return value?.trim()
if (field === "interfaces") return value?.split(",").sort().join(",")
@@ -63,6 +68,11 @@ function verifyNativeId(row: NativeRow) {
export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[]): Task[] {
const namespace = ixNamespace(id)
const egressObject = (comment = "") => comment.startsWith(namespace + ":egress-")
const withEgressList = new Set(devices.filter(device => Object.values(device.rows).some(rows =>
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
// An older applied revision had no egress list. A partial set still needs reconciliation.
previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId))
const desiredKeys = new Set(desired.map(deviceMarker))
const previousKeys = new Set(previous.map(deviceMarker))
const result: Task[] = []
@@ -108,6 +118,17 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
return result.concat(interfaceCleanup)
}
function verifyEgressMembers(device: NativeDevice, id: string, objects: IxRouterObject[]) {
const path = "/interface/list/member"
const list = ixEgressList(id)
const catalogue = rowsFor(device, "/interface/list").find(row => row.name === list)
const expected = objects.filter(object => object.serverId === device.serverId && object.path === path)
if ([catalogue?.include, catalogue?.exclude].some(value => value && value !== "none") ||
rowsFor(device, path).some(row => row.list === list && (isTrue(row.disabled) || !expected.some(object => matches(row, object.fields))))) {
throw new IxConflict("В списке выходов IX есть посторонний интерфейс")
}
}
async function readRows(client: IpCore, path: string, props: readonly string[]) {
const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") }))
if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) {
@@ -127,9 +148,10 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[]): Promise
fieldsByPath.set(object.path, [...new Set([...(fieldsByPath.get(object.path) ?? columns),
...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])])
}
if (fieldsByPath.has("/interface/list")) fieldsByPath.get("/interface/list")!.push("include", "exclude")
if (objects.some(object => object.fields["ipsec-policy"])) {
fieldsByPath.set("/interface/gre", [".id", "name", "local-address", "remote-address", "allow-fast-path"])
fieldsByPath.set("/ip/ipsec/policy", [".id", "action", "level", "tunnel", "protocol", "src-address", "dst-address", "disabled", "template"])
fieldsByPath.set("/interface/gre", greColumns)
fieldsByPath.set("/ip/ipsec/policy", ipsecPolicyColumns)
}
const rows: Record<string, NativeRow[]> = {}
for (const [path, keys] of fieldsByPath) rows[path] = await readRows(client, path, keys)
@@ -140,6 +162,21 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[]): Promise
return { serverId: server.id, source: fingerprint(server), rows }
}
function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: NativeRow[], policies: NativeRow[]) {
const gre = interfaces.find(row => row.name === binding.name)
const policy = policies.some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint || !policy) {
throw new IxConflict("Для " + binding.name + " не подтверждены адреса и обязательная политика GRE/IPsec")
}
if (!["false", "no"].includes(gre["allow-fast-path"])) {
throw new IxConflict("Отключите FastPath на интерфейсе GRE/IPsec " + binding.name)
}
return gre
}
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[]) {
for (const site of configuration.sites) {
const device = devices.find(entry => entry.serverId === site.serverId)!
@@ -165,17 +202,7 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
}
if (binding.kind === "gre-ipsec") {
const gre = rowsFor(device, "/interface/gre").find(row => row.name === binding.name)
const policy = rowsFor(device, "/ip/ipsec/policy").some(row =>
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint || !policy) {
throw new IxConflict("Для " + binding.name + " не подтверждены адреса и обязательная политика GRE/IPsec")
}
if (!["false", "no"].includes(gre["allow-fast-path"])) {
throw new IxConflict("Отключите FastPath на интерфейсе GRE/IPsec " + binding.name)
}
verifyGreBinding(binding, rowsFor(device, "/interface/gre"), rowsFor(device, "/ip/ipsec/policy"))
}
}
}
@@ -191,6 +218,7 @@ async function prepareNative(id: string, configuration: IxConfiguration, previou
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId)))
}
validateBindings(configuration, id, before)
for (const device of before) verifyEgressMembers(device, id, previous)
for (const old of previousConfiguration?.sites ?? []) {
const next = configuration.sites.find(site => site.serverId === old.serverId)
const device = before.find(device => device.serverId === old.serverId)!
@@ -218,7 +246,7 @@ export async function prepareIxChange(raw: unknown) {
await assertIxSites(change.configuration)
const previous = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
const native = await prepareNative(id, change.configuration, previous)
const before = { revision: current?.revision ?? 0, devices: fingerprint(native.before) }
const before = { revision: current?.revision ?? 0, devices: nativePlanDigest(native) }
const objects = native.before.flatMap(device => [{ kind: "server", id: String(device.serverId), serverId: device.serverId }])
return { id, change, before, native, objects }
}
@@ -228,7 +256,7 @@ export async function currentIxChange(id: string, change: IxChange) {
if (current?.revision !== change.revision && !(current === null && change.revision === 0)) return { revision: current?.revision ?? 0 }
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
const native = await prepareNative(id, change.configuration, applied)
return { revision: current?.revision ?? 0, devices: fingerprint(native.before) }
return { revision: current?.revision ?? 0, devices: nativePlanDigest(native) }
}
export async function reconcileIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, authorize: () => Promise<void>) {
@@ -243,6 +271,8 @@ export async function reconcileIxChange(id: string, change: IxChange, expected:
if (!server?.enabled) return { matchesDesiredState: false, matchesOriginalState: false }
const objects = desired.filter(object => object.serverId === site.serverId)
const observed = await readDevice(server, objects)
try { verifyEgressMembers(observed, id, objects) }
catch { return { matchesDesiredState: false, matchesOriginalState: false } }
matchesDesiredState &&= objects.every(object => {
const row = managedRow(observed, object)
return row && !isTrue(row.invalid) && matches(row, object.fields)
@@ -290,35 +320,69 @@ export async function observeIxSegment(segment: IxSegment): Promise<IxSiteObserv
}))
}
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string) {
export async function listIxLinuxClients(segment: IxSegment) {
const revision = segment.appliedRevision
if (revision === null) return { revision, items: [] }
const configuration = await readIxRevision(segment.id, revision)
const items: IxLinuxBinding[] = configuration.sites.flatMap(site => site.interfaces.flatMap(binding => {
const kind = ixLinuxBindingKind(binding)
return kind && binding.peerServerId === undefined ? [{ serverId: site.serverId, interfaceName: binding.name, kind }] : []
}))
return { revision, items }
}
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string): 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)
const binding = site?.interfaces.find(entry => entry.name === name)
const server = await getServerRowById(serverId)
if (!site || !binding || !server?.enabled || server.type !== "ix-node") throw new IxConflict("Подключение IX не найдено", 404)
const wireguard = await readRows(MikrotikClient.fromServer(server), "/interface/wireguard", ["name", "public-key", "comment"])
const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-"))
const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed")
const clientInfo = {
revision: segment.appliedRevision,
...(peer ? { bgp: { localAs: peer.remoteAs, remoteAs: site.autonomousSystem, neighbor: peer.localAddress, advertisedPrefixes: peer.prefixes } } : {}),
}
const client = MikrotikClient.fromServer(server)
if (binding.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([
readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns),
])
if (isTrue(verifyGreBinding(binding, interfaces, policies).disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer) }
}
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "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 &&
row.comment?.startsWith(ixNamespace(segment.id) + ":wg-peer-") && !isTrue(row.disabled))) {
throw new IxConflict("Пир WireGuard из применённой ревизии отсутствует или отключён")
}
const routes = configuration.sites.flatMap(entry => entry.interfaces
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
const peer = site.neighbors.find(entry => entry.binding === name)
return {
...clientInfo,
kind: "wireguard",
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes),
...(peer ? { bgp: { localAs: peer.remoteAs, remoteAs: site.autonomousSystem, neighbor: peer.localAddress, advertisedPrefixes: peer.prefixes } } : {}),
}
}
export async function applyIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, actorId: string) {
export async function applyIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, actorId: string,
authorize = assertVerifiedConfigurationAccess) {
return withApplicationMutationLock(async () => withConfigMutationLock(await ixTarget(change), async () => {
await assertVerifiedConfigurationAccess()
await authorize()
const current = await readIxSegment(id)
assertIxRevision(current, expected.revision)
await assertIxName(id, change.configuration.name)
await assertIxSites(change.configuration)
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
const native = await prepareNative(id, change.configuration, applied)
if (fingerprint(native.before) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
if (nativePlanDigest(native) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
for (const task of native.tasks) {
await assertVerifiedConfigurationAccess()
await authorize()
const server = await getServerRowById(task.serverId)
if (!server?.enabled || fingerprint(server) !== native.before.find(device => device.serverId === task.serverId)?.source) {
throw new IxConflict("Изменился источник конфигурации IX")
@@ -333,13 +397,13 @@ export async function applyIxChange(id: string, change: IxChange, expected: { re
throw new IxConflict("Объект IX был создан после подготовки плана")
}
if (!task.fields) {
await client.delete(nativePath)
await client.delete(nativePath, undefined, authorize)
if ((await readRows(client, task.path, [".id"])).some(row => row[".id"] === task.rosId)) throw new IxConflict("Удаление объекта IX не подтверждено")
continue
}
const result = task.rosId
? await client.patch<NativeRow>(nativePath, task.fields)
: await client.put<NativeRow>(nativePath, { ...task.fields, ...(task.placeBefore ? { "place-before": task.placeBefore } : {}) })
? await client.patch<NativeRow>(nativePath, task.fields, undefined, authorize)
: await client.put<NativeRow>(nativePath, { ...task.fields, ...(task.placeBefore ? { "place-before": task.placeBefore } : {}) }, undefined, authorize)
const returnedId = task.rosId ?? result?.[".id"]
if (!returnedId || !routerId.test(returnedId)) throw new IxConflict("RouterOS не подтвердил ID объекта IX")
const row = (await readRows(client, task.path, [".id", ...Object.keys(task.fields)])).find(entry => entry[".id"] === returnedId)
@@ -353,19 +417,20 @@ export async function applyIxChange(id: string, change: IxChange, expected: { re
}
}
}
await assertVerifiedConfigurationAccess()
await authorize()
for (const device of native.before) {
const server = await getServerRowById(device.serverId)
if (!server || fingerprint(server) !== device.source) throw new IxConflict("Источник IX изменился во время проверки")
const desired = native.objects.filter(object => object.serverId === device.serverId)
const after = await readDevice(server, desired)
verifyEgressMembers(after, id, desired)
if (rowsFor(after, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) throw new IxConflict("Нарушена изоляция bridge отбрасывания IX")
if (!desired.every(object => {
const row = managedRow(after, object)
return row && !isTrue(row.invalid) && matches(row, object.fields)
})) throw new IxConflict("Итоговая конфигурация IX не совпала с планом")
}
await assertVerifiedConfigurationAccess()
await authorize()
const segment = await writeIxRevision(id, expected.revision, change.configuration, actorId, true)
return { segmentId: segment.id, revision: segment.revision, configurationVerified: true, forwardingVerified: false, changedObjects: native.tasks.length }
}), { waitMs: 30_000 })
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { ixSegmentConfigurationSchema, type IxConfiguration } from "@mmapp/contracts/internet-exchange"
import { compileIxConfiguration, ixDiscardInterface, ixNamespace } from "./internet-exchange-plan.js"
import { compileIxConfiguration, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
const table = ixNamespace(id)
@@ -22,6 +22,24 @@ const fixture = (): IxConfiguration => ixSegmentConfigurationSchema.parse({
}],
})
test("forwarding permits the VRF to exit through its own members before isolation drops", () => {
const objects = compileIxConfiguration(id, fixture())
const egress = ixEgressList(id)
const members = objects.filter(object => object.path === "/interface/list/member")
assert.deepEqual(members.map(object => [object.fields.list, object.fields.interface]),
["wg-eu", "wg-arn", "uplink", "wg-feed"].map(member => [egress, member]))
for (const [family, path] of [[4, "/ip/firewall/filter"], [6, "/ipv6/firewall/filter"]] as const) {
const forward = objects.filter(object => object.path === path && object.fields.chain === "forward")
const boundary = forward.findIndex(object => object.fields.comment === table + ":deny-outside-" + family)
assert.deepEqual(forward.slice(0, boundary).map(object => [object.fields["in-interface"], object.fields["out-interface"] ?? object.fields["out-interface-list"]]),
[[table, table], [table, egress]])
assert.equal(forward[boundary - 1].fields["out-interface-list"], egress)
assert.equal(forward[boundary].fields.action, "drop")
assert.equal(forward.at(-1)?.fields.action, "drop")
assert.equal(forward.at(-1)?.fields["out-interface-list"], egress)
}
})
test("a BGP community uses a stable recursive next hop with independent probes and a final discard", () => {
const objects = compileIxConfiguration(id, fixture())
const policy = objects.find(object => object.fields.comment.endsWith(":bgp-in-evo"))!.fields.rule
@@ -26,6 +26,7 @@ const forbiddenPublic = {
export function ixNamespace(id: string) { return "ix-" + id.replace(/-/g, "").slice(0, 18) }
// RouterOS accepts unambiguous prefixes for interface names before the VRF interface appears.
export function ixDiscardInterface(id: string) { return "ix-drop-" + ixNamespace(id).slice(3) }
export function ixEgressList(id: string) { return "ix-out-" + ixNamespace(id).slice(3) }
export function ixDeviceIds(configuration: IxConfiguration) {
return [...new Set(configuration.sites.flatMap(site => [site.serverId, ...site.interfaces.flatMap(binding => binding.peerServerId === undefined ? [] : [binding.peerServerId])]))].sort((a, b) => a - b)
}
@@ -164,6 +165,11 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
add("/interface/bridge", "drop-bridge", { name: dropInterface, "protocol-mode": "none" })
add("/ip/vrf", "vrf", { name: namespace, interfaces: [dropInterface, ...site.interfaces.map(binding => binding.name)].join(",") })
if (site.interfaces.length) {
const egress = ixEgressList(id)
add("/interface/list", "egress-list", { name: egress })
for (const binding of site.interfaces) {
add("/interface/list/member", "egress-member-" + binding.name, { list: egress, interface: binding.name })
}
for (const family of families) {
const filter = family === 4 ? "/ip/firewall/filter" : "/ipv6/firewall/filter"
for (const peer of site.neighbors.filter(peer => familyOf(peer.address) === family)) {
@@ -174,8 +180,10 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
add(filter, "allow-control-" + family, { chain: "input", "in-interface": namespace, protocol: family === 4 ? "icmp" : "icmpv6", action: "accept" })
add(filter, "deny-input-" + family, { chain: "input", "in-interface": namespace, action: "drop" })
add(filter, "allow-segment-" + family, { chain: "forward", "in-interface": namespace, "out-interface": namespace, action: "accept" })
add(filter, "egress-allow-" + family, { chain: "forward", "in-interface": namespace, "out-interface-list": egress, action: "accept" })
add(filter, "deny-outside-" + family, { chain: "forward", "in-interface": namespace, action: "drop" })
add(filter, "deny-inside-" + family, { chain: "forward", "out-interface": namespace, action: "drop" })
add(filter, "egress-deny-" + family, { chain: "forward", "out-interface-list": egress, action: "drop" })
}
for (const [index, binding] of site.interfaces.entries()) {
if (binding.natIpv4) add("/ip/firewall/nat", "nat-" + index, { chain: "srcnat", action: "masquerade", "out-interface": binding.name })
+6 -1
View File
@@ -53,7 +53,12 @@
}
```
Для создания WireGuard самим планом используйте `provisionWireguard` с `listenPort`, `localAddress`, `peerAddress` и `peerPublicKey`. Если задан `hubEndpoint`, после применения вкладка маршрутов выдаёт шаблон Linux с публичным ключом CHR. Шаблон использует `Table = off`. Оператор устанавливает маршруты и политику выбора источника на Linux отдельно. Для GRE/IPsec перед привязкой туннеля настройте IKEv2 и политику transport mode на обоих концах и отключите FastPath на интерфейсах GRE. В конфигурации IX укажите фиксированные `localEndpoint` и `endpoint`.
### Доступ конечных Linux-серверов
На нужной площадке добавьте по одному подключению на сервер. В поле «Удалённый узел» выберите «Внешний сервер». Сохраните черновик, просмотрите изменения и примените их через WebUI. Во вкладке «Linux-клиенты» скачайте конфигурацию конкретного подключения из применённой ревизии.
- **WireGuard.** Создайте пару ключей на Linux и внесите в форму публичный ключ. Включите создание интерфейса и пира. Укажите порт, адреса туннеля, внешний адрес IX и префиксы за клиентом. Шаблон `wg-quick` использует `Table = off`. Добавьте на Linux нужные маршруты или настройте BGP по параметрам из карточки.
- **GRE/IPsec.** Подготовьте на узле выделенный GRE с отключённым FastPath и обязательной политикой IKEv2/IPsec в транспортном режиме. Задайте оба фиксированных внешних IPv4-адреса в IX. Скачайте шаблон strongSwan, согласуйте предложения и идентификаторы IKE с узлом, подставьте отдельный PSK клиента. После установки IPsec поднимите GRE по командам из вкладки. При использовании статической маршрутизации назначьте согласованный адрес внутри туннеля и добавьте нужные маршруты.
## MCP и ввод в эксплуатацию
@@ -106,6 +106,32 @@ export interface IxRouterObject {
fields: Record<string, string>
}
export interface IxWebPlan {
revision: number
digest: string
changes: Array<IxRouterObject & { action: "create" | "update" | "delete"; target?: string; placeBefore?: string }>
}
export interface IxLinuxBinding {
serverId: number
interfaceName: string
kind: "wireguard" | "gre-ipsec"
}
export interface IxLinuxAccess {
kind: IxLinuxBinding["kind"]
revision: number
filename: string
template: string
setup?: string
bgp?: {
localAs: number
remoteAs: number
neighbor: string
advertisedPrefixes: string[]
}
}
export interface IxSiteObservation {
serverId: number
observedAt: string
+132
View File
@@ -0,0 +1,132 @@
import { expect, test } from "@playwright/test"
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
const observedAt = "2026-11-20T00:00:00Z"
const nodes = [
{ id: 1, name: "ix-node-01", site: "TEST-1", country: "DE", enabled: true },
{ id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true },
]
test("IX: редактирование и применение сохранённой ревизии из WebUI без MCP", async ({ page }, testInfo) => {
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-central", sites: [
{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10", interfaces: [{ name: "wg-member", kind: "wireguard" }] },
{ serverId: 2, autonomousSystem: 64512, routerId: "192.0.2.11" },
] })
let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt }
const digest = "a".repeat(64)
const mcpCalls: string[] = []
let applies = 0
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const request = route.request()
const path = new URL(request.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, peers: nodes })
if (path.startsWith("/api/mcp/")) {
mcpCalls.push(path)
return route.fulfill({ status: 503, json: { error: "MCP недоступен" } })
}
if (path === "/api/ix/segments" && request.method() === "POST") {
const change = ixChangeSchema.parse(request.postDataJSON())
segment = { ...segment, configuration: change.configuration, revision: change.revision + 1 }
return json({ segment })
}
if (path === "/api/ix/segments") return json({ items: [segment] })
if (path === `/api/ix/segments/${id}/linux`) {
const kind = new URL(request.url()).searchParams.get("interfaceName")
if (kind === "wg-linux") return json({ revision: segment.appliedRevision, kind: "wireguard",
filename: "wg-linux.conf", template: "[Interface]\nTable = off\n" })
if (kind === "gre-linux") return json({ revision: segment.appliedRevision, kind: "gre-ipsec",
filename: "gre-linux.conf", template: "mode = transport\n", setup: "swanctl --initiate --child gre-linux" })
return json({ revision: segment.appliedRevision, items: [
{ serverId: 1, kind: "wireguard", interfaceName: "wg-linux" },
{ serverId: 2, kind: "gre-ipsec", interfaceName: "gre-linux" },
] })
}
if (path === `/api/ix/segments/${id}/status`) return json({ sites: [{
serverId: 1, available: true, observedAt, neighbors: [{ name: "member", established: true }],
routes: [{ prefix: "2001:db8:120::/48", gateway: "2001:db8::1", immediateGateway: "2001:db8::2%wg-member", active: true }],
}] })
if (path === `/api/ix/segments/${id}/plan`) {
expect(request.postDataJSON()).toEqual({ revision: segment.revision })
return json({ revision: segment.revision, digest, changes: [
{ serverId: 1, action: "create", path: "/ipv6/route", fields: { "dst-address": "2001:db8:120::/48" } },
] })
}
if (path === `/api/ix/segments/${id}/apply`) {
expect(request.postDataJSON()).toEqual({ revision: segment.revision, digest })
applies++
segment = { ...segment, revision: segment.revision + 1, appliedRevision: segment.revision + 1 }
return json({ segment })
}
if (path === "/api/servers") return json([])
return json({})
})
await page.goto("/ix")
const row = page.getByRole("button", { name: "ix-central", exact: true })
await expect(row).toBeVisible()
const search = page.getByRole("searchbox", { name: "Поиск сегментов" })
await search.fill("no-match")
await expect(page.getByText("Сегменты не найдены")).toBeVisible()
await search.clear()
await expect(row).toBeVisible()
await page.screenshot({ path: testInfo.outputPath("ix-list-desktop.png"), animations: "disabled" })
await row.click()
await expect(page.getByRole("heading", { name: "ix-central" })).toBeFocused()
await page.screenshot({ path: testInfo.outputPath("ix-detail-desktop.png"), animations: "disabled" })
await page.setViewportSize({ width: 390, height: 760 })
await page.getByLabel("Локальный ASN", { exact: true }).first().fill("64513")
await page.getByText("Подключения · 1", { 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.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.getByLabel("Префикс маршрута").fill("2001:db8:120::/48")
const save = page.getByRole("button", { name: "Сохранить черновик" })
await save.scrollIntoViewIfNeeded()
await expect(save).toBeInViewport()
await save.click()
await expect(page.getByText("Черновик сохранён")).toBeVisible()
expect(segment.configuration.sites[0]).toMatchObject({
autonomousSystem: 64513,
interfaces: [{ name: "wg-member", prefixes: ["2001:db8:120::/48"] }],
groups: [{ id: "member", primary: { interface: "wg-member", nextHop: "2001:db8::2" } }],
routes: [{ prefix: "2001:db8:120::/48", group: "member" }],
})
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()
expect(applies).toBe(0)
await page.getByRole("button", { name: "Применить", exact: true }).click()
await expect(page.getByText("Конфигурация IX применена")).toBeVisible()
expect(segment.appliedRevision).toBe(3)
expect(applies).toBe(1)
await page.getByRole("tab", { name: "Linux-клиенты" }).click()
await page.getByRole("button", { name: "Получить конфиг wg-linux" }).click()
await expect(page.getByText(/Table = off/)).toBeVisible()
const download = page.waitForEvent("download")
await page.getByRole("link", { name: "Скачать wg-linux.conf" }).click()
expect((await download).suggestedFilename()).toBe("wg-linux.conf")
await page.getByRole("button", { name: "Получить конфиг gre-linux" }).click()
await expect(page.getByText("mode = transport", { exact: true })).toBeVisible()
await expect(page.getByText("swanctl --initiate --child gre-linux", { exact: true })).toBeVisible()
expect(mcpCalls).toEqual([])
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390)
})
+23
View File
@@ -45,6 +45,29 @@ async function edit(page: Page, id = 1) {
await page.getByRole("menuitem", { name: "Редактировать", exact: true }).click()
}
test("типы узлов в узкой форме выбираются кнопкой и с клавиатуры", async ({ page }, testInfo) => {
await setup(page)
await page.setViewportSize({ width: 390, height: 844 })
await page.getByRole("button", { name: "Добавить сервер", exact: true }).click()
const types = page.getByRole("group", { name: "Тип узла" })
const exit = types.getByRole("button", { name: "Exit Node" })
const ix = types.getByRole("button", { name: "IX Node" })
await expect(exit).toHaveAttribute("aria-pressed", "true")
await expect(types).toBeInViewport({ ratio: 1 })
const buttonTops = await types.getByRole("button").evaluateAll(buttons => buttons.map(button => button.getBoundingClientRect().top))
expect(buttonTops).toHaveLength(4)
expect(new Set(buttonTops).size).toBe(1)
await ix.click()
await expect(ix).toHaveAttribute("aria-pressed", "true")
await expect(types.getByRole("button", { pressed: true })).toHaveCount(1)
await expect(page.getByPlaceholder("AS65001")).toBeVisible()
await page.screenshot({ path: testInfo.outputPath("node-type-mobile.png"), animations: "disabled" })
await page.keyboard.press("Shift+Tab")
await expect(exit).toBeFocused()
await page.keyboard.press("Space")
await expect(exit).toHaveAttribute("aria-pressed", "true")
})
test("ссылка на сервер: выбор, опрос одного устройства, сброс и возврат", async ({ page }) => {
const calls: string[] = []
await setup(page, async (route, path) => {