Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9f623ccda | ||
|
|
9951035448 | ||
|
|
95be5178d0 | ||
|
|
c9152bb106 |
No files matched your search
@@ -0,0 +1,117 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import type { IxNodeInventory, IxSegment, IxTransitRequest } from "@mmapp/contracts/internet-exchange"
|
||||
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 { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
export function publicEndpoint(inventory?: IxNodeInventory) {
|
||||
if (!inventory) return ""
|
||||
const wan = new Set(inventory.defaultRoutes.filter(route => route.family === 4).map(route => route.interface))
|
||||
const addresses = new Set(inventory.interfaces.filter(iface => !iface.disabled && wan.has(iface.name))
|
||||
.flatMap(iface => iface.addresses.filter(address => !address.includes(":")).map(address => address.split("/")[0])))
|
||||
return addresses.size === 1 ? [...addresses][0] : ""
|
||||
}
|
||||
|
||||
export function transitName(segment: IxSegment, serverId: number, target: number, family: 4 | 6) {
|
||||
const used = segment.configuration.sites.find(site => site.serverId === serverId)?.groups ?? []
|
||||
const base = "via-" + target.toString(36) + "-v" + family
|
||||
let name = base
|
||||
for (let i = 2; used.some(group => group.id === name); i++) name = base + "-" + i
|
||||
return name
|
||||
}
|
||||
|
||||
function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean
|
||||
save: (input: IxTransitRequest) => void; cancel: () => void
|
||||
}) {
|
||||
const [serverId, setServerId] = useState(segment.configuration.sites[0].serverId)
|
||||
const [targetServerId, setTargetServerId] = useState(0)
|
||||
const [local, setLocal] = useState("")
|
||||
const [remote, setRemote] = useState("")
|
||||
const [name, setName] = useState("")
|
||||
const [probe, setProbe] = useState("")
|
||||
const [family, setFamily] = useState<4 | 6>(4)
|
||||
const origin = useIxNodeInventory(backendUrl, serverId, segment.id)
|
||||
const target = useIxNodeInventory(backendUrl, targetServerId, segment.id)
|
||||
const localEndpoint = local || publicEndpoint(origin.inventory)
|
||||
const remoteEndpoint = remote || publicEndpoint(target.inventory)
|
||||
const exitName = name || transitName(segment, serverId, targetServerId, family)
|
||||
const sourceChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
.map(node => ({ value: String(node.id), label: node.name + (node.type === "ix-node" ? " · IX" : " · ExitNode") }))
|
||||
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
if (!busy && targetServerId && localEndpoint && remoteEndpoint && exitName) {
|
||||
save({ revision: segment.revision, name: exitName, serverId, targetServerId, localEndpoint, remoteEndpoint, family, probe: probe || undefined })
|
||||
}
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
|
||||
{sourceChoices.length > 1 && <Field><FieldLabel htmlFor="ix-egress-source">Узел входа</FieldLabel>
|
||||
<Select items={sourceChoices} value={String(serverId)} onValueChange={value => {
|
||||
if (value) { setServerId(Number(value)); setTargetServerId(0); setLocal(""); setRemote("") }
|
||||
}}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-source"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{sourceChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>}
|
||||
<Field><FieldLabel htmlFor="ix-egress-target">Выходной узел</FieldLabel>
|
||||
<Select items={targets} value={targetServerId ? String(targetServerId) : null}
|
||||
onValueChange={value => { setTargetServerId(Number(value)); setRemote("") }}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-target"><SelectValue placeholder="Другой IX или ExitNode" /></SelectTrigger>
|
||||
<SelectContent>{targets.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<details key={serverId + ":" + targetServerId + ":" + (origin.loading || target.loading)} open={!!targetServerId && (!publicEndpoint(origin.inventory) || !publicEndpoint(target.inventory)) && !origin.loading && !target.loading}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-egress-name">Имя выхода</FieldLabel>
|
||||
<Input id="ix-egress-name" value={exitName} pattern="[a-z][a-z0-9-]{0,23}" onChange={event => setName(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-local">Внешний IPv4 узла входа</FieldLabel>
|
||||
<Input id="ix-egress-local" value={localEndpoint} required onChange={event => setLocal(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-remote">Внешний IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-egress-remote" value={remoteEndpoint} required onChange={event => setRemote(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-probe">Контрольный адрес</FieldLabel>
|
||||
<Input id="ix-egress-probe" value={probe} placeholder="Адрес второго конца туннеля" onChange={event => setProbe(event.target.value)} />
|
||||
<FieldDescription>Для проверки выхода за пределами туннеля укажите доступную цель за удалённым узлом.</FieldDescription>
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-family">Семейство трафика</FieldLabel>
|
||||
<Select value={String(family)} items={[{ value: "4", label: "IPv4" }, { value: "6", label: "IPv6" }]}
|
||||
onValueChange={value => { setFamily(value === "6" ? 6 : 4); setProbe("") }}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-family"><SelectValue /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="4">IPv4</SelectItem><SelectItem value="6">IPv6</SelectItem></SelectContent>
|
||||
</Select>
|
||||
{family === 6 && <FieldDescription>Для выхода в Интернет IPv6 нужен маршрутизируемый префикс Linux с обратным маршрутом до выходной CHR.</FieldDescription>}
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
{(origin.error || target.error) && <p role="status" className="text-sm text-muted-foreground">{origin.error ?? target.error}</p>}
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button type="submit" disabled={busy || !targetServerId || !localEndpoint || !remoteEndpoint}>Сохранить</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
}
|
||||
|
||||
export function IxExits({ segment, nodes, backendUrl, busy, error, save }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean; error: string
|
||||
save: (input: IxTransitRequest) => Promise<boolean>
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
return <>
|
||||
<Button size="sm" className="w-fit" disabled={busy} onClick={() => setOpen(true)}>Добавить удалённый выход</Button>
|
||||
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
|
||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
||||
<SheetHeader><SheetTitle>Удалённый выход</SheetTitle>
|
||||
<SheetDescription>WireGuard, обратные маршруты и IPv4 SNAT будут подготовлены на обоих узлах.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
</SheetHeader>
|
||||
{open && <TransitEditor segment={segment} nodes={nodes} backendUrl={backendUrl} busy={busy}
|
||||
save={input => void save(input).then(success => { if (success) setOpen(false) })} cancel={() => setOpen(false)} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||
import type { IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
|
||||
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
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 { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { publicEndpoint, transitName } from "./ix-exits"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
type FormState = {
|
||||
serverId: number
|
||||
name: string
|
||||
kind: IxLinuxClientRequest["kind"]
|
||||
hub: string
|
||||
peer: string
|
||||
key: string
|
||||
localAddress: string
|
||||
peerAddress: string
|
||||
prefixes: string
|
||||
destinations: string
|
||||
exit: string
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
|
||||
|
||||
function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
|
||||
const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
|
||||
const label = target ? "Через " + nodeLabel(nodes, target) : group.primary.viaMain ? "Интернет с этого IX" : group.id
|
||||
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
|
||||
}
|
||||
|
||||
function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
|
||||
segment: IxSegment; edit: { site: IxSite; binding: Binding } | null; nodes: IxNode[]; backendUrl: string
|
||||
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
|
||||
}) {
|
||||
const binding = edit?.binding
|
||||
const [form, setForm] = useState<FormState>(() => ({
|
||||
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
|
||||
name: binding?.linux?.name ?? "", kind: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
|
||||
hub: binding?.localEndpoint ?? binding?.provisionWireguard?.hubEndpoint ?? "",
|
||||
peer: binding?.linux?.peerEndpoint ?? binding?.endpoint ?? "",
|
||||
key: binding?.provisionWireguard?.credentialId ? "" : binding?.provisionWireguard?.peerPublicKey ?? "",
|
||||
localAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.localAddress ?? "",
|
||||
peerAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.peerAddress ?? "",
|
||||
prefixes: binding?.prefixes.join("\n") ?? "", destinations: binding?.linux?.destinations.join("\n") ?? "",
|
||||
exit: binding?.linux?.exit ?? "isolated", enabled: binding?.linux?.enabled ?? true,
|
||||
}))
|
||||
const [rotate, setRotate] = useState(false)
|
||||
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
|
||||
const [transitLocal, setTransitLocal] = useState("")
|
||||
const [transitRemote, setTransitRemote] = useState("")
|
||||
const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
|
||||
const suggested = publicEndpoint(origin.inventory)
|
||||
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
|
||||
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
|
||||
const localEndpoint = transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
|
||||
const remoteEndpoint = transitRemote.trim() || publicEndpoint(target.inventory)
|
||||
const family = form.peerAddress.includes(":") ? 6 : 4
|
||||
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
|
||||
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const transports = [{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec (IKEv2)" }]
|
||||
const groups = site?.groups.filter(group => group.onFailure === "block" && group.gateway.includes(":") === (family === 6)) ?? []
|
||||
const local = groups.find(group => group.id === "ix-wan" + family && group.primary.viaMain)
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== form.serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
const exits = [
|
||||
{ value: "isolated", label: "Только разрешённые сети" },
|
||||
{ value: local?.id ?? "local-wan", label: local ? groupLabel(local, site!, nodes) : "Интернет с этого IX" },
|
||||
...groups.filter(group => group !== local).map(group => ({ value: group.id, label: groupLabel(group, site!, nodes) + " · " + group.id })),
|
||||
...targets.filter(node => !groups.some(group => site?.interfaces.some(link => link.name === group.primary.interface && link.peerServerId === node.id)))
|
||||
.map(node => ({ value: "remote:" + node.id, label: "Через " + node.name + (node.type === "exit-node" ? " · ExitNode" : " · IX") })),
|
||||
]
|
||||
const valid = !!form.name.trim() && !!(form.hub || suggested) && (form.kind === "wireguard" || !!form.peer) &&
|
||||
(!targetId || !!localEndpoint && !!remoteEndpoint) && exits.some(exit => exit.value === form.exit)
|
||||
const destinationsField = <Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
|
||||
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
|
||||
<FieldDescription>Перечислите префиксы для доступа через IX, например 10.2.0.0/24.</FieldDescription></Field>
|
||||
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
if (!valid || busy) return
|
||||
void save({
|
||||
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
|
||||
kind: form.kind, hubEndpoint: form.hub.trim() || suggested, peerEndpoint: form.peer.trim() || undefined,
|
||||
peerPublicKey: form.kind === "wireguard" ? form.key.trim() || undefined : undefined,
|
||||
localAddress: form.localAddress.trim() || undefined, peerAddress: form.peerAddress.trim() || undefined,
|
||||
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" || targetId ? undefined : form.exit,
|
||||
transit: targetId ? { targetServerId: targetId, name: transitName(segment, form.serverId, targetId, family), family,
|
||||
localEndpoint, remoteEndpoint } : undefined,
|
||||
enabled: form.enabled, rotate,
|
||||
})
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
|
||||
<Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel>
|
||||
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" required onChange={event => patch({ name: event.target.value })} /></Field>
|
||||
{nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel>
|
||||
<Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit}
|
||||
onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}>
|
||||
<SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>}
|
||||
<Field><FieldLabel htmlFor="ix-linux-transport">Туннель</FieldLabel>
|
||||
<Select value={form.kind} items={transports} disabled={!!edit}
|
||||
onValueChange={value => (value === "wireguard" || value === "gre-ipsec") && patch({ kind: value })}>
|
||||
<SelectTrigger id="ix-linux-transport" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{transports.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
|
||||
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={form.kind === "gre-ipsec"} onChange={event => patch({ peer: event.target.value })} />
|
||||
<FieldDescription>{form.kind === "gre-ipsec" ? "Фиксированный IPv4 на стороне VPS для GRE/IPsec." : form.exit === "isolated"
|
||||
? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
|
||||
<Select value={form.exit} items={exits} onValueChange={value => { if (value) { patch({ exit: value }); setTransitLocal(""); setTransitRemote("") } }}>
|
||||
<SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
{!!targetId && <FieldDescription>IX создаст туннель до {nodeLabel(nodes, targetId)} для выхода в Интернет.</FieldDescription>}
|
||||
</Field>
|
||||
{!!targetId && !publicEndpoint(target.inventory) && (target.loading ? <p role="status" className="text-sm text-muted-foreground">Читаем WAN выходного узла…</p> :
|
||||
<Field><FieldLabel htmlFor="ix-transit-target">IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-transit-target" value={transitRemote} onChange={event => setTransitRemote(event.target.value)} />
|
||||
<FieldDescription>Укажите адрес интерфейса CHR для межузлового туннеля.</FieldDescription></Field>)}
|
||||
{!!targetId && !suggested && !origin.loading && <Field><FieldLabel htmlFor="ix-transit-source">IPv4 узла IX для транзита</FieldLabel>
|
||||
<Input id="ix-transit-source" value={localEndpoint} onChange={event => setTransitLocal(event.target.value)} /></Field>}
|
||||
{form.exit === "isolated" && destinationsField}
|
||||
<details className="grid gap-3" key={form.serverId + ":" + origin.loading}
|
||||
open={!origin.loading && !suggested && !binding?.provisionWireguard?.hubEndpoint && !binding?.localEndpoint}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
|
||||
<Input id="ix-linux-hub" value={form.hub || suggested} onChange={event => patch({ hub: event.target.value })} />
|
||||
<FieldDescription>{origin.loading ? "Читаем адрес WAN с CHR…" : suggested ? "Адрес WAN для подключения VPS." : "Введите адрес IX, доступный с VPS."}</FieldDescription>
|
||||
</Field>
|
||||
{form.kind === "wireguard" && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
|
||||
<Input id="ix-linux-key" value={form.key} placeholder="Создать автоматически" onChange={event => patch({ key: event.target.value })} />
|
||||
<FieldDescription>Укажите ключ только для своей пары WireGuard.</FieldDescription></Field>}
|
||||
{form.exit !== "isolated" && destinationsField}
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel>
|
||||
<Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field>
|
||||
</div>
|
||||
</details>
|
||||
{edit && <div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled}
|
||||
onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button>
|
||||
{form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"}
|
||||
aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
<SheetFooter>{form.kind === "wireguard" && !form.key && <p className="text-sm text-muted-foreground">После подтверждения можно скачать готовый файл WireGuard для Linux.</p>}
|
||||
<Button type="submit" disabled={!valid || busy}>Сохранить</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
|
||||
</form>
|
||||
}
|
||||
|
||||
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
|
||||
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
|
||||
view: (binding: IxLinuxBinding) => void; revoke: (binding: IxLinuxBinding) => void
|
||||
inspect: (binding: IxLinuxBinding) => void
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [edit, setEdit] = useState<{ site: IxSite; binding: Binding } | null>(null)
|
||||
const rows = useMemo(() => {
|
||||
const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{
|
||||
serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"],
|
||||
policy: binding.linux, name: binding.linux.name, enabled: binding.linux.enabled,
|
||||
connection: applied.find(item => item.serverId === site.serverId && item.interfaceName === binding.name)?.connection,
|
||||
}] : []))
|
||||
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
|
||||
}, [segment, applied])
|
||||
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
|
||||
{ id: "name", header: "Клиент", size: 170, cell: ({ row }) => <div className="grid gap-0.5">
|
||||
<span className="font-medium">{row.original.name ?? row.original.interfaceName}</span>
|
||||
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
|
||||
</div> },
|
||||
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
|
||||
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
|
||||
const client = row.original
|
||||
const site = segment.configuration.sites.find(item => item.serverId === client.serverId)
|
||||
const binding = site?.interfaces.find(item => item.name === client.interfaceName)
|
||||
const group = site?.groups.find(item => item.id === client.policy?.exit)
|
||||
const label = site && group ? groupLabel(group, site, nodes) : client.policy ? client.policy.exit ?? "Только сети IX" : "По настройкам интерфейса"
|
||||
return readOnly || !site || !binding?.linux ? label : <Button type="button" size="sm" variant="link" className="max-w-full"
|
||||
disabled={busy} aria-label={"Доступ и выход клиента " + client.name} onClick={() => { setEdit({ site, binding }); setOpen(true) }}>
|
||||
<span className="truncate">{label}</span><PencilIcon aria-hidden />
|
||||
</Button>
|
||||
} },
|
||||
{ id: "state", header: "Состояние", size: 160, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
if (!binding.policy) return <Badge variant="secondary">Прежняя настройка</Badge>
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)
|
||||
const site = segment.configuration.sites.find(item => item.serverId === binding.serverId)
|
||||
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
|
||||
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
|
||||
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
|
||||
return binding.connection?.state === "connected" ? <div className="grid gap-1">
|
||||
<Badge variant="success-light" className="w-fit">Подключён</Badge>
|
||||
{binding.connection.rx !== undefined && <span className="text-xs text-muted-foreground">RX {binding.connection.rx} · TX {binding.connection.tx}</span>}
|
||||
</div>
|
||||
: <Badge variant="secondary">{binding.connection?.state === "waiting" ? "Ожидает туннель" : "Нет данных"}</Badge>
|
||||
} },
|
||||
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
const site = segment.configuration.sites.find(site => site.serverId === binding.serverId)
|
||||
const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName)
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
|
||||
return <div className="flex flex-wrap gap-1">
|
||||
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName)}
|
||||
onClick={() => view(live)}>Конфиг Linux</Button>}
|
||||
{binding.policy && (live || !readOnly && saved?.linux) && <DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + binding.name} />}>
|
||||
<EllipsisIcon aria-hidden />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{live && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
|
||||
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>}
|
||||
</div>
|
||||
} },
|
||||
], [nodes, applied, segment.configuration.sites, readOnly, busy, view, revoke, inspect])
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns,
|
||||
getRowId: row => row.serverId + ":" + row.interfaceName })
|
||||
return <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<FrameTitle>Linux-клиенты</FrameTitle>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button>
|
||||
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
|
||||
</div>
|
||||
</FrameHeader>
|
||||
<FramePanel className="min-w-0 p-0">
|
||||
<DataGridShell table={table} recordCount={rows.length} isLoading={busy && !rows.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
|
||||
</FramePanel>
|
||||
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
|
||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
||||
<SheetHeader><SheetTitle>{edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
||||
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
</SheetHeader>
|
||||
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} busy={busy}
|
||||
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</Frame>
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client"
|
||||
|
||||
import { useId, type ReactNode } from "react"
|
||||
import { useId, useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { PlusIcon, XIcon } from "lucide-react"
|
||||
import type { IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import type { IxNodeInventory, 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"
|
||||
@@ -15,7 +15,7 @@ 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 }
|
||||
type Choice = { value: string; label: string; disabled?: boolean }
|
||||
|
||||
function TextField({ label, value, edit, numeric, placeholder }: {
|
||||
label: string; value: string | number; edit: (value: string) => void; numeric?: boolean; placeholder?: string
|
||||
@@ -29,7 +29,7 @@ function TextField({ label, value, edit, numeric, placeholder }: {
|
||||
}
|
||||
|
||||
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
|
||||
label: string; value?: T; options: readonly { value: T; label: string; disabled?: boolean }[]; edit: (value: T) => void; disabled: boolean
|
||||
}) {
|
||||
const id = useId()
|
||||
return <Field className="min-w-0">
|
||||
@@ -37,7 +37,7 @@ function Pick<T extends string>({ label, value, options, edit, disabled }: {
|
||||
<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>
|
||||
<SelectContent>{options.map(item => <SelectItem key={item.value} value={item.value} disabled={item.disabled}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
}
|
||||
@@ -62,25 +62,29 @@ function Lines({ label, value, edit }: { label: string; value: string[]; edit: (
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children }: {
|
||||
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children, label, visible }: {
|
||||
title: string; items: T[]; edit: (items: T[]) => void; make: () => T
|
||||
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
|
||||
label?: (item: T) => string; visible?: (item: T) => boolean
|
||||
}) {
|
||||
return <details className="min-w-0 rounded-lg border">
|
||||
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">{title} · {items.length}</summary>
|
||||
<div className="grid gap-3 border-t p-3">
|
||||
{items.map((item, index) => <div className="grid min-w-0 gap-3 rounded-md border p-3" key={index}>
|
||||
<div className="flex items-center justify-between gap-2 text-sm text-muted-foreground">
|
||||
<span>Запись {index + 1}</span>
|
||||
{!readOnly && <Button type="button" size="icon-sm" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
|
||||
onClick={() => edit(items.filter((_, position) => position !== index))}><XIcon aria-hidden /></Button>}
|
||||
</div>
|
||||
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
|
||||
</div>)}
|
||||
{!readOnly && <Button type="button" variant="outline" size="sm" className="w-fit" disabled={items.length >= max}
|
||||
onClick={() => edit([...items, make()])}><PlusIcon aria-hidden />{addLabel}</Button>}
|
||||
const [expanded, setExpanded] = useState<number | null>(null)
|
||||
const rows = items.map((item, index) => ({ item, index })).filter(({ item }) => !visible || visible(item))
|
||||
return <section className="grid min-w-0 gap-2 border-t py-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium">{title} <span className="text-muted-foreground">· {rows.length}</span></h4>
|
||||
{!readOnly && <Button type="button" variant="outline" size="sm" disabled={items.length >= max}
|
||||
onClick={() => { setExpanded(items.length); edit([...items, make()]) }}><PlusIcon aria-hidden />{addLabel}</Button>}
|
||||
</div>
|
||||
</details>
|
||||
{rows.map(({ item, index }) => <div key={index} className="min-w-0 border-s-2 ps-3">
|
||||
<Button type="button" size="sm" variant="ghost" aria-expanded={expanded === index}
|
||||
onClick={() => setExpanded(expanded === index ? null : index)}>{label?.(item) || "Запись " + (index + 1)}</Button>
|
||||
{expanded === index && <fieldset disabled={readOnly} className="grid gap-3 py-2">
|
||||
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
|
||||
{!readOnly && <Button type="button" size="sm" className="w-fit" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
|
||||
onClick={() => { setExpanded(null); edit(items.filter((_, position) => position !== index)) }}><XIcon aria-hidden />Удалить</Button>}
|
||||
</fieldset>}
|
||||
</div>)}
|
||||
</section>
|
||||
}
|
||||
|
||||
const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
|
||||
@@ -91,13 +95,21 @@ const kinds = [
|
||||
{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec" }, { value: "uplink", label: "Аплинк" },
|
||||
] as const
|
||||
|
||||
function InterfaceFields({ value, edit, peers, readOnly, segmentName }: {
|
||||
function InterfaceFields({ value, edit, peers, readOnly, segmentName, inventory }: {
|
||||
value: Binding; edit: (value: Binding) => void; peers: Choice[]; readOnly: boolean; segmentName: string
|
||||
inventory: IxNodeInventory["interfaces"]
|
||||
}) {
|
||||
const wireGuard = value.provisionWireguard
|
||||
const choices = inventory.filter(item => item.name === value.name || value.kind === "uplink" ||
|
||||
(value.kind === "wireguard" ? ["wg", "wireguard"] : ["gre", "gre-tunnel"]).includes(item.type))
|
||||
.map(item => ({ value: item.name, label: [item.name, item.addresses.join(", "), item.restriction].filter(Boolean).join(" · "),
|
||||
disabled: item.name !== value.name && (item.disabled || !!item.restriction) }))
|
||||
if (value.name && !choices.some(item => item.value === value.name)) choices.unshift({ value: value.name, label: value.name, disabled: false })
|
||||
return <>
|
||||
<div className={columns}>
|
||||
<TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
|
||||
{wireGuard || !inventory.length ? <TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
|
||||
: <Pick label="Интерфейс CHR" value={value.name || undefined} options={choices} disabled={readOnly}
|
||||
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}
|
||||
@@ -128,21 +140,33 @@ function InterfaceFields({ value, edit, peers, readOnly, segmentName }: {
|
||||
</>
|
||||
}
|
||||
|
||||
function PathFields({ title, value, edit, interfaces, readOnly }: {
|
||||
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; readOnly: boolean
|
||||
function PathFields({ title, value, edit, interfaces, inventory, readOnly }: {
|
||||
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]; readOnly: boolean
|
||||
}) {
|
||||
const choices = value.viaMain ? inventory.filter(item => !interfaces.some(choice => choice.value === item.name) && !item.disabled)
|
||||
.map(item => ({ value: item.name, label: item.name })) : [...interfaces]
|
||||
if (value.interface && !choices.some(item => item.value === value.interface)) choices.unshift({ value: value.interface, label: value.interface })
|
||||
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} />
|
||||
<div className="sm:col-span-3"><Flag label="WAN из таблицы main" checked={!!value.viaMain} disabled={readOnly}
|
||||
edit={viaMain => edit({ ...emptyPath(""), viaMain })} /></div>
|
||||
<Pick label="Интерфейс пути" value={value.interface || undefined} options={choices} 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
|
||||
function GroupFields({ value, edit, interfaces, inventory, alternatives, readOnly }: {
|
||||
value: Group; edit: (value: Group) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]
|
||||
alternatives: Group[]; readOnly: boolean
|
||||
}) {
|
||||
const selectedBackup = alternatives.find(other => other.primary.interface === value.backup?.interface &&
|
||||
other.primary.nextHop === value.backup?.nextHop && other.primary.probe === value.backup?.probe)
|
||||
return <>
|
||||
<Pick label="Резервный выход" value={value.backup ? selectedBackup?.id ?? ":manual" : ""} disabled={readOnly}
|
||||
options={[none, ...alternatives.map(other => ({ value: other.id, label: other.id })), { value: ":manual", label: "Указать другой шлюз" }]}
|
||||
edit={id => edit({ ...value, backup: id === ":manual" ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "")
|
||||
: alternatives.find(other => other.id === id)?.primary })} />
|
||||
<div className={columns}>
|
||||
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
|
||||
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
|
||||
@@ -150,10 +174,9 @@ function GroupFields({ value, edit, interfaces, readOnly }: {
|
||||
{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 })} />}
|
||||
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={primary => edit({ ...value, primary })} />
|
||||
{value.backup && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} inventory={inventory}
|
||||
readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -188,41 +211,44 @@ function PeerFields({ value, edit, interfaces, groups, readOnly }: {
|
||||
</>
|
||||
}
|
||||
|
||||
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName }: {
|
||||
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName, inventory }: {
|
||||
site: IxSite; edit: (fields: Partial<IxSite>) => void; peers: Choice[]; readOnly: boolean; segmentName: string
|
||||
inventory: IxNodeInventory["interfaces"]
|
||||
}) {
|
||||
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} />}
|
||||
return <div className="grid min-w-0 gap-2">
|
||||
<Entries<Binding> title="Интерфейсы маршрутизации" label={item => item.name} visible={item => !item.linux && !item.provisionTransit} items={site.interfaces} edit={interfaces => edit({ interfaces })}
|
||||
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={80} addLabel="Добавить интерфейс" readOnly={readOnly}>
|
||||
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} inventory={inventory} />}
|
||||
</Entries>
|
||||
<Entries<Group> title="Группы шлюзов" items={site.groups} edit={groups => edit({ groups })}
|
||||
<Entries<Group> title="Выходы и резерв" label={item => item.id} items={site.groups} edit={groups => edit({ groups })}
|
||||
make={() => ({ id: "", gateway: "", primary: emptyPath(interfaces[0]?.value ?? ""), onFailure: "block" })}
|
||||
max={24} addLabel="Добавить группу шлюзов" readOnly={readOnly}>
|
||||
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} readOnly={readOnly} />}
|
||||
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} inventory={inventory}
|
||||
alternatives={site.groups.filter(group => group.id !== value.id && group.primary.interface !== value.primary.interface &&
|
||||
group.gateway.includes(":") === value.gateway.includes(":"))} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<Entries title="Статические маршруты" items={site.routes} edit={routes => edit({ routes })}
|
||||
<Entries title="Статические маршруты" label={item => item.prefix} items={site.routes} edit={routes => edit({ routes })}
|
||||
make={() => ({ prefix: "", group: groups[0]?.value ?? "" })} max={250} addLabel="Добавить маршрут" readOnly={readOnly}>
|
||||
{(route, update) => <div className={columns}>
|
||||
<TextField label="Префикс маршрута" value={route.prefix} edit={prefix => update({ ...route, prefix })} />
|
||||
<Pick label="Группа шлюзов маршрута" value={route.group} options={groups} edit={group => update({ ...route, group })} disabled={readOnly} />
|
||||
</div>}
|
||||
</Entries>
|
||||
<Entries<Peer> title="BGP-соседи" items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
|
||||
<Entries<Peer> title="BGP-соседи" label={item => item.id} items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
|
||||
make={() => ({ id: "", type: "member", address: "", localAddress: "", remoteAs: 0,
|
||||
binding: interfaces[0]?.value ?? "", group: groups[0]?.value, prefixes: [], exportPrefixes: [], rules: [], limit: 1000 })}>
|
||||
{(value, update) => <PeerFields value={value} edit={update} interfaces={interfaces} groups={groups} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<details className="rounded-lg border">
|
||||
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">Выходы по умолчанию и маршруты отбрасывания</summary>
|
||||
<div className="grid gap-3 border-t p-3">
|
||||
<fieldset disabled={readOnly} className="grid gap-3 border-t p-3">
|
||||
{[0, 1].map(index => <Pick key={index} label={"Группа выхода " + (index + 1)} value={site.exits[index] ?? ""}
|
||||
options={[none, ...groups.filter(group => group.value !== site.exits[1 - index])]} disabled={readOnly}
|
||||
edit={id => { const exits = [...site.exits]; exits[index] = id; edit({ exits: exits.filter(Boolean) }) }} />)}
|
||||
<Lines label="Префиксы отбрасывания" value={site.discardNetworks} edit={discardNetworks => edit({ discardNetworks })} />
|
||||
</div>
|
||||
</fieldset>
|
||||
</details>
|
||||
</fieldset>
|
||||
</div>
|
||||
}
|
||||
+70
-26
@@ -1,9 +1,9 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo } from "react"
|
||||
import { useEffect, useMemo, useState } 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 type { IxConfiguration, IxNodeInventory, 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"
|
||||
@@ -13,14 +13,15 @@ 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 { requestJson } from "@/shared/api/http-client"
|
||||
import { IxSiteEditor } from "./ix-site-editor"
|
||||
|
||||
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean }
|
||||
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean; type?: string }
|
||||
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: "",
|
||||
serverId: 0, autonomousSystem: 64512, routerId: "", autoRouterId: true,
|
||||
interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [],
|
||||
})
|
||||
|
||||
@@ -40,16 +41,64 @@ export function SegmentGrid({ rows, nodes, loading, open, empty }: {
|
||||
</Button>
|
||||
) },
|
||||
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
|
||||
{ id: "neighbors", header: "BGP-соседи", size: 115, cell: ({ row }) =>
|
||||
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.neighbors.length, 0)}</span> },
|
||||
{ id: "clients", header: "Linux-клиенты", size: 125, cell: ({ row }) =>
|
||||
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.interfaces.filter(item => item.linux).length, 0)}</span> },
|
||||
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
|
||||
], [nodes, open])
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
|
||||
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
|
||||
}
|
||||
|
||||
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change }: {
|
||||
export function useIxNodeInventory(backendUrl: string, serverId: number, segmentId?: string) {
|
||||
const path = serverId > 0 ? `/api/ix/nodes/${serverId}/inventory${segmentId ? "?segmentId=" + segmentId : ""}` : null
|
||||
const [result, setResult] = useState<{ path: string; inventory?: IxNodeInventory; error?: string }>()
|
||||
const [refresh, setRefresh] = useState(0)
|
||||
useEffect(() => {
|
||||
if (!path) return
|
||||
const controller = new AbortController()
|
||||
void requestJson<IxNodeInventory>(backendUrl, path, { signal: controller.signal }).then(inventory => {
|
||||
if (!Array.isArray(inventory?.interfaces) || !Array.isArray(inventory.defaultRoutes)) throw new Error("Неполный каталог интерфейсов")
|
||||
if (!controller.signal.aborted) setResult({ path, inventory })
|
||||
}).catch(() => {
|
||||
if (!controller.signal.aborted) setResult({ path, error: "Не удалось прочитать интерфейсы CHR" })
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [backendUrl, path, refresh])
|
||||
return { ...(result?.path === path ? result : undefined), loading: path !== null && result?.path !== path,
|
||||
reload: () => { setResult(undefined); setRefresh(value => value + 1) } }
|
||||
}
|
||||
|
||||
function IxInventoryFields({ site, segmentId, backendUrl, fieldId, peers, readOnly, segmentName, edit }: {
|
||||
site: IxSite; segmentId?: string; backendUrl: string; fieldId: string; peers: { value: string; label: string }[]
|
||||
readOnly: boolean; segmentName: string; edit: (fields: Partial<IxSite>) => void
|
||||
}) {
|
||||
const { inventory, error, loading, reload } = useIxNodeInventory(backendUrl, site.serverId, segmentId)
|
||||
const suggested = site.routerId || (site.autoRouterId ? inventory?.routerId ?? "" : "")
|
||||
return <>
|
||||
<Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
|
||||
<Input id={fieldId + "-router"} value={suggested} placeholder="Подбирается автоматически" readOnly={readOnly}
|
||||
onChange={event => edit({ routerId: event.target.value, autoRouterId: !event.target.value })} />
|
||||
<FieldDescription>{suggested ? site.autoRouterId ? "Назначен автоматически" : "Задан вручную" :
|
||||
loading ? "Проверяем занятые идентификаторы…" : "Свободный ID будет выбран при сохранении."}</FieldDescription>
|
||||
</Field>
|
||||
<div className="grid min-w-0 gap-3 sm:col-span-2 lg:col-span-3">
|
||||
{site.serverId > 0 && <div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-sm text-muted-foreground" role="status">
|
||||
{loading ? "Читаем интерфейсы CHR…" : error ?? `Интерфейсы CHR · ${inventory?.interfaces?.length ?? 0}`}
|
||||
</span>
|
||||
<Button type="button" size="sm" variant="outline" disabled={loading} onClick={reload}>Обновить интерфейсы</Button>
|
||||
</div>}
|
||||
<IxSiteEditor site={site} segmentName={segmentName} readOnly={readOnly} edit={edit} peers={peers}
|
||||
inventory={inventory?.interfaces ?? []} />
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
|
||||
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId, section }: {
|
||||
section: "configuration" | "routes"
|
||||
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
|
||||
backendUrl: string; segmentId?: string
|
||||
}) {
|
||||
function updateSite(index: number, fields: Partial<IxSite>) {
|
||||
change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) })
|
||||
@@ -57,7 +106,7 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length
|
||||
|
||||
return <div className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
{section === "configuration" && <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
|
||||
<FramePanel>
|
||||
<Field className="max-w-md">
|
||||
@@ -67,17 +116,16 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
|
||||
</Field>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</Frame>}
|
||||
{configuration.sites.map((site, index) => {
|
||||
const fieldId = `ix-site-${index}`
|
||||
const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id)))
|
||||
return <Frame key={fieldId} spacing="sm">
|
||||
<FrameHeader className="flex-row items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<FrameTitle>Площадка {index + 1}</FrameTitle>
|
||||
{site.serverId > 0 && <FrameDescription className="wrap-anywhere">{nodeLabel(nodes, site.serverId)}</FrameDescription>}
|
||||
<FrameTitle>{section === "configuration" ? "Площадка " + (index + 1) : nodeLabel(nodes, site.serverId)}</FrameTitle>
|
||||
</div>
|
||||
{!readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
||||
{section === "configuration" && !readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
||||
aria-label={`Убрать площадку ${index + 1}`}
|
||||
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
|
||||
<XIcon aria-hidden />
|
||||
@@ -85,38 +133,34 @@ export function ConfigurationFields({ configuration, nodes, peers, readOnly, cha
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid gap-4">
|
||||
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Field className="min-w-0">
|
||||
{section === "configuration" && <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
|
||||
<Select
|
||||
value={site.serverId ? String(site.serverId) : null}
|
||||
items={choices.map(node => ({ value: String(node.id), label: node.name }))}
|
||||
disabled={readOnly}
|
||||
onValueChange={value => { if (value) updateSite(index, { serverId: Number(value) }) }}
|
||||
onValueChange={value => { if (value && Number(value) !== site.serverId) updateSite(index, { ...newSite(), 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">
|
||||
</Field>}
|
||||
{section === "routes" && <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
|
||||
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
|
||||
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
|
||||
</Field>
|
||||
<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>
|
||||
</Field>}
|
||||
{section !== "configuration" && <IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId}
|
||||
readOnly={readOnly} segmentName={configuration.name} edit={fields => updateSite(index, fields)}
|
||||
peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
|
||||
.map(node => ({ value: String(node.id), label: node.name }))} />}
|
||||
</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"
|
||||
{section === "configuration" && !readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
|
||||
<PlusIcon aria-hidden />Добавить площадку
|
||||
</Button>}
|
||||
|
||||
+227
-125
@@ -3,13 +3,16 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon, Trash2Icon } 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 { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxLinuxClientRequest, type IxLinuxPath, type IxTransitRequest, 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 { ServerRailLayout, ServerRailMobileButton } from "@/components/server-rail-layout"
|
||||
import { ALL_SERVERS_ID } from "@/components/server-tile-rail"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
@@ -18,14 +21,25 @@ import { can, ensureAuthConfig } from "@/lib/auth"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
|
||||
import { IxLinuxClients } from "./ix-linux-clients"
|
||||
import { IxExits } from "./ix-exits"
|
||||
|
||||
type Tab = "configuration" | "routes" | "changes" | "linux"
|
||||
type Tab = "configuration" | "routes" | "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 download(name: string, content: string) {
|
||||
const url = URL.createObjectURL(new Blob([content], { type: "text/plain;charset=utf-8" }))
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = name
|
||||
link.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
|
||||
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
|
||||
|
||||
function RouterOsChanges({ changes, nodes }: { changes: IxWebPlan["changes"]; nodes: IxNode[] }) {
|
||||
@@ -57,9 +71,13 @@ export default function IxPage() {
|
||||
const [draft, setDraft] = useState<IxConfiguration | null>(null)
|
||||
const [advanced, setAdvanced] = useState<string | null>(null)
|
||||
const [filter, setFilter] = useState("")
|
||||
const [activeNode, setActiveNode] = useState(ALL_SERVERS_ID)
|
||||
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
|
||||
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
|
||||
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
|
||||
const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null)
|
||||
const [review, setReview] = useState("")
|
||||
const [reviewError, setReviewError] = useState("")
|
||||
const [plan, setPlan] = useState<IxWebPlan | null>(null)
|
||||
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
|
||||
const [tab, setTab] = useState<Tab>("configuration")
|
||||
@@ -109,8 +127,10 @@ export default function IxPage() {
|
||||
}
|
||||
}, [inDetail])
|
||||
|
||||
const rows = segments.filter(segment => segment.configuration.name.includes(filter.trim().toLowerCase()))
|
||||
const enabledNodes = nodes.filter(node => node.enabled)
|
||||
const rows = segments.filter(segment => (activeNode === ALL_SERVERS_ID ||
|
||||
segment.configuration.sites.some(site => String(site.serverId) === activeNode)) &&
|
||||
segment.configuration.name.includes(filter.trim().toLowerCase()))
|
||||
const enabledNodes = nodes.filter(node => node.enabled && (activeNode === ALL_SERVERS_ID || String(node.id) === activeNode))
|
||||
const live = prefsHydrated && mode === "live"
|
||||
const canCreate = live && write && !loading && enabledNodes.length > 0
|
||||
const savedConfiguration = selected ? json(selected.configuration) : null
|
||||
@@ -119,21 +139,25 @@ export default function IxPage() {
|
||||
|
||||
function invalidateReview() {
|
||||
setPlan(null)
|
||||
setReview("")
|
||||
setReviewError("")
|
||||
setRemovalPlan(null)
|
||||
setNotice("")
|
||||
}
|
||||
|
||||
function open(segment: IxSegment | null) {
|
||||
function open(segment: IxSegment | null, defaultTab: Tab = segment ? "linux" : "configuration") {
|
||||
focusAfterNavigation.current = !inDetail
|
||||
setSelected(segment)
|
||||
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setLinuxBindings([])
|
||||
setTab("configuration")
|
||||
setTab(defaultTab)
|
||||
setError("")
|
||||
invalidateReview()
|
||||
if (defaultTab === "linux" && segment?.appliedRevision) void perform(() => loadLinuxBindings(segment))
|
||||
}
|
||||
|
||||
function close() {
|
||||
@@ -145,7 +169,9 @@ export default function IxPage() {
|
||||
}
|
||||
|
||||
function change(): IxChange {
|
||||
const configuration = ixSegmentConfigurationSchema.parse(advanced === null ? draft : JSON.parse(advanced))
|
||||
const configuration = ixSegmentConfigurationSchema.parse(advanced === null && draft
|
||||
? { ...draft, sites: draft.sites.map(site => ({ ...site, routerId: site.routerId || (site.autoRouterId ? "0.0.0.0" : "") })) }
|
||||
: JSON.parse(advanced ?? "null"))
|
||||
return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration }
|
||||
}
|
||||
|
||||
@@ -153,23 +179,29 @@ export default function IxPage() {
|
||||
setBusy(true)
|
||||
setError("")
|
||||
setNotice("")
|
||||
try { await work() } catch (error) { setError(describe(error)) }
|
||||
try { await work(); return true } catch (error) { setError(describe(error)); return false }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (selected && !dirty) {
|
||||
await reviewSegment(selected, selected.configuration.name)
|
||||
return
|
||||
}
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
|
||||
open(segment)
|
||||
setSegments(current => current.some(item => item.id === segment.id)
|
||||
? current.map(item => item.id === segment.id ? segment : item)
|
||||
: [segment, ...current])
|
||||
setNotice("Черновик сохранён")
|
||||
await reviewSegment(segment, segment.configuration.name)
|
||||
}
|
||||
|
||||
async function prepare() {
|
||||
if (!selected || !canPlan) return
|
||||
async function prepare(segment: IxSegment, resume = false) {
|
||||
setPlan(null)
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/plan", post({ revision: selected.revision })))
|
||||
setReviewError("")
|
||||
try {
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + segment.id + "/plan", post({
|
||||
revision: segment.revision, ...(resume && { resume }),
|
||||
})))
|
||||
} catch (error) {
|
||||
setReviewError(describe(error))
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareRemoval() {
|
||||
@@ -193,31 +225,39 @@ export default function IxPage() {
|
||||
setPlan(null)
|
||||
try {
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
|
||||
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest }))
|
||||
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest, ...(plan.resume && { resume: true }) }))
|
||||
setSelected(segment)
|
||||
setDraft(segment.configuration)
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setLinuxBindings([])
|
||||
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
|
||||
setReview("")
|
||||
setReviewError("")
|
||||
setNotice("Конфигурация IX применена")
|
||||
if (tab === "linux" || selected.appliedRevision === null) {
|
||||
setTab("linux")
|
||||
await loadLinuxBindings(segment).catch(error => setError(describe(error)))
|
||||
} else if (tab === "routes") {
|
||||
await observe(segment).catch(error => setError(describe(error)))
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(describe(error) + " Проверьте состояние сегмента перед повторным применением.")
|
||||
setReviewError(describe(error))
|
||||
}
|
||||
}
|
||||
|
||||
async function observe() {
|
||||
if (!selected?.appliedRevision) return
|
||||
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${selected.id}/status`)
|
||||
async function observe(segment = selected) {
|
||||
if (!segment?.appliedRevision) return
|
||||
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${segment.id}/status`)
|
||||
setObservations(sites)
|
||||
}
|
||||
|
||||
async function loadLinuxBindings() {
|
||||
if (!selected) return
|
||||
async function loadLinuxBindings(segment = selected) {
|
||||
if (!segment) return
|
||||
setLinux(null)
|
||||
setLinuxBindings([])
|
||||
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${selected.id}/linux`)
|
||||
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${segment.id}/linux`)
|
||||
setLinuxBindings(items)
|
||||
}
|
||||
|
||||
@@ -225,27 +265,99 @@ export default function IxPage() {
|
||||
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}`)
|
||||
if (binding.managedWireguard && write) {
|
||||
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
|
||||
download(access.filename, access.template)
|
||||
setNotice("Конфигурация WireGuard скачана")
|
||||
return
|
||||
}
|
||||
const access = binding.policy && binding.kind === "gre-ipsec" && write
|
||||
? await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
|
||||
: await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
|
||||
setLinux({ ...binding, ...access })
|
||||
}
|
||||
|
||||
async function inspectLinux(binding: IxLinuxBinding) {
|
||||
if (!selected) return
|
||||
setLinuxPath(null)
|
||||
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
|
||||
const path = await requestJson<IxLinuxPath>(backendUrl, `/api/ix/segments/${selected.id}/linux/path?${query}`)
|
||||
setLinuxPath({ name: binding.name, interfaceName: binding.interfaceName, ...path })
|
||||
}
|
||||
|
||||
async function stageClient(input: IxLinuxClientRequest | IxLinuxBinding) {
|
||||
if (!selected || dirty || !write) return
|
||||
const path = `/api/ix/segments/${selected.id}`
|
||||
const result = "revision" in input
|
||||
? await requestJson<{ segment: IxSegment; interfaceName: string }>(backendUrl, path + "/linux", post(input))
|
||||
: await requestJson<{ segment: IxSegment }>(backendUrl, path + "/linux/revoke",
|
||||
post({ revision: selected.revision, serverId: input.serverId, interfaceName: input.interfaceName }))
|
||||
await reviewSegment(result.segment, "revision" in input ? "Доступ клиента " + input.name : "Отзыв доступа " + (input.name ?? input.interfaceName))
|
||||
}
|
||||
|
||||
async function stageTransit(input: IxTransitRequest) {
|
||||
if (!selected || dirty || !write) return
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
|
||||
`/api/ix/segments/${selected.id}/transit`, post(input))
|
||||
await reviewSegment(segment, "Выход через " + nodeLabel(peers, input.targetServerId))
|
||||
}
|
||||
|
||||
async function reviewSegment(segment: IxSegment, title: string) {
|
||||
setSelected(segment)
|
||||
setDraft(segment.configuration)
|
||||
setAdvanced(null)
|
||||
setSegments(current => current.some(item => item.id === segment.id)
|
||||
? current.map(item => item.id === segment.id ? segment : item) : [segment, ...current])
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setReview(title)
|
||||
await prepare(segment)
|
||||
}
|
||||
|
||||
function closeReview() {
|
||||
if (busy) return
|
||||
setReview("")
|
||||
setPlan(null)
|
||||
setReviewError("")
|
||||
setNotice("Изменения сохранены в черновике. Нажмите «Сохранить», чтобы вернуться к подтверждению.")
|
||||
}
|
||||
|
||||
function showTab(next: Tab) {
|
||||
if (next === tab || busy) return
|
||||
if (advanced !== null) {
|
||||
try { setDraft(change().configuration); setAdvanced(null) } catch (error) { setError(describe(error)); return }
|
||||
}
|
||||
setError("")
|
||||
setTab(next)
|
||||
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
|
||||
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
|
||||
}
|
||||
|
||||
const settingsProps = draft && {
|
||||
configuration: draft, nodes, peers, backendUrl, segmentId: selected?.id, readOnly: !live || !write || busy,
|
||||
change: (value: IxConfiguration) => { setDraft(value); invalidateReview() },
|
||||
}
|
||||
|
||||
const listEmpty = error ? "Не удалось загрузить список" :
|
||||
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
|
||||
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
|
||||
!live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node."
|
||||
|
||||
return <>
|
||||
<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]} />
|
||||
return <ServerRailLayout items={nodes.map(node => ({ ...node, id: String(node.id), type: "ix-node", selectable: node.enabled }))}
|
||||
selectedId={activeNode} allCount={nodes.length} loading={loading} showCount={false} preserveSelection onSelect={id => {
|
||||
if (busy || id === activeNode) return
|
||||
setActiveNode(id)
|
||||
setFilter("")
|
||||
const forNode = segments.filter(segment => segment.configuration.sites.some(site => String(site.serverId) === id))
|
||||
if (forNode.length === 1) open(forNode[0], "linux")
|
||||
else close()
|
||||
}}
|
||||
header={<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]}
|
||||
actions={<ServerRailMobileButton />} />}>
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
|
||||
<div className="mx-auto flex w-full max-w-6xl min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
|
||||
<div className="flex w-full min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
|
||||
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
|
||||
<ArrowLeftIcon aria-hidden />Все сегменты
|
||||
</Button>}
|
||||
@@ -258,30 +370,33 @@ export default function IxPage() {
|
||||
{inDetail && selected && <SegmentStatus segment={selected} />}
|
||||
</div>
|
||||
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
|
||||
Ревизия {selected.revision}{selected.appliedRevision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
|
||||
Ревизия {selected.revision}{selected.appliedRevision && selected.appliedRevision !== selected.revision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
|
||||
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
|
||||
</div>
|
||||
{inDetail && selected && live && write && <AlertDialog open={removalPlan !== null}
|
||||
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
|
||||
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
|
||||
<Trash2Icon aria-hidden />Удалить сегмент
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{selected.appliedRevision
|
||||
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
|
||||
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>}
|
||||
{inDetail && live && write && <div className="flex flex-wrap items-center gap-2">
|
||||
{(dirty || canPlan) && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(save)}>Сохранить</Button>}
|
||||
{selected && <AlertDialog open={removalPlan !== null}
|
||||
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
|
||||
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
|
||||
<Trash2Icon aria-hidden />Удалить сегмент
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{selected.appliedRevision
|
||||
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
|
||||
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>}
|
||||
</div>}
|
||||
{!inDetail && <div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
|
||||
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
|
||||
@@ -308,16 +423,16 @@ export default function IxPage() {
|
||||
</Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3">
|
||||
<div className="min-w-0 overflow-x-auto border-b pb-1">
|
||||
<TabsList variant="line" aria-label="Разделы сегмента">
|
||||
<TabsTrigger value="configuration">Конфигурация</TabsTrigger>
|
||||
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
|
||||
<TabsTrigger value="routes">Маршруты и BGP</TabsTrigger>
|
||||
<TabsTrigger value="changes">План изменений</TabsTrigger>
|
||||
{selected && <>
|
||||
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
|
||||
<TabsTrigger value="routes">Маршрутизация</TabsTrigger>
|
||||
</>}
|
||||
<TabsTrigger value="configuration">Настройки IX</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<TabsContent value="configuration" className="grid min-w-0 gap-3">
|
||||
{advanced === null ? <ConfigurationFields configuration={draft} nodes={nodes} peers={peers} readOnly={!live || !write || busy}
|
||||
change={value => { setDraft(value); invalidateReview() }} /> : <Frame spacing="sm">
|
||||
{advanced === null ? settingsProps && <ConfigurationFields {...settingsProps} section="configuration" /> : <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
|
||||
<FramePanel>
|
||||
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
|
||||
@@ -325,7 +440,6 @@ export default function IxPage() {
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{write && <Button type="button" size="sm" disabled={busy || !live} onClick={() => void perform(save)}>Сохранить черновик</Button>}
|
||||
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
|
||||
{write ? "Редактировать JSON" : "Показать JSON"}
|
||||
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
@@ -336,8 +450,10 @@ export default function IxPage() {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="routes" className="grid min-w-0 gap-3">
|
||||
{!selected?.appliedRevision ? <EmptyState title="Конфигурация ещё не применена"
|
||||
description="Маршруты и BGP-сессии появятся после применения плана." className="py-8" /> : <>
|
||||
{selected && !dirty && live && write && <IxExits segment={selected} nodes={peers} backendUrl={backendUrl} busy={busy}
|
||||
error={error} save={input => perform(() => stageTransit(input))} />}
|
||||
{settingsProps && <ConfigurationFields {...settingsProps} section="routes" />}
|
||||
{!!selected?.appliedRevision && <>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
|
||||
<RefreshCwIcon aria-hidden />Обновить состояние
|
||||
@@ -349,31 +465,24 @@ export default function IxPage() {
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="linux" className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
{selected ? <IxLinuxClients key={selected.id} segment={selected} nodes={peers} backendUrl={backendUrl}
|
||||
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
|
||||
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
|
||||
refresh={() => void perform(loadLinuxBindings)} view={binding => void perform(() => exportLinux(binding))}
|
||||
inspect={binding => void perform(() => inspectLinux(binding))} />
|
||||
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
|
||||
{linuxPath && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Доступ для Linux-серверов</FrameTitle>
|
||||
<FrameDescription>Выдайте каждому серверу отдельное подключение из применённой ревизии сегмента.</FrameDescription>
|
||||
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
|
||||
<FrameDescription>{linuxPath.policy ?? "Только сети IX"} · {new Date(linuxPath.observedAt).toLocaleString("ru-RU")}</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 className="grid gap-2 text-sm">
|
||||
<p className="text-muted-foreground">Чтение FIB CHR. Доставку пакетов проверяют с Linux-клиента.</p>
|
||||
{linuxPath.routes.length ? <ul className="grid gap-2">{linuxPath.routes.map((route, index) => <li key={index}>
|
||||
<code>{route.prefix}</code> · {route.immediateGateway || route.gateway || "—"} · {route.active ? "активен" : "неактивен"}
|
||||
</li>)}</ul> : <p>Подходящих маршрутов сейчас нет.</p>}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</Frame>}
|
||||
{linux && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Конфигурация Linux · {linux.interfaceName}</FrameTitle>
|
||||
@@ -381,12 +490,19 @@ export default function IxPage() {
|
||||
</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.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
|
||||
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
|
||||
: linux.policy && write ? "Подключите файл к strongSwan. Храните конфиг с PSK с правами доступа только для root."
|
||||
: "Для подключения нужен индивидуальный PSK, выданный оператором."}</p>
|
||||
{(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>}
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}>
|
||||
Скачать {linux.managedWireguard ? "шаблон" : linux.filename}
|
||||
</Button>
|
||||
{linux.setup && <>
|
||||
<pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать команды настройки</Button>
|
||||
</>}
|
||||
{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(", ")}</>}
|
||||
@@ -395,43 +511,29 @@ export default function IxPage() {
|
||||
</Frame>}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="changes" className="grid min-w-0 gap-3">
|
||||
<Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Изменения RouterOS</FrameTitle>
|
||||
<FrameDescription>Предпросмотр сравнивает сохранённую ревизию с текущим состоянием узлов.</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
{!write ? <p className="text-sm text-muted-foreground">Нужно право изменять сетевую конфигурацию.</p>
|
||||
: dirty ? <p className="text-sm text-muted-foreground">Сохраните черновик на вкладке «Конфигурация».</p>
|
||||
: selected?.appliedRevision === selected?.revision ? <p className="text-sm text-muted-foreground">Текущая ревизия применена.</p>
|
||||
: <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>}
|
||||
<RouterOsChanges changes={plan.changes} nodes={nodes} />
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger render={<Button type="button" size="sm" className="w-fit" disabled={busy || !canPlan} />}>
|
||||
Применить план
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Применить конфигурацию IX?</AlertDialogTitle>
|
||||
<AlertDialogDescription>Будет применена ревизия {plan.revision} сегмента {selected?.configuration.name}. Операций RouterOS: {plan.changes.length}.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={() => void perform(apply)}>Применить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</TabsContent>
|
||||
</Tabs>}
|
||||
<Dialog open={!!review} onOpenChange={open => { if (!open) closeReview() }}>
|
||||
<DialogContent showCloseButton={!busy} className="max-h-[85dvh] overflow-y-auto sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Подтвердите сохранение</DialogTitle>
|
||||
<DialogDescription>{review} · ревизия {selected?.revision}. После подтверждения изменения вступят в силу на узлах IX.</DialogDescription>
|
||||
</DialogHeader>
|
||||
{reviewError ? <Alert variant="destructive"><AlertTitle>Не удалось подтвердить состояние IX</AlertTitle>
|
||||
<AlertDescription>{reviewError}</AlertDescription></Alert>
|
||||
: plan ? <>
|
||||
<p className="text-sm font-medium">{plan.changes.length ? "Операций RouterOS: " + plan.changes.length : "RouterOS уже настроена. Будет отмечена применённая ревизия."}</p>
|
||||
<RouterOsChanges changes={plan.changes} nodes={peers} />
|
||||
</> : <p role="status" className="text-sm text-muted-foreground">{busy ? "Проверяем конфигурацию на узлах…" : "Обновите сравнение перед сохранением."}</p>}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={closeReview}>Отмена</Button>
|
||||
{reviewError && selected && <Button type="button" variant="outline" disabled={busy}
|
||||
onClick={() => void perform(() => prepare(selected, true))}>Сверить и продолжить</Button>}
|
||||
{plan ? <Button type="button" disabled={busy || !canPlan} onClick={() => void perform(apply)}>Подтвердить</Button>
|
||||
: reviewError && selected && <Button type="button" disabled={busy} onClick={() => void perform(() => prepare(selected))}>Повторить проверку</Button>}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</ServerRailLayout>
|
||||
}
|
||||
@@ -66,8 +66,10 @@ import {
|
||||
hopHasRate,
|
||||
matchNetflowForGreEdge,
|
||||
matchNetflowForWan,
|
||||
type GreNetflowHop,
|
||||
type MatchedNetflowHop,
|
||||
} from "@/lib/map-netflow-hops"
|
||||
import { useMapGreTraffic } from "@/hooks/use-map-gre-traffic"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { CountryFlagSvg } from "@/components/network-map/country-flag-svg"
|
||||
@@ -599,19 +601,21 @@ function NetflowRateBadge({
|
||||
mx,
|
||||
my,
|
||||
hop,
|
||||
liveInterface,
|
||||
onOpen,
|
||||
}: {
|
||||
mx: number
|
||||
my: number
|
||||
hop: MatchedNetflowHop
|
||||
hop: Pick<MatchedNetflowHop, "bps" | "bpsFwd" | "bpsRev">
|
||||
liveInterface?: string
|
||||
onOpen?: (e: React.SyntheticEvent<SVGElement>) => void
|
||||
}) {
|
||||
const showDir = hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
const showDir = !!liveInterface || hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
const bw = showDir ? 86 : 72
|
||||
const bh = showDir ? 32 : 20
|
||||
const bh = liveInterface ? 41 : showDir ? 32 : 20
|
||||
return (
|
||||
<g
|
||||
role={onOpen?"button":undefined} aria-label={onOpen?"Поток NetFlow между узлами":undefined} tabIndex={onOpen?0:undefined} className="network-map-focusable"
|
||||
role={onOpen?"button":undefined} aria-label={onOpen ? liveInterface ? "Текущий трафик GRE " + liveInterface : "Поток NetFlow между узлами" : undefined} tabIndex={onOpen?0:undefined} className="network-map-focusable"
|
||||
onKeyDown={e=>{if(onOpen&&(e.key==="Enter"||e.key===" ")){e.preventDefault();e.stopPropagation();onOpen(e)}}}
|
||||
transform={`translate(${mx},${my})`}
|
||||
style={{ cursor: onOpen ? "pointer" : "default" }}
|
||||
@@ -619,7 +623,7 @@ function NetflowRateBadge({
|
||||
onClick={(e) => { e.stopPropagation(); onOpen?.(e) }}
|
||||
>
|
||||
<title>
|
||||
Поток NetFlow между узлами за интервал карты, без overlay/mesh.
|
||||
{liveInterface ? "Текущий RX/TX интерфейса " + liveInterface : "Поток NetFlow между узлами за интервал карты, без overlay/mesh."}
|
||||
</title>
|
||||
<rect className="network-map-focus-ring" x={-bw / 2 - 4} y={-bh / 2 - 4} width={bw + 8} height={bh + 8} rx="9" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||
<rect
|
||||
@@ -632,14 +636,15 @@ function NetflowRateBadge({
|
||||
stroke="var(--status-online)"
|
||||
strokeWidth="1.15"
|
||||
/>
|
||||
<text textAnchor="middle" y={showDir ? "-4" : "4"} fontFamily="ui-monospace,monospace">
|
||||
<text textAnchor="middle" y={liveInterface ? "-8" : showDir ? "-4" : "4"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online-fg)" fontSize="8" fontWeight="700">{formatNetflowRate(hop)}</tspan>
|
||||
</text>
|
||||
{showDir && (
|
||||
<text textAnchor="middle" y="10" fontFamily="ui-monospace,monospace">
|
||||
<text textAnchor="middle" y={liveInterface ? "4" : "10"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online)" fontSize="6.5" fontWeight="600">{formatNetflowDir(hop)}</tspan>
|
||||
</text>
|
||||
)}
|
||||
{liveInterface && <text textAnchor="middle" y="14" fill="var(--muted-foreground)" fontSize="6.5">Live GRE</text>}
|
||||
</g>
|
||||
)
|
||||
}
|
||||
@@ -1630,15 +1635,28 @@ function NetworkMapContent() {
|
||||
}, [greEdges])
|
||||
|
||||
const netflowByGreKey = useMemo(() => {
|
||||
const m = new Map<string, MatchedNetflowHop>()
|
||||
const m = new Map<string, GreNetflowHop>()
|
||||
if (!showNetflow) return m
|
||||
for (const e of greEdges) {
|
||||
const hop = matchNetflowForGreEdge(e, mapHops)
|
||||
if (hopHasRate(hop)) m.set(greEdgeKey(e), hop)
|
||||
if (hop && hopHasRate(hop)) m.set(greEdgeKey(e), hop)
|
||||
}
|
||||
return m
|
||||
}, [greEdges, mapHops, showNetflow])
|
||||
|
||||
const greTrafficTargets = useMemo(() => {
|
||||
if (!useLiveData || !showNetflow || (!flowReadAt && !flowError)) return []
|
||||
return greEdges.flatMap(edge => {
|
||||
const edgeId = greEdgeKey(edge)
|
||||
const owner = edge.fromServer.id === edge.tunnel.serverId ? edge.fromServer : edge.toServer
|
||||
return edge.tunnel.enabled && edge.tunnel.status !== "down" && owner.status !== "offline" &&
|
||||
edge.tunnel.name && !netflowByGreKey.get(edgeId)?.exactInterface
|
||||
? [{ edgeId, serverId: owner.id, iface: edge.tunnel.name }]
|
||||
: []
|
||||
})
|
||||
}, [useLiveData, showNetflow, flowReadAt, flowError, greEdges, netflowByGreKey])
|
||||
const getGreLiveRate = useMapGreTraffic(backendUrl, greTrafficTargets)
|
||||
|
||||
const netflowByWanKey = useMemo(() => {
|
||||
const m = new Map<string, MatchedNetflowHop>()
|
||||
if (!showNetflow) return m
|
||||
@@ -2183,7 +2201,7 @@ function NetworkMapContent() {
|
||||
<PopoverContent align="start" aria-label="Слои карты" className="gap-0.5">
|
||||
{([
|
||||
{ key: "showPingBadges", label: "Ping-значки", val: showPingBadges, set: setShowPingBadges, hint: "P" },
|
||||
{ key: "showNetflow", label: "NetFlow", val: showNetflow, set: setShowNetflow, hint: "" },
|
||||
{ key: "showNetflow", label: "Трафик на линиях", val: showNetflow, set: setShowNetflow, hint: "" },
|
||||
{ key: "showServices", label: "Назначения", val: showServices, set: setShowServices, hint: "" },
|
||||
{ key: "showAnimDots", label: "Анимация трафика", val: showAnimDots, set: setShowAnimDots, hint: "" },
|
||||
{ key: "showMinimap", label: "Минимап", val: showMinimap, set: setShowMinimap, hint: "M" },
|
||||
@@ -2335,7 +2353,8 @@ function NetworkMapContent() {
|
||||
tBadge,
|
||||
normalPx,
|
||||
)
|
||||
const flowHop = netflowByGreKey.get(edgeId)
|
||||
const liveRate = getGreLiveRate(edgeId)
|
||||
const flowHop = liveRate ?? netflowByGreKey.get(edgeId)
|
||||
const flowPos = edgeBadgePosition(
|
||||
e.from.x,
|
||||
e.from.y,
|
||||
@@ -2364,7 +2383,7 @@ function NetworkMapContent() {
|
||||
strokeWidth={
|
||||
highlightedPath && greMatchesPath(e, highlightedPath)
|
||||
? 3.4
|
||||
: hopHasRate(flowHop) ? 2.6 : 1.5
|
||||
: flowHop && flowHop.bps > 0 ? 2.6 : 1.5
|
||||
}
|
||||
strokeDasharray={e.tunnel.ipsec ? "7 4" : "none"}
|
||||
opacity={ts.opacity}
|
||||
@@ -2400,11 +2419,12 @@ function NetworkMapContent() {
|
||||
outerSummary={greOuterSummaryLine(e.tunnel, fromN, toN, greResolvedMap)}
|
||||
/>
|
||||
)}
|
||||
{showNetflow && hopHasRate(flowHop) && (
|
||||
{showNetflow && flowHop && (
|
||||
<NetflowRateBadge
|
||||
mx={flowPos.mx}
|
||||
my={flowPos.my}
|
||||
hop={flowHop}
|
||||
liveInterface={liveRate ? e.tunnel.name : undefined}
|
||||
onOpen={openGreDetail}
|
||||
/>
|
||||
)}
|
||||
@@ -2881,7 +2901,10 @@ function NetworkMapContent() {
|
||||
{(() => {
|
||||
const edge = selectedGreEdge
|
||||
const t = edge.tunnel
|
||||
const tunnelOwner = edge.fromServer.id === t.serverId ? edge.fromServer : edge.toServer
|
||||
const selectedEdgeId = greEdgeKey(edge)
|
||||
const liveRate = getGreLiveRate(selectedEdgeId)
|
||||
const greFlow = liveRate ?? netflowByGreKey.get(selectedEdgeId)
|
||||
const localWanName = ifaceNameForGreOuterIp(edge.fromServer, t.localAddress, greResolvedMap)
|
||||
const remoteWanName = ifaceNameForGreOuterIp(edge.toServer, t.remoteAddress, greResolvedMap)
|
||||
const baseProbe = greTunnelProbe(t,!useLiveData)
|
||||
@@ -2945,15 +2968,11 @@ function NetworkMapContent() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Поток (NetFlow)</span>
|
||||
<span className="text-xs text-muted-foreground">{liveRate ? "Текущий RX/TX GRE" : "Поток (NetFlow)"}</span>
|
||||
<span className="text-xs font-mono font-semibold text-emerald-400">
|
||||
{(() => {
|
||||
const hop = netflowByGreKey.get(selectedEdgeId)
|
||||
if (!hopHasRate(hop)) return "—"
|
||||
return hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
? formatNetflowDir(hop)
|
||||
: formatNetflowRate(hop)
|
||||
})()}
|
||||
{greFlow ? liveRate || greFlow.bpsFwd > 0 && greFlow.bpsRev > 0
|
||||
? formatNetflowDir(greFlow)
|
||||
: formatNetflowRate(greFlow) : "—"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground pt-2 leading-snug">
|
||||
@@ -2961,7 +2980,7 @@ function NetworkMapContent() {
|
||||
? "Ping и/или TX/RX — с последнего прогона speed-пробы; проба сопоставляется с этим GRE по WAN и интерфейсам. "
|
||||
: useLiveData?"Измерения GRE неизвестны: нет подходящей пробы. ":"Измерения демонстрационные. "}
|
||||
{spGr?"Проба "+spGr.id+" · время Ping: "+(spGr.lastPingAt?new Date(spGr.lastPingAt).toLocaleString("ru-RU"):"неизвестно")+" · время TX/RX неизвестно. ":""}
|
||||
Поток по данным NetFlow за {mapWindowSec / 60} мин, без overlay/mesh.
|
||||
{liveRate ? "Текущий трафик по счётчикам интерфейса RouterOS." : `Поток по данным NetFlow за ${mapWindowSec / 60} мин, без overlay/mesh.`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2973,7 +2992,7 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">На узле</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{edge.fromServer.name}</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{tunnelOwner.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Пир (каталог)</span>
|
||||
@@ -3415,11 +3434,12 @@ function NetworkMapContent() {
|
||||
fromServer && toServer ? speedProbeByTunnelId.get(tunnelPanelKey) : undefined
|
||||
const merged = mergeGreMetricsWithSpeedProbe(spGre, baseProbe)
|
||||
const pc = pingColor(merged.pingMs)
|
||||
const greFlow = netflowByGreKey.get(tunnelPanelKey)
|
||||
const liveRate = getGreLiveRate(tunnelPanelKey)
|
||||
const greFlow = liveRate ?? netflowByGreKey.get(tunnelPanelKey)
|
||||
const showMetrics =
|
||||
merged.pingMs != null ||
|
||||
(merged.dlMbps != null && merged.ulMbps != null) ||
|
||||
hopHasRate(greFlow)
|
||||
!!greFlow
|
||||
return (
|
||||
<div key={tunnelPanelKey} className="rounded-md border border-border/60 px-3 py-2 bg-muted/20">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
@@ -3459,9 +3479,9 @@ function NetworkMapContent() {
|
||||
↓{merged.dlMbps} ↑{merged.ulMbps}
|
||||
</span>
|
||||
)}
|
||||
{hopHasRate(greFlow) && (
|
||||
{greFlow && (
|
||||
<span className="text-[9px] ml-1.5 text-emerald-400">
|
||||
{formatNetflowRate(greFlow)}
|
||||
{formatNetflowRate(greFlow)}{liveRate ? " · Live GRE" : ""}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -471,6 +471,13 @@
|
||||
"operations": [],
|
||||
"reason": "Служебная проекция для выбора площадок в интерфейсе. В MCP доступ к серверам определяется областью подключения."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/nodes/:serverId/inventory",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.inventory"],
|
||||
"reason": "Общее чтение интерфейсов, шлюзов и кандидата Router ID. MCP проверяет серверную область, а контекст редактируемого сегмента используется в WebUI."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments",
|
||||
@@ -485,6 +492,13 @@
|
||||
"operations": [],
|
||||
"reason": "Шаблон подключения Linux оператор получает в интерфейсе для локальной настройки клиента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/linux/path",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.linux-path"],
|
||||
"reason": "Общее чтение маршрутов Linux-клиента из применённой ревизии. MCP проверяет доступ к узлу клиента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/status",
|
||||
@@ -1106,7 +1120,7 @@
|
||||
"operations": [
|
||||
"traffic.live.read"
|
||||
],
|
||||
"reason": "Общий readTrafficLiveSample; MCP возвращает ограниченную серию до трёх срезов вместо бесконечного SSE. Полнота суммы, направление RX/TX, отзыв доступа и смена источника проверяются перед каждым новым native-запросом."
|
||||
"reason": "Общий readTrafficLiveSample для разового чтения интерфейса, SSE и ограниченной MCP-серии. Источник проверяется перед каждым новым native-запросом."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
@@ -1618,6 +1632,27 @@
|
||||
"operations": ["network.ix.configure"],
|
||||
"reason": "Пользователь WebUI подтверждает просмотренную ревизию. MCP применяет свой подтверждённый план через общий исполнитель IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI сохраняет одной ревизией клиента Linux и выбранный транзит. Записи на RouterOS идут после подтверждения изменений."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux/credential",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI выдаёт действующий PSK или ключ WireGuard оператору с правом изменения сети и записью в журнале. Для WireGuard MCP возвращает защищённую ссылку через network.wireguard.export."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux/revoke",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI сохраняет черновик отзыва клиента. Удаление конфигурации RouterOS выполняется отдельным подтверждённым планом."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/removal-plan",
|
||||
@@ -1625,6 +1660,13 @@
|
||||
"operations": ["network.ix.delete"],
|
||||
"reason": "Предпросмотр управляемых объектов перед явным подтверждением удаления сегмента."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/transit",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Мастер WebUI собирает черновик связи и выхода по инвентарю двух узлов. Применение к обоим маршрутизаторам требует отдельного подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "DELETE",
|
||||
"path": "/api/ix/segments/:id",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { isIPv4 } from "node:net"
|
||||
import { homedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
export const hosts = ["194.226.121.150", "104.165.244.7"] as const
|
||||
const targets = process.env.MMAPP_IX_CHR_HOSTS?.split(",").map(value => value.trim()) ?? []
|
||||
if (targets.length !== 2 || new Set(targets).size !== 2 || !targets.every(isIPv4)) {
|
||||
throw new Error("MMAPP_IX_CHR_HOSTS must identify two distinct, isolated CHR IPv4 addresses")
|
||||
}
|
||||
export const hosts = [targets[0], targets[1]] as const
|
||||
const key = join(homedir(), ".ssh", "chr_claude")
|
||||
const known = process.env.MMAPP_IX_TEST_KNOWN_HOSTS ?? join(homedir(), ".ssh", "known_hosts")
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomBytes, randomUUID } from "node:crypto"
|
||||
import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
|
||||
import { mkdtemp } from "node:fs/promises"
|
||||
import { createServer } from "node:http"
|
||||
import { tmpdir } from "node:os"
|
||||
@@ -32,6 +32,7 @@ const rows: Record<string, Record<string, string>[]> = {
|
||||
}
|
||||
let writes = 0
|
||||
let deletes = 0
|
||||
let failPutAt = -1
|
||||
let failDeleteAt = -1
|
||||
const router = createServer(async (request, response) => {
|
||||
try {
|
||||
@@ -39,6 +40,7 @@ const router = createServer(async (request, response) => {
|
||||
let result: unknown
|
||||
if (request.method === "GET") result = rows[path] ?? []
|
||||
else if (request.method === "PUT") {
|
||||
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
|
||||
let raw = ""
|
||||
for await (const chunk of request) raw += chunk
|
||||
const { "place-before": place, ...fields } = JSON.parse(raw)
|
||||
@@ -128,13 +130,21 @@ try {
|
||||
await post(path + "/apply", { revision: 1, digest }, 409)
|
||||
assert.equal(writes, 0)
|
||||
const fresh = await post(path + "/plan", { revision: 1 }, 200)
|
||||
await post(path + "/plan", { revision: 1, resume: true }, 409)
|
||||
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)
|
||||
failPutAt = 1
|
||||
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 503)
|
||||
assert.equal(writes, 1)
|
||||
await post(path + "/plan", { revision: 1 }, 409)
|
||||
failPutAt = -1
|
||||
const resume = await post(path + "/plan", { revision: 1, resume: true }, 200)
|
||||
assert.equal(resume.changes.length, changes.length - 1)
|
||||
const applied = await post(path + "/apply", { revision: 1, digest: resume.digest, resume: true }, 200)
|
||||
assert.equal(applied.segment.appliedRevision, 2)
|
||||
assert.equal(applied.result.configurationVerified, true)
|
||||
assert.equal(applied.result.forwardingVerified, false)
|
||||
@@ -147,6 +157,7 @@ try {
|
||||
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
|
||||
assert.match(wg.template, /Table = off/)
|
||||
assert(!wg.template.includes("A".repeat(43)))
|
||||
await post(path + "/linux/credential", { serverId: Number(server.id), interfaceName: "wg-ix-web" }, 404)
|
||||
const gre = await linux("gre-client")
|
||||
assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/)
|
||||
assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/)
|
||||
@@ -240,7 +251,7 @@ try {
|
||||
}
|
||||
const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval",
|
||||
permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(),
|
||||
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "changes.apply", "operations.read"] } })
|
||||
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "network.wireguard.export", "changes.apply", "operations.read"] } })
|
||||
mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" })
|
||||
await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"),
|
||||
{ requestInit: { headers: { authorization: "Bearer " + mcpToken } } }))
|
||||
@@ -265,9 +276,104 @@ try {
|
||||
assert.equal(terminal.state, "applied", JSON.stringify(terminal))
|
||||
assert.equal(terminal.verification, "passed")
|
||||
assert.equal(deletes, writes)
|
||||
|
||||
const managed = (await post("", { revision: 0, configuration: { name: "ix-web-managed", sites: [
|
||||
{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" },
|
||||
] } }, 200)).segment
|
||||
const managedPath = "/" + managed.id
|
||||
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
|
||||
prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
|
||||
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
|
||||
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
|
||||
await post(managedPath + "/linux/credential", clientKey, 409)
|
||||
await post(managedPath + "/linux/credential", clientKey, 403, reader)
|
||||
const edited = await post(managedPath + "/linux", { ...clientInput, ...clientKey, revision: staged.segment.revision, name: "linux-renamed" }, 200)
|
||||
const provision = edited.segment.configuration.sites[0].interfaces[0].provisionWireguard
|
||||
assert.deepEqual(provision, staged.segment.configuration.sites[0].interfaces[0].provisionWireguard)
|
||||
const plan = await post(managedPath + "/plan", { revision: edited.segment.revision }, 200)
|
||||
await post(managedPath + "/apply", { revision: edited.segment.revision, digest: plan.digest }, 200)
|
||||
const credential = await post(managedPath + "/linux/credential", clientKey, 200)
|
||||
const privateKey = credential.template.match(/^PrivateKey = ([A-Za-z0-9+/]{43}=)$/m)?.[1]
|
||||
assert.ok(privateKey)
|
||||
const scalar = Buffer.from(privateKey, "base64")
|
||||
const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar]),
|
||||
format: "der", type: "pkcs8" })
|
||||
const publicKey = createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")
|
||||
assert.equal(publicKey, provision.peerPublicKey)
|
||||
assert.equal(rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)?.["public-key"], publicKey)
|
||||
assert(!JSON.stringify([edited, plan, rows]).includes(privateKey))
|
||||
const templateResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux?" + new URLSearchParams({
|
||||
serverId: String(clientKey.serverId), interfaceName: clientKey.interfaceName,
|
||||
}), { headers: { authorization: "Bearer " + reader } })
|
||||
assert.equal(templateResponse.status, 200)
|
||||
assert.match((await templateResponse.json()).template, /PrivateKey = <локальный_приватный_ключ>/)
|
||||
|
||||
const exportPlan = await call<{ planId: string; state: string }>("mm_wireguard_export_plan",
|
||||
{ ...clientKey, ixSegmentId: managed.id, format: "peer-conf" })
|
||||
assert.equal(exportPlan.state, "awaiting-approval")
|
||||
assert(!JSON.stringify(exportPlan).includes(privateKey))
|
||||
await mcpPost("plans/" + exportPlan.planId + "/decision", { approve: true })
|
||||
const exportOperation = await call<Operation>("mm_change_apply", { planId: exportPlan.planId, idempotencyKey: randomUUID() })
|
||||
let exported = exportOperation
|
||||
for (let attempts = 0; attempts < 50 && ["pending", "running"].includes(exported.state); attempts++) {
|
||||
await delay(200)
|
||||
exported = await call<Operation>("mm_operation_get", { operationId: exportOperation.id })
|
||||
}
|
||||
assert.equal(exported.state, "applied", JSON.stringify(exported))
|
||||
assert(!JSON.stringify(exported).includes(privateKey))
|
||||
const { rows: [{ result: receipt }] } = await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [exported.id])
|
||||
assert.equal(receipt.humanDownloadOnly, true)
|
||||
const secretRecords = await pool.query(`SELECT to_jsonb(s) AS record FROM mcp_operation_steps s WHERE operation_id=$1
|
||||
UNION ALL SELECT to_jsonb(p) FROM mcp_plans p WHERE id=$2
|
||||
UNION ALL SELECT to_jsonb(a) FROM mcp_artifacts a WHERE id=$3
|
||||
UNION ALL SELECT to_jsonb(a) FROM mcp_audit a WHERE actor_id IN ('ix-web-owner','ix-mcp-owner')`,
|
||||
[exported.id, exportPlan.planId, receipt.artifactId])
|
||||
assert(!JSON.stringify(secretRecords.rows).includes(privateKey))
|
||||
const download = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
|
||||
assert.equal(download.status, 200)
|
||||
assert.equal(await download.text(), credential.template)
|
||||
assert.equal(download.headers.get("cache-control"), "private, no-store")
|
||||
const denied = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + otherWriter } })
|
||||
assert.equal(denied.status, 403)
|
||||
const appliedPeer = rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)!
|
||||
appliedPeer.disabled = "true"
|
||||
const inactive = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
|
||||
assert.equal(inactive.status, 409)
|
||||
delete appliedPeer.disabled
|
||||
|
||||
const { rows: [exit] } = await pool.query(`INSERT INTO servers
|
||||
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
|
||||
VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port])
|
||||
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
|
||||
rows["/ip/address"].push(
|
||||
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
|
||||
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
|
||||
)
|
||||
rows["/ip/route"].push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0", "immediate-gw": "192.0.2.1%ether1", active: "true" })
|
||||
const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
|
||||
const remoteClient = { ...clientInput, name: "linux-remote", revision: credential.revision, transit }
|
||||
const beforeStage = writes
|
||||
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
|
||||
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
|
||||
assert.equal(writes, beforeStage)
|
||||
assert.equal(stagedRemote.segment.revision, credential.revision + 1)
|
||||
assert.equal(stagedRemote.segment.appliedRevision, credential.revision)
|
||||
const remoteSite = stagedRemote.segment.configuration.sites[0]
|
||||
assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name)
|
||||
const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface)
|
||||
assert.equal(transitBinding.peerServerId, Number(exit.id))
|
||||
const { ixReservedTunnelBindings } = await import("../../src/services/internet-exchange-store.js")
|
||||
assert((await ixReservedTunnelBindings(Number(exit.id))).some(binding => binding.name === transitBinding.name))
|
||||
const remotePlan = await post(managedPath + "/plan", { revision: stagedRemote.segment.revision }, 200)
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(exit.id) &&
|
||||
change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1"))
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard"))
|
||||
assert.equal(writes, beforeStage)
|
||||
|
||||
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
|
||||
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
|
||||
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions, mcpRemovalVerified: true }))
|
||||
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
|
||||
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true }))
|
||||
} finally {
|
||||
await mcp?.close()
|
||||
await app?.close()
|
||||
|
||||
@@ -14,6 +14,10 @@ const ixInterfaceRoutes = new Set([
|
||||
"GET /api/ix/topology",
|
||||
"POST /api/ix/preview",
|
||||
"POST /api/ix/segments",
|
||||
"POST /api/ix/segments/:id/linux",
|
||||
"POST /api/ix/segments/:id/linux/credential",
|
||||
"POST /api/ix/segments/:id/linux/revoke",
|
||||
"POST /api/ix/segments/:id/transit",
|
||||
])
|
||||
for (const route of coverage.routes) {
|
||||
assert.equal(route.status === "mediated", route.operations.length > 0, routeKey(route))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod"
|
||||
import { ixChangeSchema, type IxChange } from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { applyIxChange, currentIxChange, ixTarget, observeIxSegment, prepareIxChange, prepareIxRemoval, reconcileIxChange, removeIxSegment } from "../../services/internet-exchange-execution.js"
|
||||
import { applyIxChange, currentIxChange, ixTarget, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxNodeInventory, reconcileIxChange, removeIxSegment } from "../../services/internet-exchange-execution.js"
|
||||
import { IxConflict, ixDeviceIds } from "../../services/internet-exchange-plan.js"
|
||||
import { assertIxRevision, isIxSegmentArchived, listIxSegments, readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import type { add } from "./actions.js"
|
||||
@@ -152,6 +152,23 @@ export function registerIxActions(register: typeof add) {
|
||||
return { segment: row, observations: await observeIxSegment(row) }
|
||||
},
|
||||
})
|
||||
const nodeInput = z.object({ serverId: z.number().int().positive().safe() }).strict()
|
||||
register("network.ix.inventory", "mm_ix_inventory_get", "Интерфейсы CHR и кандидат Router ID", "network", "mm:network:read", "read", "servers",
|
||||
nodeInput, {
|
||||
target: async input => ({ scope: "servers", serverIds: [nodeInput.parse(input).serverId] }),
|
||||
read: input => present(() => readIxNodeInventory(nodeInput.parse(input).serverId, undefined, true)),
|
||||
})
|
||||
const pathInput = nodeInput.extend({ id, interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) })
|
||||
register("network.ix.linux-path", "mm_ix_linux_path_get", "Маршруты Linux-клиента IX", "network", "mm:network:read", "read", "servers",
|
||||
pathInput, {
|
||||
target: async input => ({ scope: "servers", serverIds: [pathInput.parse(input).serverId] }),
|
||||
read: input => present(async () => {
|
||||
const args = pathInput.parse(input)
|
||||
const segment = await readIxSegment(args.id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return observeIxLinuxPath(segment, args.serverId, args.interfaceName)
|
||||
}),
|
||||
})
|
||||
register(ixOperation, "mm_ix_change_plan", "План изменения сегмента IX", "network", "mm:network:write", "write", "servers", changeArgs, {
|
||||
target: async input => ({ scope: "servers", serverIds: await ixTarget(changeArgs.parse(input).change) }),
|
||||
prepare: (input, context) => present(() => prepare(changeArgs.parse(input).change, context)),
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { fingerprint, accessGeneration, McpError } from "./security.js"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
|
||||
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, mcpWireguardExportRequestSchema, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
|
||||
import type { add } from "./actions.js"
|
||||
|
||||
export function registerWireguardExportActions(register: typeof add) {
|
||||
@@ -16,10 +15,10 @@ export function registerWireguardExportActions(register: typeof add) {
|
||||
return receipt?.humanDownloadOnly===true && receipt.wireguardContentReturned===false && !!receipt.artifactId && await verifyWireguardExportArtifact(receipt.artifactId,authority(input),String(input.expectedProof))
|
||||
},
|
||||
})
|
||||
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт для скачивания владельцем после человеческого подтверждения","network","mm:network:write","write","servers",wireguardExportRequestSchema,{
|
||||
target:input=>({scope:"servers",serverIds:[wireguardExportRequestSchema.parse(input).serverId]}),
|
||||
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт или готовый .conf для Linux-клиента IX","network","mm:network:write","write","servers",mcpWireguardExportRequestSchema,{
|
||||
target:input=>({scope:"servers",serverIds:[mcpWireguardExportRequestSchema.parse(input).serverId]}),
|
||||
prepare:async(input,context)=>{
|
||||
const request=wireguardExportRequestSchema.parse(input)
|
||||
const request=mcpWireguardExportRequestSchema.parse(input)
|
||||
const authorize=async()=>{
|
||||
if(context.signal?.aborted)throw new McpError("READ_CANCELLED","Экспорт WireGuard отменён",409)
|
||||
const fresh=await effectiveMcpConnection(context.principal)
|
||||
@@ -33,7 +32,10 @@ export function registerWireguardExportActions(register: typeof add) {
|
||||
await authorize()
|
||||
return {target:{scope:"servers",serverIds:[request.serverId]},objects:[{kind:"server",id:String(request.serverId),serverId:request.serverId},{kind:"wireguard-export",id:request.interfaceName,serverId:request.serverId},...protections.map(row=>row.object_ref)],snapshots:[],before:{proof:source.proof},requiresHuman:true,mutationCost:1,
|
||||
steps:[{kind:"service",service:"network.wireguard.export",input:{authority:access,expectedProof:source.proof,beforeFingerprint:fingerprint({proof:source.proof})}}],
|
||||
warnings:[request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
|
||||
warnings: request.ixSegmentId ? [
|
||||
"Готовый конфиг IX содержит приватный ключ Linux-клиента. Скачивание доступно вошедшему владельцу на 15 минут.",
|
||||
"MCP возвращает только квитанцию и ссылку. Изменение применённой ревизии, прав или защит блокирует выдачу.",
|
||||
] : [request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import type { PoolClient } from "pg"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission, type AuthUser } from "../../lib/permissions.js"
|
||||
import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
||||
import { readIxLinuxClient } from "../../services/internet-exchange-execution.js"
|
||||
import { IxConflict } from "../../services/internet-exchange-plan.js"
|
||||
import { readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
||||
import { assertLogArtifactBudget } from "./log-artifacts.js"
|
||||
import { assertPortalClaimsCurrent } from "./portal-revocation.js"
|
||||
@@ -13,7 +16,11 @@ import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError,
|
||||
const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576
|
||||
const digest = z.string().regex(/^[a-f0-9]{64}$/)
|
||||
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict()
|
||||
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: wireguardExportRequestSchema }).strict()
|
||||
export const mcpWireguardExportRequestSchema = wireguardExportRequestSchema.extend({
|
||||
ixSegmentId: z.string().uuid().optional().describe("Для готового конфига Linux из IX укажите ID сегмента и формат peer-conf"),
|
||||
}).refine(request => !request.ixSegmentId || request.format === "peer-conf" && !request.peerId && !request.includePrivateKey,
|
||||
"Для клиента IX укажите peer-conf и имя интерфейса клиента. Его управляемый ключ будет включён в файл.")
|
||||
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: mcpWireguardExportRequestSchema }).strict()
|
||||
export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema>
|
||||
const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest,
|
||||
bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict()
|
||||
@@ -41,10 +48,25 @@ async function protectionProof(authority: WireguardExportAuthority, client: Pick
|
||||
export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) {
|
||||
await authorize(); await assertWireguardExportAccess(authority)
|
||||
const protections=await protectionProof(authority)
|
||||
const source=await readWireguardExport(authority.request, { signal, authorize: async()=>{
|
||||
const check = async () => {
|
||||
signal?.throwIfAborted()
|
||||
await authorize(); await assertWireguardExportAccess(authority)
|
||||
if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT")
|
||||
} })
|
||||
}
|
||||
const { ixSegmentId, ...request } = authority.request
|
||||
if (ixSegmentId) {
|
||||
await check()
|
||||
const segment = await readIxSegment(ixSegmentId)
|
||||
if (!segment) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
const access = await readIxLinuxClient(segment, request.serverId, request.interfaceName, "wireguard").catch(error => {
|
||||
if (error instanceof IxConflict) throw new McpError(error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
|
||||
throw error
|
||||
})
|
||||
await check()
|
||||
const proof = await sign({ protections, ixSegmentId, request, access })
|
||||
return { filename: access.filename, content: Buffer.from(access.template), protectionProof: protections, proof }
|
||||
}
|
||||
const source=await readWireguardExport(request, { signal, authorize: check })
|
||||
return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { randomUUID } from "node:crypto"
|
||||
import type { FastifyPluginAsync } from "fastify"
|
||||
import { z } from "zod"
|
||||
import { ixChangeSchema, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
|
||||
import { fingerprint, McpError } from "../modules/mcp/security.js"
|
||||
import { audit } from "../modules/mcp/store.js"
|
||||
import { pool } from "../db/index.js"
|
||||
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
|
||||
import { withApplicationMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { withConfigurationActor } from "../services/config-mutation-policy.js"
|
||||
import { applyIxChange, listIxLinuxClients, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, removeIxSegment } from "../services/internet-exchange-execution.js"
|
||||
import { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } 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"
|
||||
|
||||
@@ -17,17 +19,19 @@ const paging = z.object({
|
||||
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}$/) })
|
||||
const clientKey = z.object({ serverId: z.number().int().positive().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) })
|
||||
const safeFields = (fields: Record<string, string>) => Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "secret" && key !== "private-key"))
|
||||
|
||||
async function prepareSavedRevision(id: string, revision: number) {
|
||||
async function prepareSavedRevision(id: string, revision: number, resume = false) {
|
||||
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 })
|
||||
return prepareIxChange({ id, revision, configuration: segment.configuration }, resume)
|
||||
}
|
||||
|
||||
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 })
|
||||
function reviewDigest(prepared: Awaited<ReturnType<typeof prepareSavedRevision>>, actorId: string, resume: boolean) {
|
||||
return fingerprint({ operation: "ix.web.apply", actorId, change: prepared.change, before: prepared.before, tasks: prepared.native.tasks, resume })
|
||||
}
|
||||
|
||||
function removalDigest(id: string, revision: number, actorId: string, nativeDigest: string) {
|
||||
@@ -40,7 +44,7 @@ function summarizeTasks(tasks: Awaited<ReturnType<typeof prepareIxChange>>["nati
|
||||
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))),
|
||||
fields: task.fields ? safeFields(task.fields) : Object.fromEntries(Object.entries(task.before ?? {}).filter(([key]) => ["name", "comment", "dst-address", "chain"].includes(key))),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -62,13 +66,19 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
return { items: await listIxSegments(input.limit, input.offset) }
|
||||
})
|
||||
app.get("/ix/nodes", async () => {
|
||||
const { pool } = await import("../db/index.js")
|
||||
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"),
|
||||
pool.query("SELECT id,name,site,country,enabled,type FROM servers ORDER BY name,id LIMIT 1000"),
|
||||
])
|
||||
return { items: nodes.rows, peers: peers.rows }
|
||||
})
|
||||
app.get("/ix/nodes/:serverId/inventory", async request => {
|
||||
const { serverId } = z.object({ serverId: z.coerce.number().int().positive().safe() }).parse(request.params)
|
||||
const { segmentId } = z.object({ segmentId: z.string().uuid().optional() }).strict().parse(request.query)
|
||||
const segment = segmentId ? await readIxSegment(segmentId) : null
|
||||
if (segmentId && !segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return readIxNodeInventory(serverId, segment ?? undefined, true)
|
||||
})
|
||||
app.get("/ix/topology", async () => {
|
||||
const segments = await listIxSegments(100, 0)
|
||||
const links = segments.filter(segment => segment.appliedRevision === segment.revision).flatMap(({ configuration }) =>
|
||||
@@ -93,43 +103,112 @@ const ixRoutes: FastifyPluginAsync = async app => {
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName) : listIxLinuxClients(segment)
|
||||
})
|
||||
app.post("/ix/segments/:id/linux", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const input = ixLinuxClientRequest.parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, input.revision)
|
||||
const base = input.transit ? { ...current, configuration: await configureIxTransit(current, {
|
||||
...input.transit, revision: input.revision, serverId: input.serverId,
|
||||
}) } : current
|
||||
const { configuration, interfaceName } = await configureIxLinuxClient(base, {
|
||||
...input, exit: input.transit?.name ?? input.exit,
|
||||
})
|
||||
const segment = await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false)
|
||||
return { segment, interfaceName }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.get("/ix/segments/:id/linux/path", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName } = clientKey.extend({ serverId: z.coerce.number().int().positive().safe() }).strict().parse(request.query)
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return observeIxLinuxPath(segment, serverId, interfaceName)
|
||||
})
|
||||
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName } = clientKey.parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + 60_000 }
|
||||
const token = await captureVerifiedRestRequest(request, scope)
|
||||
const { ownerId } = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
const access = await readIxLinuxClient(segment, serverId, interfaceName, true)
|
||||
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
|
||||
reply.header("Cache-Control", "no-store")
|
||||
return access
|
||||
})
|
||||
app.post("/ix/segments/:id/linux/revoke", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName, revision } = clientKey.extend(planRequest.shape).strict().parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, revision)
|
||||
const site = current.configuration.sites.find(item => item.serverId === serverId)
|
||||
if (!site?.interfaces.some(item => item.name === interfaceName && item.linux)) throw new IxConflict("Управляемый клиент не найден", 404)
|
||||
const configuration = { ...current.configuration, sites: current.configuration.sites.map(item => item !== site ? item : {
|
||||
...item, interfaces: item.interfaces.filter(binding => binding.name !== interfaceName),
|
||||
neighbors: item.neighbors.filter(neighbor => neighbor.binding !== interfaceName),
|
||||
}) }
|
||||
compileIxConfiguration(id, configuration)
|
||||
return { segment: await writeIxRevision(id, revision, configuration, request.authUser?.id ?? "system", false) }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/segments/:id/transit", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const input = ixTransitRequest.parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, input.revision)
|
||||
const configuration = await configureIxTransit(current, input)
|
||||
return { segment: await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false) }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/segments", async request => {
|
||||
const input = ixChangeSchema.parse(request.body)
|
||||
const id = input.id ?? randomUUID()
|
||||
compileIxConfiguration(id, input.configuration)
|
||||
return withApplicationMutationLock(async () => {
|
||||
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
|
||||
const segment = await writeIxRevision(id, input.revision, input.configuration, request.authUser?.id ?? "system", false)
|
||||
const current = input.id ? await readIxSegment(id) : null
|
||||
assertIxRevision(current, input.revision)
|
||||
const configuration = await assignIxRouterIds(id, input.configuration, current)
|
||||
compileIxConfiguration(id, configuration)
|
||||
const segment = await writeIxRevision(id, input.revision, configuration, request.authUser?.id ?? "system", false)
|
||||
return { segment }
|
||||
})
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/preview", async request => {
|
||||
const input = ixChangeSchema.parse(request.body)
|
||||
const id = input.id ?? randomUUID()
|
||||
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
|
||||
return { id, objects: compileIxConfiguration(id, input.configuration) }
|
||||
return { id, objects: compileIxConfiguration(id, input.configuration).map(object => ({ ...object, fields: safeFields(object.fields) })) }
|
||||
})
|
||||
|
||||
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)
|
||||
const { revision, resume = false } = planRequest.extend({ resume: z.boolean().optional() }).parse(request.body)
|
||||
const prepared = await prepareSavedRevision(id, revision, resume)
|
||||
return {
|
||||
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator"),
|
||||
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator", resume), ...(resume && { resume }),
|
||||
changes: summarizeTasks(prepared.native.tasks),
|
||||
}
|
||||
})
|
||||
|
||||
app.post("/ix/segments/:id/apply", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { revision, digest } = applyRequest.parse(request.body)
|
||||
const { revision, digest, resume = false } = applyRequest.extend({ resume: z.boolean().optional() }).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() }))
|
||||
const prepared = await prepareSavedRevision(id, revision, resume)
|
||||
if (digest !== reviewDigest(prepared, ownerId, resume)) throw new IxConflict("План IX устарел. Постройте новый предпросмотр")
|
||||
const result = await withConfigurationActor(ownerId, () => applyIxChange(id, prepared.change, prepared.before, ownerId,
|
||||
async () => { await inspect() }, { resume }))
|
||||
return { segment: await readIxSegment(result.segmentId), result }
|
||||
})
|
||||
|
||||
|
||||
@@ -106,7 +106,11 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
app.get("/traffic/servers/:id/live", async (req, reply) => {
|
||||
const p = req.params as { id?: string | number }
|
||||
const q = req.query as { iface?: string }
|
||||
const q = req.query as { iface?: string; once?: string }
|
||||
if (q.once === "1" && (typeof q.iface !== "string" || !q.iface.trim() ||
|
||||
q.iface.length > 128 || q.iface === "__all__" || /[,\x00-\x1f\x7f]/.test(q.iface))) {
|
||||
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
|
||||
}
|
||||
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
|
||||
signal?.throwIfAborted()
|
||||
const row = await getEnabledServerById(id)
|
||||
@@ -117,11 +121,30 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" })
|
||||
|
||||
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, async () => {
|
||||
const current = await readServer(server.id, signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
const abort = new AbortController()
|
||||
const onClose = () => abort.abort()
|
||||
registerDatabaseStreamAbort(req, onClose)
|
||||
if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" })
|
||||
if (reply.raw.destroyed) return
|
||||
if (q.once === "1") {
|
||||
reply.raw.once("close", onClose)
|
||||
try {
|
||||
const sample = await readSample(abort.signal)
|
||||
return reply.header("Cache-Control", "no-store").send(sample)
|
||||
} catch {
|
||||
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
|
||||
return
|
||||
} finally {
|
||||
reply.raw.off("close", onClose)
|
||||
}
|
||||
}
|
||||
reply.raw.on("close", onClose)
|
||||
|
||||
reply.hijack()
|
||||
@@ -144,17 +167,10 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
reply.raw.writeHead(200, sseHeaders)
|
||||
reply.raw.write(":\n\n")
|
||||
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
|
||||
try {
|
||||
while (!abort.signal.aborted) {
|
||||
try {
|
||||
const sample = await readTrafficLiveSample(client, onlyInterface, cache, abort.signal, async () => {
|
||||
const current = await readServer(server.id, abort.signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Live-поток остановлен")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
const sample = await readSample(abort.signal)
|
||||
if (abort.signal.aborted) break
|
||||
writeSse(reply.raw, "sample", sample)
|
||||
} catch (error) {
|
||||
|
||||
@@ -16,7 +16,7 @@ export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, bi
|
||||
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
|
||||
}
|
||||
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[]) {
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>") {
|
||||
const config = binding.provisionWireguard
|
||||
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
|
||||
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
|
||||
@@ -28,8 +28,12 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
|
||||
return [
|
||||
"[Interface]",
|
||||
"Address = " + address(config.peerAddress),
|
||||
"PrivateKey = <локальный_приватный_ключ>",
|
||||
"Table = off",
|
||||
"PrivateKey = " + privateKey,
|
||||
binding.linux ? "Table = auto" : "Table = off",
|
||||
...(binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
|
||||
"PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
|
||||
"PreDown = ip -" + family + " rule del pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
|
||||
] : []),
|
||||
"",
|
||||
"[Peer]",
|
||||
"PublicKey = " + hubPublicKey,
|
||||
@@ -40,7 +44,7 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }) {
|
||||
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string) {
|
||||
const hub = binding.localEndpoint
|
||||
const client = binding.endpoint
|
||||
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
|
||||
@@ -48,6 +52,12 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
}
|
||||
const id = ixLinuxInterfaceName("ixg", serverId, binding)
|
||||
const hostMask = bgp && isIP(bgp.address) === 6 ? "/128" : "/32"
|
||||
const tunnel = binding.provisionGre
|
||||
const family = tunnel ? isIP(tunnel.peerAddress) : 4
|
||||
const protocol = "ip -" + family
|
||||
const local = tunnel?.localAddress.split("/")[0]
|
||||
const table = 30000 + parseInt(id.slice(-4), 16)
|
||||
const management = 10000 + parseInt(id.slice(-3), 16)
|
||||
return {
|
||||
filename: id + ".conf",
|
||||
template: [
|
||||
@@ -82,7 +92,7 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
" ike-" + id + " {",
|
||||
" id-1 = " + client,
|
||||
" id-2 = " + hub,
|
||||
' secret = "<PSK этого клиента>"',
|
||||
' secret = "' + (credential ?? "<PSK этого клиента>") + '"',
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
@@ -92,8 +102,22 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
|
||||
"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 внутри туннеля.",
|
||||
tunnel ? "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id :
|
||||
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
|
||||
"ip link set " + id + " up",
|
||||
...(tunnel ? [
|
||||
protocol + " route replace " + local + (family === 4 ? "/32" : "/128") + " dev " + id + " src " + tunnel.peerAddress,
|
||||
...(binding.linux?.destinations ?? []).map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress),
|
||||
...(binding.linux?.exit ? [
|
||||
protocol + " route replace default dev " + id + " src " + tunnel.peerAddress + " table " + table,
|
||||
...(family === 4 ? [
|
||||
"ip -4 rule add pref " + management + " to " + hub + "/32 lookup main",
|
||||
"ip -4 rule add pref " + management + " from " + client + "/32 lookup main",
|
||||
] : []),
|
||||
protocol + " rule add pref " + (management + 1) + " lookup " + table,
|
||||
"# Удаление политик: " + protocol + " rule del pref " + (management + 1) + " lookup " + table,
|
||||
] : []),
|
||||
] : []),
|
||||
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
|
||||
].join("\n"),
|
||||
}
|
||||
|
||||
@@ -31,6 +31,26 @@ test("managed changes update one exact ID and never adopt unknown objects after
|
||||
assert.deepEqual(task.fields, { gateway: "192.0.2.2@" + name })
|
||||
assert.throws(() => planIxNative(id, [next], [], state), /незавершённой операции/)
|
||||
assert.throws(() => planIxNative(id, [next], [route], device({ "/ip/route": [{ ".id": "*B", ...next.fields }] })), /изменён вне операции/)
|
||||
const resumed = planIxNative(id, [next, vrf], [route], device({
|
||||
"/ip/route": [{ ".id": "*B", ...next.fields }],
|
||||
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
|
||||
}), true)
|
||||
assert.deepEqual(resumed.map(task => task.path), ["/ip/vrf"])
|
||||
})
|
||||
|
||||
test("revocation disables the owned client tunnel before withdrawing rules and deleting its native object", () => {
|
||||
const tunnel = { serverId: 17, path: "/interface/gre", fields: {
|
||||
name: "il-client", comment: name + ":gre-il-client", disabled: "false",
|
||||
} }
|
||||
const changes = planIxNative(id, [], [tunnel, route], device({
|
||||
[tunnel.path]: [{ ".id": "*A", ...tunnel.fields }],
|
||||
[route.path]: [{ ".id": "*B", ...route.fields }],
|
||||
}))
|
||||
assert.deepEqual(changes.map(task => [task.rosId, task.fields, task.before?.disabled]), [
|
||||
["*A", { disabled: "true" }, "false"],
|
||||
["*B", undefined, undefined],
|
||||
["*A", undefined, "true"],
|
||||
])
|
||||
})
|
||||
|
||||
test("a foreign route in the IX table and implicit native field removal are refused", () => {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { createPrivateKey, createPublicKey, randomUUID } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
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 { ixChangeSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxLinuxClientRequest, type IxLinuxPath, type IxNodeInventory, type IxRouterObject, type IxSegment, type IxSite, type IxSiteObservation, type IxTransitRequest } from "@mmapp/contracts/internet-exchange"
|
||||
import { constantEqual, fingerprint, privateFingerprinter, privateFingerprinterExisting } from "../modules/mcp/security.js"
|
||||
import { pool } from "../db/index.js"
|
||||
import { audit } from "../modules/mcp/store.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, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
|
||||
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxSites, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
|
||||
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
|
||||
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { ixGreClientTemplate, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
|
||||
|
||||
@@ -25,24 +27,46 @@ interface IxNativeChange {
|
||||
tasks: Task[]
|
||||
}
|
||||
|
||||
function wireguardKeys(seed: string) {
|
||||
const scalar = Buffer.from(seed, "hex")
|
||||
scalar[0] &= 248
|
||||
scalar[31] = (scalar[31] & 127) | 64
|
||||
const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar])
|
||||
const key = createPrivateKey({ key: der, format: "der", type: "pkcs8" })
|
||||
return {
|
||||
privateKey: scalar.toString("base64"),
|
||||
publicKey: createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64"),
|
||||
}
|
||||
}
|
||||
|
||||
async function ixLinuxWireguardKeys(segmentId: string, serverId: number, name: string, credentialId: string, create = false) {
|
||||
const derive = await (create ? privateFingerprinter : privateFingerprinterExisting)("ix-linux-wireguard-credential-v1")
|
||||
return wireguardKeys(derive([segmentId, serverId, name, credentialId].join(":")))
|
||||
}
|
||||
|
||||
const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks })
|
||||
|
||||
const routerId = /^\*[a-z\d]+$/i
|
||||
const marker = (path: string, comment: string) => path + "\0" + comment
|
||||
const objectMarker = (object: IxRouterObject) => marker(object.path, object.fields.comment)
|
||||
const objectMarker = (object: IxRouterObject) => marker(object.path, object.fields.comment ?? object.fields.name)
|
||||
const deviceMarker = (object: IxRouterObject) => object.serverId + "\0" + objectMarker(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 filterPath = (path: string) => /^\/(ip|ipv6)\/firewall\/(filter|nat|raw|mangle)$/.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 (["blackhole", "fib"].includes(field) && value === "") return "yes"
|
||||
if (["disabled", "advertise", "blackhole", "multihop", "fib", "passive", "tunnel", "allow-fast-path", "passthrough"].includes(field)) {
|
||||
return value === undefined ? null : isTrue(value) ? "yes" : "no"
|
||||
}
|
||||
if (field === "rule") return value?.trim()
|
||||
if (field === "gateway") return value?.replace(/@main$/, "")
|
||||
if (field === "interfaces") return value?.split(",").sort().join(",")
|
||||
if (value && ["src-address", "dst-address", "remote.address"].includes(field)) {
|
||||
if (field === "allowed-address") return value?.split(",").sort().join(",")
|
||||
if (field === "persistent-keepalive" && /^\d+(s)?$/.test(value ?? "")) return Number(value?.replace(/s$/, ""))
|
||||
if (value && ["address", "src-address", "dst-address", "remote.address"].includes(field)) {
|
||||
const slash = value.lastIndexOf("/")
|
||||
const address = value.slice(0, slash)
|
||||
if ((value.endsWith("/32") && isIP(address) === 4) || (value.endsWith("/128") && isIP(address) === 6)) return address
|
||||
@@ -56,7 +80,7 @@ function matches(row: NativeRow, fields: Record<string, string>) {
|
||||
|
||||
function rowsFor(device: NativeDevice, path: string) { return device.rows[path] ?? [] }
|
||||
function managedRow(device: NativeDevice, object: IxRouterObject) {
|
||||
const matches = rowsFor(device, object.path).filter(row => row.comment === object.fields.comment)
|
||||
const matches = rowsFor(device, object.path).filter(row => object.fields.comment ? row.comment === object.fields.comment : row.name === object.fields.name)
|
||||
if (matches.length > 1) throw new IxConflict("Дублируется идентификатор объекта IX на RouterOS")
|
||||
return matches[0]
|
||||
}
|
||||
@@ -66,7 +90,7 @@ function verifyNativeId(row: NativeRow) {
|
||||
return row[".id"]
|
||||
}
|
||||
|
||||
export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[]): Task[] {
|
||||
export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[], resume = false): 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 =>
|
||||
@@ -74,17 +98,24 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
|
||||
// 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 previousByKey = new Map(previous.map(object => [deviceMarker(object), object]))
|
||||
const result: Task[] = []
|
||||
const shutdown: Task[] = []
|
||||
const interfaceCleanup: Task[] = []
|
||||
// Never remove user objects by name or rebuild a whole RouterOS resource table.
|
||||
for (const object of [...previous].reverse()) {
|
||||
if (desiredKeys.has(deviceMarker(object))) continue
|
||||
const device = devices.find(entry => entry.serverId === object.serverId)!
|
||||
const row = managedRow(device, object)
|
||||
if (!row || !matches(row, object.fields)) throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
|
||||
const steps = object.path === "/interface/wireguard" ? interfaceCleanup : result
|
||||
steps.push({ serverId: object.serverId, path: object.path, rosId: verifyNativeId(row), before: row })
|
||||
if (!row && resume) continue
|
||||
const tunnel = ["/interface/wireguard", "/interface/gre"].includes(object.path)
|
||||
const managedTunnel = tunnel && [":wg-il-", ":gre-il-", ":transit-it-"].some(sign => object.fields.comment?.includes(sign))
|
||||
const alreadyStopped = managedTunnel && resume && row && matches(row, { ...object.fields, disabled: "true" })
|
||||
if (!row || !alreadyStopped && !matches(row, object.fields)) throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
|
||||
const task = { serverId: object.serverId, path: object.path, rosId: verifyNativeId(row), before: row }
|
||||
if (managedTunnel && !isTrue(row.disabled)) shutdown.push({ ...task, fields: { disabled: "true" } })
|
||||
const steps = tunnel ? interfaceCleanup : result
|
||||
steps.push(managedTunnel ? { ...task, before: { ...row, disabled: "true" } } : task)
|
||||
}
|
||||
for (const object of desired) {
|
||||
const device = devices.find(entry => entry.serverId === object.serverId)!
|
||||
@@ -93,9 +124,13 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
|
||||
rowsFor(device, path).some(entry => entry !== row && entry["routing-table"] === "main" && entry["dst-address"] === object.fields["dst-address"])) {
|
||||
throw new IxConflict("Служебный next hop BGP уже занят в таблице main")
|
||||
}
|
||||
if (row && !previousKeys.has(deviceMarker(object))) throw new IxConflict("Найден объект незавершённой операции IX. Сначала выполните сверку")
|
||||
if (resume && row && !isTrue(row.invalid) && matches(row, object.fields)) { verifyNativeId(row); continue }
|
||||
if (row && !previousByKey.has(deviceMarker(object))) {
|
||||
throw new IxConflict(object.fields.comment ? "Найден объект незавершённой операции IX. Сначала выполните сверку" :
|
||||
"Имя объекта IX уже занято. Сначала выполните сверку")
|
||||
}
|
||||
if (row) {
|
||||
const before = previous.find(entry => deviceMarker(entry) === deviceMarker(object))!
|
||||
const before = previousByKey.get(deviceMarker(object))!
|
||||
if (!matches(row, before.fields)) throw new IxConflict("Объект IX изменён вне операции")
|
||||
if (Object.keys(before.fields).some(field => !(field in object.fields))) {
|
||||
throw new IxConflict("Поле RouterOS нельзя неявно сбросить. Замените объект с новым идентификатором")
|
||||
@@ -104,7 +139,7 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
|
||||
if (Object.keys(fields).length) result.push({ serverId: object.serverId, path, rosId: verifyNativeId(row), fields, before: row })
|
||||
continue
|
||||
}
|
||||
if (previousKeys.has(deviceMarker(object))) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
|
||||
if (previousByKey.has(deviceMarker(object))) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
|
||||
const foreign = rowsFor(device, path).some(entry => !entry.comment?.startsWith(namespace + ":") &&
|
||||
(object.fields.name && entry.name === object.fields.name || object.fields.chain && entry.chain === object.fields.chain && path === "/routing/filter/rule" ||
|
||||
object.fields["routing-table"] && entry["routing-table"] === namespace && !isTrue(entry.dynamic)))
|
||||
@@ -115,7 +150,7 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
|
||||
if (placeBefore && !routerId.test(placeBefore)) throw new IxConflict("Не подтверждена позиция правила фильтра")
|
||||
result.push({ serverId: object.serverId, path, fields: object.fields, placeBefore })
|
||||
}
|
||||
return result.concat(interfaceCleanup)
|
||||
return shutdown.concat(result, interfaceCleanup)
|
||||
}
|
||||
|
||||
function verifyEgressMembers(device: NativeDevice, id: string, objects: IxRouterObject[]) {
|
||||
@@ -140,12 +175,237 @@ async function readRows(client: IpCore, path: string, props: readonly string[])
|
||||
}))) as NativeRow[]
|
||||
}
|
||||
|
||||
async function requiredIxNode(serverId: number, allowExitNode = false) {
|
||||
const server = await getServerRowById(serverId)
|
||||
if (!server?.enabled || (server.type !== "ix-node" && !(allowExitNode && server.type === "exit-node"))) {
|
||||
throw new IxConflict("Узел IX или ExitNode не найден либо отключён", 404)
|
||||
}
|
||||
return MikrotikClient.fromServer(server)
|
||||
}
|
||||
|
||||
async function observedIxRouterIds(client: IpCore, segmentId?: string) {
|
||||
const [bgp, ospf, named, sessions] = await Promise.all([
|
||||
readRows(client, "/routing/bgp/instance", ["name", "router-id"]),
|
||||
readRows(client, "/routing/ospf/instance", ["router-id"]),
|
||||
readRows(client, "/routing/id", ["name", "id", "dynamic-id"]),
|
||||
readRows(client, "/routing/bgp/session", ["remote.id"]),
|
||||
])
|
||||
const others = bgp.filter(row => !segmentId || row.name !== ixNamespace(segmentId))
|
||||
const selected = [...others, ...ospf].map(row => row["router-id"])
|
||||
return new Set([...selected, ...named.flatMap(row => [row.id, row["dynamic-id"]]),
|
||||
...sessions.map(row => row["remote.id"])].filter(value => isIP(value ?? "") === 4 && value !== "0.0.0.0"))
|
||||
}
|
||||
|
||||
export async function readIxNodeInventory(serverId: number, segment?: IxSegment, allowExitNode = false): Promise<IxNodeInventory> {
|
||||
const client = await requiredIxNode(serverId, allowExitNode)
|
||||
const [interfaces, bridgePorts, vrfs, routes, ipv6Routes, addresses, ipv6Addresses, wireguard, observed, reserved] = await Promise.all([
|
||||
readRows(client, "/interface", ["name", "type", "running", "disabled", "comment"]),
|
||||
readRows(client, "/interface/bridge/port", ["interface", "bridge"]),
|
||||
readRows(client, "/ip/vrf", ["name", "interfaces"]),
|
||||
readRows(client, "/ip/route", ["routing-table", "dst-address", "gateway", "immediate-gw", "active"]),
|
||||
readRows(client, "/ipv6/route", ["routing-table", "dst-address", "gateway", "immediate-gw", "active"]),
|
||||
readRows(client, "/ip/address", ["interface", "address"]),
|
||||
readRows(client, "/ipv6/address", ["interface", "address"]),
|
||||
readRows(client, "/interface/wireguard", ["listen-port"]),
|
||||
observedIxRouterIds(client, segment?.id).catch(() => null),
|
||||
ixReservedRouterIds(segment?.id),
|
||||
])
|
||||
const namespace = segment ? ixNamespace(segment.id) : null
|
||||
const owned = segment?.configuration.sites.find(site => site.serverId === serverId)
|
||||
const allAddresses = addresses.concat(ipv6Addresses)
|
||||
return {
|
||||
observedAt: new Date().toISOString(),
|
||||
routerId: owned?.routerId ?? (observed ? nextIxRouterId(new Set([...observed, ...reserved,
|
||||
...allAddresses.map(row => row.address?.split("/")[0]), ...(segment?.configuration.sites.map(site => site.routerId) ?? [])])) : null),
|
||||
wireguardPorts: wireguard.map(row => Number(row["listen-port"])).filter(port => Number.isInteger(port) && port > 0),
|
||||
defaultRoutes: ([4, 6] as const).flatMap(family => (family === 4 ? routes : ipv6Routes).flatMap(row => {
|
||||
if (row["routing-table"] !== "main" || row["dst-address"] !== (family === 4 ? "0.0.0.0/0" : "::/0") || !isTrue(row.active)) return []
|
||||
const [gateway, iface] = (row["immediate-gw"] ?? row.gateway ?? "").split("%")
|
||||
const name = iface?.split("@")[0]
|
||||
return name && isIP(gateway) === family && interfaces.some(item => item.name === name && !isTrue(item.disabled))
|
||||
? [{ family, gateway, interface: name }] : []
|
||||
})),
|
||||
interfaces: interfaces.filter(row => row.name).map(row => {
|
||||
const foreign = vrfs.find(vrf => vrf.name !== "main" && vrf.name !== namespace && vrf.interfaces?.split(",").includes(row.name))
|
||||
const bridge = bridgePorts.find(port => port.interface === row.name)
|
||||
const main = routes.concat(ipv6Routes).some(route => route["routing-table"] === "main" &&
|
||||
(route.gateway === row.name || [route.gateway, route["immediate-gw"]].some(value => value?.split("%")[1]?.split("@")[0] === row.name)))
|
||||
return {
|
||||
name: row.name, type: row.type ?? "", running: isTrue(row.running), disabled: isTrue(row.disabled),
|
||||
addresses: allAddresses.filter(address => address.interface === row.name && address.address).map(address => address.address),
|
||||
restriction: row.name === namespace || row.name === (segment && ixDiscardInterface(segment.id)) ? "Служебный интерфейс IX" :
|
||||
foreign ? "Интерфейс используется в VRF " + foreign.name : bridge ? "Порт моста " + bridge.bridge :
|
||||
main ? "Интерфейс используется в таблице main" : null,
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export async function assignIxRouterIds(id: string, configuration: IxConfiguration, existing: IxSegment | null) {
|
||||
const used = await ixReservedRouterIds(id)
|
||||
const sites = await Promise.all(configuration.sites.map(async site => {
|
||||
if (!site.autoRouterId || existing?.configuration.sites.some(old => old.serverId === site.serverId && old.routerId === site.routerId)) {
|
||||
return { site }
|
||||
}
|
||||
const routerIds = await observedIxRouterIds(await requiredIxNode(site.serverId), id).catch(() => new Set<string>())
|
||||
return { site, routerIds }
|
||||
}))
|
||||
const candidates = new Set([...used, ...sites.flatMap(({ site, routerIds }) => routerIds ? [...routerIds] : [site.routerId])])
|
||||
return { ...configuration, sites: sites.map(({ site, routerIds }) => {
|
||||
if (!routerIds) return site
|
||||
const routerId = !candidates.has(site.routerId) && site.routerId !== "0.0.0.0" ? site.routerId : nextIxRouterId(candidates)
|
||||
candidates.add(routerId)
|
||||
return { ...site, routerId }
|
||||
}) }
|
||||
}
|
||||
|
||||
export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) {
|
||||
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
|
||||
if (!site) throw new IxConflict("Узел не входит в сегмент IX", 404)
|
||||
const previous = site.interfaces.find(binding => binding.name === input.interfaceName && binding.linux)
|
||||
if (input.interfaceName && !previous) throw new IxConflict("Управляемый клиент не найден", 404)
|
||||
if (previous && previous.kind !== input.kind) throw new IxConflict("Для смены протокола создайте новое подключение", 400)
|
||||
const [inventory, reserved] = await Promise.all([
|
||||
readIxNodeInventory(site.serverId, segment), ixReservedTunnelBindings(site.serverId),
|
||||
])
|
||||
const currentTunnel = previous?.provisionWireguard ?? previous?.provisionGre
|
||||
let localAddress = input.localAddress ?? currentTunnel?.localAddress
|
||||
let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress
|
||||
if (!localAddress && !peerAddress) {
|
||||
const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved
|
||||
.concat(segment.configuration.sites.flatMap(candidate => candidate.interfaces))
|
||||
.flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress,
|
||||
binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined)))
|
||||
for (let index = 0; index < 65536; index += 4) {
|
||||
const base = "10.254." + (index >> 8) + "."
|
||||
const next = base + ((index & 255) + 1) + "/30"
|
||||
if (used.some(network => inIxNetwork(network, next) || inIxNetwork(next, network))) continue
|
||||
localAddress = next
|
||||
peerAddress = base + ((index & 255) + 2)
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!localAddress || !peerAddress) throw new IxConflict("Укажите оба адреса туннеля или оставьте их для автоматического подбора", 400)
|
||||
const ports = new Set(inventory.wireguardPorts)
|
||||
for (const binding of [...reserved, ...site.interfaces]) {
|
||||
if (binding.provisionWireguard) ports.add(binding.provisionWireguard.listenPort)
|
||||
if (binding.provisionTransit) {
|
||||
ports.add(binding.provisionTransit.localPort)
|
||||
ports.add(binding.provisionTransit.remotePort)
|
||||
}
|
||||
}
|
||||
let listenPort = 51820
|
||||
while (ports.has(listenPort) && listenPort <= 65535) listenPort++
|
||||
const name = previous?.name ?? "il-" + randomUUID().replace(/-/g, "").slice(0, 12)
|
||||
const family = isIP(peerAddress)
|
||||
const localExit = "ix-wan" + family
|
||||
const groups = [...site.groups]
|
||||
if (input.exit === "local-wan" && !groups.some(group => group.id === localExit)) {
|
||||
const wan = inventory.defaultRoutes.find(route => route.family === family)
|
||||
if (!wan) throw new IxConflict("Не найден действующий WAN в таблице main для этого семейства")
|
||||
const occupied = new Set(groups.map(group => group.gateway))
|
||||
let gateway = family === 4 ? "198.19.255.254" : "fd00:198:18::ffff"
|
||||
for (let suffix = 1; occupied.has(gateway) && suffix < 255; suffix++) {
|
||||
gateway = family === 4 ? "198.19.254." + suffix : "fd00:198:18::" + suffix.toString(16)
|
||||
}
|
||||
groups.push({ id: localExit, gateway, onFailure: "block",
|
||||
primary: { interface: wan.interface, nextHop: wan.gateway, probe: wan.gateway, viaMain: true } })
|
||||
}
|
||||
const binding: IxSite["interfaces"][number] = {
|
||||
name, kind: input.kind, prefixes: input.prefixes,
|
||||
linux: { name: input.name, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
|
||||
exit: input.exit === "local-wan" ? localExit : input.exit },
|
||||
}
|
||||
if (input.kind === "wireguard") {
|
||||
const existing = previous?.provisionWireguard
|
||||
if (!existing && listenPort > 65535) throw new IxConflict("Нет свободного порта WireGuard", 400)
|
||||
let peerPublicKey = input.peerPublicKey ?? existing?.peerPublicKey
|
||||
let credentialId = peerPublicKey === existing?.peerPublicKey ? existing?.credentialId : undefined
|
||||
if (!peerPublicKey) {
|
||||
credentialId = randomUUID()
|
||||
peerPublicKey = (await ixLinuxWireguardKeys(segment.id, site.serverId, name, credentialId, true)).publicKey
|
||||
}
|
||||
binding.provisionWireguard = { peerPublicKey, credentialId, listenPort: existing?.listenPort ?? listenPort,
|
||||
localAddress, peerAddress, hubEndpoint: input.hubEndpoint }
|
||||
} else {
|
||||
if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400)
|
||||
binding.endpoint = input.peerEndpoint
|
||||
binding.localEndpoint = input.hubEndpoint
|
||||
binding.provisionGre = { localAddress, peerAddress,
|
||||
credentialId: !input.rotate && previous?.provisionGre?.credentialId || randomUUID() }
|
||||
}
|
||||
const interfaces = previous ? site.interfaces.map(candidate => candidate === previous ? binding : candidate) : [...site.interfaces, binding]
|
||||
const configuration = { ...segment.configuration, sites: segment.configuration.sites.map(candidate => candidate === site
|
||||
? { ...site, interfaces, groups } : candidate) }
|
||||
compileIxConfiguration(segment.id, configuration)
|
||||
return { configuration, interfaceName: name }
|
||||
}
|
||||
|
||||
export async function configureIxTransit(segment: IxSegment, input: IxTransitRequest) {
|
||||
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
|
||||
if (!site || input.targetServerId === input.serverId) throw new IxConflict("Выберите другую площадку IX или ExitNode", 400)
|
||||
if (site.groups.some(group => group.id === input.name)) throw new IxConflict("Имя группы шлюзов уже занято")
|
||||
const [origin, remote, a, b] = await Promise.all([
|
||||
readIxNodeInventory(site.serverId, segment), readIxNodeInventory(input.targetServerId, segment, true),
|
||||
ixReservedTunnelBindings(site.serverId), ixReservedTunnelBindings(input.targetServerId),
|
||||
])
|
||||
const wan = remote.defaultRoutes.find(route => route.family === input.family)
|
||||
if (!wan) throw new IxConflict("У выбранного узла нет активного IPv" + input.family + " WAN")
|
||||
const localIps = origin.interfaces.flatMap(item => item.addresses)
|
||||
const remoteIps = remote.interfaces.flatMap(item => item.addresses)
|
||||
if (!localIps.some(ip => ip.split("/")[0] === input.localEndpoint) || !remoteIps.some(ip => ip.split("/")[0] === input.remoteEndpoint)) {
|
||||
throw new IxConflict("Внешние IP транзита должны принадлежать выбранным маршрутизаторам", 400)
|
||||
}
|
||||
const occupied = a.concat(b).flatMap(binding =>
|
||||
[binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress, binding.provisionTransit?.localAddress, ...binding.prefixes]
|
||||
.filter(value => value !== undefined))
|
||||
const credentialId = randomUUID()
|
||||
const name = "it-" + credentialId.replace(/-/g, "").slice(0, 12)
|
||||
let third = parseInt(credentialId.slice(0, 2), 16)
|
||||
const addressBase = (value: number) => input.family === 4 ? "10.253." + value + "." : "fd00:253:" + value.toString(16) + "::"
|
||||
const mask = input.family === 4 ? "/30" : "/126"
|
||||
let base = addressBase(third)
|
||||
for (let tries = 0; occupied.concat(localIps, remoteIps).some(network =>
|
||||
inIxNetwork(network, base + "1" + mask) || inIxNetwork(base + "1" + mask, network)); tries++) {
|
||||
if (tries >= 255) throw new IxConflict("Пул адресов транзитных туннелей занят")
|
||||
third = (third + 1) % 256
|
||||
base = addressBase(third)
|
||||
}
|
||||
const freePort = (inventory: IxNodeInventory, start: number) => {
|
||||
const used = new Set(inventory.wireguardPorts)
|
||||
for (const binding of a.concat(b)) {
|
||||
if (binding.provisionWireguard) used.add(binding.provisionWireguard.listenPort)
|
||||
if (binding.provisionTransit) {
|
||||
used.add(binding.provisionTransit.localPort)
|
||||
used.add(binding.provisionTransit.remotePort)
|
||||
}
|
||||
}
|
||||
while (used.has(start) && start <= 65535) start++
|
||||
if (start > 65535) throw new IxConflict("Свободные порты WireGuard закончились")
|
||||
return start
|
||||
}
|
||||
const localPort = freePort(origin, 52000)
|
||||
const remotePort = freePort(remote, localPort + 1)
|
||||
const binding: IxSite["interfaces"][number] = { name, kind: "wireguard", prefixes: [], peerServerId: input.targetServerId,
|
||||
provisionTransit: { localEndpoint: input.localEndpoint, remoteEndpoint: input.remoteEndpoint, localAddress: base + "1" + mask,
|
||||
remoteAddress: base + "2", localPort, remotePort, credentialId,
|
||||
remoteWan: { interface: wan.interface, nextHop: wan.gateway, probe: wan.gateway, viaMain: true } } }
|
||||
const group: IxSite["groups"][number] = { id: input.name,
|
||||
gateway: input.family === 4 ? "198.19.253." + third : "fd00:198:18:253::" + (third + 1).toString(16), onFailure: "block",
|
||||
primary: { interface: binding.name, nextHop: base + "2", probe: input.probe ?? base + "2" } }
|
||||
const configuration = { ...segment.configuration, sites: segment.configuration.sites.map(candidate => candidate === site
|
||||
? { ...site, interfaces: [...site.interfaces, binding], groups: [...site.groups, group] } : candidate) }
|
||||
compileIxConfiguration(segment.id, configuration)
|
||||
return configuration
|
||||
}
|
||||
|
||||
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false): Promise<NativeDevice> {
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]],
|
||||
["/ip/vrf", columns], ["/ip/route", columns], ["/ipv6/route", columns]])
|
||||
if (removing) {
|
||||
if (removing || objects.some(object => object.fields.gateway?.endsWith("@main"))) {
|
||||
for (const path of ["/ip/address", "/ipv6/address"]) fieldsByPath.set(path, [...columns, "interface"])
|
||||
for (const path of ["/ip/address", "/ipv6/address"]) fieldsByPath.get(path)!.push("address")
|
||||
}
|
||||
for (const object of objects) {
|
||||
fieldsByPath.set(object.path, [...new Set([...(fieldsByPath.get(object.path) ?? columns),
|
||||
@@ -153,8 +413,8 @@ async function readDevice(server: ServerRow, objects: IxRouterObject[], removing
|
||||
}
|
||||
if (fieldsByPath.has("/interface/list")) fieldsByPath.get("/interface/list")!.push("include", "exclude")
|
||||
if (objects.some(object => object.fields["ipsec-policy"])) {
|
||||
fieldsByPath.set("/interface/gre", greColumns)
|
||||
fieldsByPath.set("/ip/ipsec/policy", ipsecPolicyColumns)
|
||||
fieldsByPath.set("/interface/gre", [...new Set([...greColumns, ...(fieldsByPath.get("/interface/gre") ?? [])])])
|
||||
fieldsByPath.set("/ip/ipsec/policy", [...new Set([...ipsecPolicyColumns, ...(fieldsByPath.get("/ip/ipsec/policy") ?? [])])])
|
||||
}
|
||||
const rows: Record<string, NativeRow[]> = {}
|
||||
for (const [path, keys] of fieldsByPath) rows[path] = await readRows(client, path, keys)
|
||||
@@ -188,7 +448,7 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
|
||||
}
|
||||
for (const binding of site.interfaces) {
|
||||
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
|
||||
if (!iface && binding.provisionWireguard) continue
|
||||
if (!iface && (binding.provisionWireguard || binding.provisionGre || binding.provisionTransit)) continue
|
||||
const expected = binding.kind === "wireguard" ? "wg" : binding.kind === "gre-ipsec" ? "gre-tunnel" : null
|
||||
if (!iface || (expected && iface.type !== expected && !(expected === "wg" && iface.type === "wireguard") &&
|
||||
!(expected === "gre-tunnel" && iface.type === "gre"))) {
|
||||
@@ -196,7 +456,10 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
|
||||
}
|
||||
// Moving an existing interface into a VRF affects the entire interface.
|
||||
// Explicit staging on the CHR separates IX handoff from existing services.
|
||||
if (iface.comment !== "IX:" + configuration.name && !(binding.provisionWireguard && iface.comment?.startsWith(ixNamespace(id) + ":wg-"))) {
|
||||
if (iface.comment !== "IX:" + configuration.name &&
|
||||
!(binding.provisionWireguard && iface.comment?.startsWith(ixNamespace(id) + ":wg-")) &&
|
||||
!(binding.provisionGre && iface.comment === ixNamespace(id) + ":gre-" + binding.name) &&
|
||||
!(binding.provisionTransit && iface.comment === ixNamespace(id) + ":transit-" + binding.name + "-source-wg")) {
|
||||
throw new IxConflict("Интерфейс " + binding.name + " не выделен для данного сегмента IX")
|
||||
}
|
||||
const foreignVrf = rowsFor(device, "/ip/vrf").find(row => row.name !== "main" && row.name !== ixNamespace(id) && row.interfaces?.split(",").includes(binding.name))
|
||||
@@ -211,24 +474,77 @@ function validateBindings(configuration: IxConfiguration, id: string, devices: N
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null): Promise<IxNativeChange> {
|
||||
const objects = configuration ? compileIxConfiguration(id, configuration) : []
|
||||
const previous = previousConfiguration ? compileIxConfiguration(id, previousConfiguration) : []
|
||||
function verifyIxMainGateways(device: NativeDevice, objects: IxRouterObject[]) {
|
||||
for (const object of objects) {
|
||||
const gateway = object.fields.gateway
|
||||
if (!gateway?.endsWith("@main")) continue
|
||||
const [nextHop, scoped] = gateway.split("%")
|
||||
const name = scoped?.split("@")[0]
|
||||
if (!name) continue
|
||||
const iface = rowsFor(device, "/interface").find(row => row.name === name)
|
||||
const addressPath = isIP(nextHop) === 6 ? "/ipv6/address" : "/ip/address"
|
||||
const inMain = !rowsFor(device, "/ip/vrf").some(row => row.name !== "main" && row.interfaces?.split(",").includes(name))
|
||||
const onLink = rowsFor(device, addressPath).some(row => row.interface === name && !isTrue(row.disabled) &&
|
||||
row.address?.includes("/") && inIxNetwork(row.address, nextHop))
|
||||
if (!iface || isTrue(iface.disabled) || !inMain || !onLink) {
|
||||
throw new IxConflict("WAN-шлюз " + nextHop + " недоступен напрямую через " + name + " в таблице main")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveIxCredentials(id: string, objects: IxRouterObject[], existing: boolean) {
|
||||
const key = existing ? privateFingerprinterExisting : privateFingerprinter
|
||||
const [psk, wg] = await Promise.all([
|
||||
objects.some(object => object.fields.secret?.startsWith("ix-credential:")) ? key("ix-gre-client-credential-v1") : null,
|
||||
objects.some(object => object.fields["private-key"]?.startsWith("ix-transit:")) ? key("ix-transit-wireguard-v1") : null,
|
||||
])
|
||||
if (!psk && !wg) return objects
|
||||
return objects.map(object => ({ ...object, fields: Object.fromEntries(Object.entries(object.fields).map(([name, value]) => {
|
||||
if (name === "secret" && psk && value.startsWith("ix-credential:")) return [name, psk(id + ":" + object.serverId + ":" + value)]
|
||||
if (wg && ["public-key", "private-key"].includes(name) && value.startsWith("ix-transit:")) {
|
||||
const [, variant, version, side] = value.split(":")
|
||||
const keys = wireguardKeys(wg([id, version, side].join(":")))
|
||||
return [name, variant === "private" ? keys.privateKey : keys.publicKey]
|
||||
}
|
||||
return [name, value]
|
||||
})) }))
|
||||
}
|
||||
|
||||
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null, resume = false): Promise<IxNativeChange> {
|
||||
for (const site of configuration?.sites ?? []) for (const binding of site.interfaces) {
|
||||
const wg = binding.provisionWireguard
|
||||
if (!wg?.credentialId) continue
|
||||
const keys = await ixLinuxWireguardKeys(id, site.serverId, binding.name, wg.credentialId)
|
||||
if (!binding.linux || !constantEqual(keys.publicKey, wg.peerPublicKey)) {
|
||||
throw new IxConflict("Ключ WireGuard не соответствует управляемому клиенту IX")
|
||||
}
|
||||
}
|
||||
const previous = previousConfiguration ? await resolveIxCredentials(id, compileIxConfiguration(id, previousConfiguration), true) : []
|
||||
const objects = configuration ? await resolveIxCredentials(id, compileIxConfiguration(id, configuration), false) : []
|
||||
const before: NativeDevice[] = []
|
||||
for (const serverId of [...new Set([...objects, ...previous].map(object => object.serverId))].sort((a, b) => a - b)) {
|
||||
const server = await getServerRowById(serverId)
|
||||
if (!server?.enabled || server.type !== "ix-node") throw new IxConflict("Площадка IX отключена или изменила тип")
|
||||
const isSite = [configuration, previousConfiguration].some(config => config?.sites.some(site => site.serverId === serverId))
|
||||
if (!server?.enabled || server.type !== "ix-node" && (isSite || server.type !== "exit-node")) {
|
||||
throw new IxConflict("Узел транзита отключён или изменил тип")
|
||||
}
|
||||
const site = configuration?.sites.find(candidate => candidate.serverId === serverId)
|
||||
if (site?.autoRouterId && (await observedIxRouterIds(MikrotikClient.fromServer(server), id)).has(site.routerId)) {
|
||||
throw new IxConflict("Router ID " + site.routerId + " уже используется на CHR")
|
||||
}
|
||||
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
|
||||
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
|
||||
}
|
||||
if (configuration) validateBindings(configuration, id, before)
|
||||
for (const device of before) verifyEgressMembers(device, id, previous)
|
||||
for (const device of before) verifyEgressMembers(device, id, resume ? previous.concat(objects) : previous)
|
||||
for (const old of previousConfiguration?.sites ?? []) {
|
||||
const next = configuration?.sites.find(site => site.serverId === old.serverId)
|
||||
const device = before.find(device => device.serverId === old.serverId)!
|
||||
if (!configuration) verifyRemovalScope(id, device, previous)
|
||||
for (const binding of old.interfaces.filter(binding => !next?.interfaces.some(candidate => candidate.name === binding.name))) {
|
||||
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
|
||||
if (!configuration && (!iface || binding.provisionWireguard || !rowsFor(device, "/ip/vrf").some(row => row.name === ixNamespace(id)))) continue
|
||||
if (binding.linux || binding.provisionTransit || !configuration &&
|
||||
(!iface || binding.provisionWireguard || !rowsFor(device, "/ip/vrf").some(row => row.name === ixNamespace(id)))) continue
|
||||
if (!isTrue(iface?.disabled)) {
|
||||
throw new IxConflict("Отключите интерфейс перед исключением из VRF IX: " + binding.name)
|
||||
}
|
||||
@@ -236,7 +552,19 @@ async function prepareNative(id: string, configuration: IxConfiguration | null,
|
||||
}
|
||||
const remaining = configuration ? previous : previous.filter(object =>
|
||||
managedRow(before.find(device => device.serverId === object.serverId)!, object))
|
||||
return { objects, before, tasks: planIxNative(id, objects, remaining, before) }
|
||||
return { objects, before, tasks: planIxNative(id, objects, remaining, before, resume) }
|
||||
}
|
||||
|
||||
async function assertIxResume(id: string, revision: number, native: IxNativeChange) {
|
||||
const { rows: [attempt] } = await pool.query<{ sources: unknown }>(`
|
||||
SELECT payload->'sources' AS sources FROM mcp_audit
|
||||
WHERE action='ix.web.apply_started' AND payload->>'segmentId'=$1 AND payload->>'revision'=$2
|
||||
ORDER BY id DESC LIMIT 1
|
||||
`, [id, String(revision)])
|
||||
const sources = native.before.map(device => [device.serverId, device.source])
|
||||
if (!attempt || fingerprint(attempt.sources) !== fingerprint(sources)) {
|
||||
throw new IxConflict("Нет подтверждённой попытки применения этой ревизии к этим устройствам")
|
||||
}
|
||||
}
|
||||
|
||||
function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) {
|
||||
@@ -272,7 +600,7 @@ export async function ixTarget(change: IxChange) {
|
||||
return [...new Set([...ixDeviceIds(change.configuration), ...(current ? ixDeviceIds(current.configuration) : []), ...(applied ? ixDeviceIds(applied) : [])])].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
export async function prepareIxChange(raw: unknown) {
|
||||
export async function prepareIxChange(raw: unknown, resume = false) {
|
||||
const change = ixChangeSchema.parse(raw)
|
||||
const id = change.id ?? randomUUID()
|
||||
const current = change.id ? await readIxSegment(id) : null
|
||||
@@ -280,7 +608,8 @@ export async function prepareIxChange(raw: unknown) {
|
||||
await assertIxName(id, change.configuration.name)
|
||||
await assertIxSites(change.configuration)
|
||||
const previous = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
|
||||
const native = await prepareNative(id, change.configuration, previous)
|
||||
const native = await prepareNative(id, change.configuration, previous, resume)
|
||||
if (resume) await assertIxResume(id, change.revision, native)
|
||||
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 }
|
||||
@@ -298,13 +627,13 @@ export async function reconcileIxChange(id: string, change: IxChange, expected:
|
||||
const current = await readIxSegment(id)
|
||||
if (current?.revision === expected.revision + 1 && current.appliedRevision === current.revision &&
|
||||
fingerprint(current.configuration) === fingerprint(change.configuration)) {
|
||||
const desired = compileIxConfiguration(id, change.configuration)
|
||||
const desired = await resolveIxCredentials(id, compileIxConfiguration(id, change.configuration), true)
|
||||
let matchesDesiredState = true
|
||||
for (const site of current.configuration.sites) {
|
||||
for (const serverId of [...new Set(desired.map(object => object.serverId))]) {
|
||||
await authorize()
|
||||
const server = await getServerRowById(site.serverId)
|
||||
const server = await getServerRowById(serverId)
|
||||
if (!server?.enabled) return { matchesDesiredState: false, matchesOriginalState: false }
|
||||
const objects = desired.filter(object => object.serverId === site.serverId)
|
||||
const objects = desired.filter(object => object.serverId === serverId)
|
||||
const observed = await readDevice(server, objects)
|
||||
try { verifyEgressMembers(observed, id, objects) }
|
||||
catch { return { matchesDesiredState: false, matchesOriginalState: false } }
|
||||
@@ -359,20 +688,75 @@ 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 }] : []
|
||||
const sites = await Promise.all(configuration.sites.map(async site => {
|
||||
const bindings = site.interfaces.filter(binding => ixLinuxBindingKind(binding) && !binding.peerServerId)
|
||||
const items: IxLinuxBinding[] = bindings.map(binding => ({
|
||||
serverId: site.serverId, interfaceName: binding.name, kind: ixLinuxBindingKind(binding)!,
|
||||
...(binding.provisionWireguard?.credentialId && { managedWireguard: true }),
|
||||
...(binding.linux && { name: binding.linux.name, enabled: binding.linux.enabled, policy: binding.linux }),
|
||||
}))
|
||||
if (!bindings.some(binding => binding.linux?.enabled)) return items
|
||||
const observedAt = new Date().toISOString()
|
||||
try {
|
||||
const client = await requiredIxNode(site.serverId)
|
||||
const [peers, ipsec] = await Promise.all([
|
||||
bindings.some(binding => binding.linux && binding.provisionWireguard) ? readRows(client, "/interface/wireguard/peers",
|
||||
["interface", "public-key", "last-handshake", "rx", "tx"]) : [],
|
||||
bindings.some(binding => binding.linux && binding.provisionGre) ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]) : [],
|
||||
])
|
||||
for (const [index, binding] of bindings.entries()) {
|
||||
if (!binding.linux?.enabled) continue
|
||||
const peer = peers.find(row => row.interface === binding.name && row["public-key"] === binding.provisionWireguard?.peerPublicKey)
|
||||
const handshake = peer?.["last-handshake"]?.trim()
|
||||
const age = handshake && /^\d+:\d{2}:\d{2}$/.test(handshake)
|
||||
? handshake.split(":").reduce((total, part) => total * 60 + Number(part), 0)
|
||||
: handshake && /^(?:(\d+)m)?(?:(\d+)s)?$/.exec(handshake)
|
||||
const fresh = typeof age === "number" ? age < 180 :
|
||||
Array.isArray(age) && Number(age[1] ?? 0) * 60 + Number(age[2] ?? 0) < 180
|
||||
const established = binding.provisionGre && ipsec.some(row => row.state === "established" &&
|
||||
(row["remote-address"] === binding.endpoint || row["remote-address"]?.startsWith(binding.endpoint + ":")))
|
||||
items[index].connection = { observedAt, state: fresh || established ? "connected" : "waiting", ...(peer && { rx: peer.rx, tx: peer.tx }) }
|
||||
}
|
||||
} catch {
|
||||
for (const item of items) if (item.enabled) item.connection = { observedAt, state: "unknown" }
|
||||
}
|
||||
return items
|
||||
}))
|
||||
return { revision, items }
|
||||
return { revision, items: sites.flat() }
|
||||
}
|
||||
|
||||
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string): Promise<IxLinuxAccess> {
|
||||
export async function observeIxLinuxPath(segment: IxSegment, serverId: number, name: string): Promise<IxLinuxPath> {
|
||||
if (!segment.appliedRevision) throw new IxConflict("Сначала примените конфигурацию площадки")
|
||||
const applied = await readIxRevision(segment.id, segment.appliedRevision)
|
||||
const binding = applied.sites.find(site => site.serverId === serverId)?.interfaces.find(item => item.name === name && item.linux)
|
||||
if (!binding?.linux) throw new IxConflict("Управляемый клиент не найден", 404)
|
||||
const client = await requiredIxNode(serverId)
|
||||
const namespace = ixNamespace(segment.id)
|
||||
const table = binding.linux.exit ? ixClientRoutingTable(namespace, name) : namespace
|
||||
const fields = ["dst-address", "routing-table", "gateway", "immediate-gw", "active", "blackhole"]
|
||||
const read = async (table: string) => {
|
||||
const result = await client.get<unknown>("/routing/route?" + new URLSearchParams({ ".proplist": fields.join(","), "routing-table": table }))
|
||||
if (!Array.isArray(result) || result.length > 10000) throw new IxConflict("Таблица маршрутов клиента недоступна")
|
||||
return result.filter(row => row && row["routing-table"] === table)
|
||||
}
|
||||
const [clientRoutes, segmentRoutes] = await Promise.all([read(table), table !== namespace ? read(namespace) : []])
|
||||
const routes = clientRoutes.concat(segmentRoutes).filter(row => typeof row["dst-address"] === "string" &&
|
||||
(row["routing-table"] === table && !!binding.linux?.exit || binding.linux?.destinations.some(prefix => inIxNetwork(prefix, row["dst-address"]))))
|
||||
return { table, observedAt: new Date().toISOString(), policy: binding.linux.exit ?? null, routes: routes.slice(0, 100).map(row => ({
|
||||
prefix: row["dst-address"], gateway: isTrue(row.blackhole) || row.blackhole === "" ? "blackhole" : row.gateway ?? "",
|
||||
immediateGateway: row["immediate-gw"] ?? null, active: isTrue(row.active),
|
||||
})) }
|
||||
}
|
||||
|
||||
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false): Promise<IxLinuxAccess> {
|
||||
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
|
||||
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
|
||||
const site = configuration.sites.find(site => site.serverId === serverId)
|
||||
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)
|
||||
if (binding.peerServerId || binding.linux?.enabled === false) throw new IxConflict("Клиентское подключение отключено или недоступно")
|
||||
if (includeCredential === "wireguard" && binding.kind !== "wireguard") throw new IxConflict("Для скачивания выберите клиента WireGuard", 404)
|
||||
const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed")
|
||||
const clientInfo = {
|
||||
revision: segment.appliedRevision,
|
||||
@@ -385,23 +769,47 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
|
||||
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 (includeCredential && !binding.provisionGre) throw new IxConflict("IX не выдавал этот IKEv2 PSK", 404)
|
||||
const credential = includeCredential && binding.provisionGre
|
||||
? (await privateFingerprinterExisting("ix-gre-client-credential-v1"))(segment.id + ":" + serverId + ":ix-credential:" + binding.provisionGre.credentialId)
|
||||
: undefined
|
||||
if (credential) {
|
||||
const identities = await readRows(client, "/ip/ipsec/identity", ["comment", "secret", "disabled"])
|
||||
const identity = identities.find(row => row.comment === ixNamespace(segment.id) + ":gre-identity-" + binding.name)
|
||||
if (!identity?.secret || isTrue(identity.disabled) || !constantEqual(identity.secret, credential)) {
|
||||
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
|
||||
}
|
||||
}
|
||||
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential) }
|
||||
}
|
||||
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
|
||||
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "comment", "disabled"])
|
||||
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
|
||||
const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-") && !isTrue(row.disabled))
|
||||
const peers = await readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "comment", "disabled"])
|
||||
if (!peers.some(row => row.interface === name && row["public-key"] === binding.provisionWireguard?.peerPublicKey &&
|
||||
row.comment?.startsWith(ixNamespace(segment.id) + ":wg-peer-") && !isTrue(row.disabled))) {
|
||||
throw new IxConflict("Пир WireGuard из применённой ревизии отсутствует или отключён")
|
||||
}
|
||||
const routes = configuration.sites.flatMap(entry => entry.interfaces
|
||||
const routes = binding.linux ? [...binding.linux.destinations,
|
||||
...(binding.linux.exit ? [isIP(binding.provisionWireguard!.peerAddress) === 4 ? "0.0.0.0/0" : "::/0"] : [])]
|
||||
: configuration.sites.flatMap(entry => entry.interfaces
|
||||
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
|
||||
let privateKey: string | undefined
|
||||
if (includeCredential) {
|
||||
const wg = binding.provisionWireguard
|
||||
if (!binding.linux || !wg?.credentialId) throw new IxConflict("Этот клиент использует собственный ключ WireGuard", 404)
|
||||
const keys = await ixLinuxWireguardKeys(segment.id, serverId, name, wg.credentialId)
|
||||
if (Number(iface?.["listen-port"]) !== wg.listenPort || !constantEqual(keys.publicKey, wg.peerPublicKey) ||
|
||||
(await readIxSegment(segment.id))?.appliedRevision !== segment.appliedRevision) {
|
||||
throw new IxConflict("Действующие параметры WireGuard не совпали с применённой ревизией. Выполните сверку")
|
||||
}
|
||||
privateKey = keys.privateKey
|
||||
}
|
||||
return {
|
||||
...clientInfo,
|
||||
kind: "wireguard",
|
||||
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
|
||||
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes),
|
||||
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -418,7 +826,7 @@ async function applyNativeTasks(native: IxNativeChange, authorize: () => Promise
|
||||
const observed = (await readRows(client, task.path, Object.keys(task.before))).find(row => row[".id"] === task.rosId)
|
||||
if (!observed || !matches(observed, task.before)) throw new IxConflict("Объект IX изменился перед записью")
|
||||
} else if (task.fields && (await readRows(client, task.path, [".id", "comment", "name"])).some(row =>
|
||||
row.comment === task.fields?.comment || task.fields?.name && row.name === task.fields.name)) {
|
||||
task.fields?.comment && row.comment === task.fields.comment || task.fields?.name && row.name === task.fields.name)) {
|
||||
throw new IxConflict("Объект IX был создан после подготовки плана")
|
||||
}
|
||||
if (!task.fields) {
|
||||
@@ -432,7 +840,10 @@ async function applyNativeTasks(native: IxNativeChange, authorize: () => Promise
|
||||
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)
|
||||
if (!row || !matches(row, task.fields)) throw new IxConflict("Перечитанный объект IX не совпал с планом")
|
||||
if (!row || !matches(row, task.fields)) {
|
||||
const fields = row ? Object.keys(task.fields).filter(field => normalize(field, row[field]) !== normalize(field, task.fields![field])) : []
|
||||
throw new IxConflict("Перечитанный объект IX не совпал с планом · " + task.path + (fields.length ? " · " + fields.join(", ") : ""))
|
||||
}
|
||||
const vrfName = task.path === "/ip/vrf" ? task.fields.name : undefined
|
||||
if (vrfName) {
|
||||
const deadline = Date.now() + 3000
|
||||
@@ -467,16 +878,23 @@ export async function removeIxSegment(id: string, revision: number, expectedDige
|
||||
}
|
||||
|
||||
export async function applyIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, actorId: string,
|
||||
authorize = assertVerifiedConfigurationAccess) {
|
||||
authorize = assertVerifiedConfigurationAccess, web?: { resume: boolean }) {
|
||||
return withApplicationMutationLock(async () => withConfigMutationLock(await ixTarget(change), async () => {
|
||||
await authorize()
|
||||
const current = await readIxSegment(id)
|
||||
assertIxRevision(current, expected.revision)
|
||||
await assertIxName(id, change.configuration.name)
|
||||
await assertIxSites(change.configuration)
|
||||
await assertIxRouterIds(id, change.configuration)
|
||||
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
|
||||
const native = await prepareNative(id, change.configuration, applied)
|
||||
const native = await prepareNative(id, change.configuration, applied, web?.resume)
|
||||
if (web?.resume) await assertIxResume(id, change.revision, native)
|
||||
if (nativePlanDigest(native) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
|
||||
if (web) {
|
||||
await authorize()
|
||||
await audit(pool, actorId, "ix.web.apply_started", null, { segmentId: id, revision: change.revision,
|
||||
sources: native.before.map(device => [device.serverId, device.source]) })
|
||||
}
|
||||
await applyNativeTasks(native, authorize)
|
||||
await authorize()
|
||||
for (const device of native.before) {
|
||||
@@ -486,10 +904,12 @@ export async function applyIxChange(id: string, change: IxChange, expected: { re
|
||||
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 mismatch = desired.find(object => {
|
||||
const row = managedRow(after, object)
|
||||
return row && !isTrue(row.invalid) && matches(row, object.fields)
|
||||
})) throw new IxConflict("Итоговая конфигурация IX не совпала с планом")
|
||||
return !row || isTrue(row.invalid) || !matches(row, object.fields)
|
||||
})
|
||||
if (mismatch) throw new IxConflict("Итоговая конфигурация IX не совпала с планом · узел " + device.serverId + " · " +
|
||||
mismatch.path + " · " + (mismatch.fields.comment ?? mismatch.fields.name))
|
||||
}
|
||||
await authorize()
|
||||
const segment = await writeIxRevision(id, expected.revision, change.configuration, actorId, true)
|
||||
|
||||
@@ -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, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
|
||||
import { compileIxConfiguration, ixClientRoutingTable, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
|
||||
|
||||
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
|
||||
const table = ixNamespace(id)
|
||||
@@ -22,6 +22,47 @@ const fixture = (): IxConfiguration => ixSegmentConfigurationSchema.parse({
|
||||
}],
|
||||
})
|
||||
|
||||
test("managed clients get their own return path and fail closed if both exit probes are lost", () => {
|
||||
const value = fixture(), site = value.sites[0]
|
||||
site.groups.push({ id: "direct", gateway: "198.18.0.10", onFailure: "block",
|
||||
primary: { interface: "ether1", nextHop: "192.0.2.1", probe: "203.0.113.101", viaMain: true },
|
||||
backup: { interface: "ether2", nextHop: "192.0.2.2", probe: "203.0.113.102", viaMain: true } })
|
||||
site.interfaces.push({ name: "linux-wg", kind: "wireguard", prefixes: [],
|
||||
linux: { name: "vps", enabled: true, exit: "direct", destinations: ["10.80.0.0/16"] },
|
||||
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
|
||||
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
|
||||
const objects = compileIxConfiguration(id, value)
|
||||
const clientTable = ixClientRoutingTable(table, "linux-wg")
|
||||
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
|
||||
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
|
||||
assert.equal(defaults.at(-1)?.fields.blackhole, "yes")
|
||||
assert.ok(objects.some(object => object.path === "/ip/firewall/raw" && object.fields["in-interface"] === "linux-wg" &&
|
||||
object.fields["src-address-list"] === "!" + clientTable + "-src"))
|
||||
assert.ok(objects.some(object => object.fields["routing-table"] === "main" &&
|
||||
object.fields["dst-address"] === "10.254.1.2/32" && object.fields.gateway === "10.254.1.2%linux-wg@" + table))
|
||||
assert.ok(objects.some(object => object.fields["routing-table"] === table &&
|
||||
object.fields["dst-address"] === "10.80.0.0/16" && object.fields.blackhole === "yes"))
|
||||
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
|
||||
})
|
||||
|
||||
test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => {
|
||||
const value = fixture(), site = value.sites[0]
|
||||
site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99,
|
||||
provisionTransit: { localEndpoint: "192.0.2.44", remoteEndpoint: "192.0.2.45", localAddress: "10.253.0.1/30", remoteAddress: "10.253.0.2",
|
||||
localPort: 52000, remotePort: 52001, credentialId: id, remoteWan: { interface: "ether1", nextHop: "192.0.2.1", probe: "192.0.2.1", viaMain: true } } })
|
||||
site.groups.push({ id: "other-ix", gateway: "198.18.0.99", onFailure: "block",
|
||||
primary: { interface: "it-abc", nextHop: "10.253.0.2", probe: "10.253.0.2" } })
|
||||
site.interfaces.push({ name: "linux-gre", kind: "gre-ipsec", endpoint: "192.0.2.90", localEndpoint: "192.0.2.44", prefixes: ["10.73.0.0/16"],
|
||||
linux: { name: "server", enabled: true, exit: "other-ix", destinations: [] },
|
||||
provisionGre: { localAddress: "10.254.2.1/30", peerAddress: "10.254.2.2", credentialId: id } })
|
||||
const objects = compileIxConfiguration(id, value)
|
||||
assert.ok(objects.some(object => object.serverId === 99 && object.path === "/ip/firewall/nat" &&
|
||||
object.fields["out-interface"] === "ether1" && object.fields["src-address-list"]))
|
||||
assert.ok(objects.some(object => object.serverId === 99 && object.fields["routing-table"] === "main" && object.fields["dst-address"] === "10.73.0.0/16"))
|
||||
assert.ok(objects.some(object => object.serverId === 17 && object.path === "/ip/ipsec/identity" && object.fields.secret === "ix-credential:" + id))
|
||||
assert.ok(objects.some(object => object.serverId === 17 && object.fields["ipsec-policy"] === "in,none" && object.fields.action === "drop"))
|
||||
})
|
||||
|
||||
test("forwarding permits the VRF to exit through its own members before isolation drops", () => {
|
||||
const objects = compileIxConfiguration(id, fixture())
|
||||
const egress = ixEgressList(id)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { BlockList, isIP } from "node:net"
|
||||
import { createHash } from "node:crypto"
|
||||
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
|
||||
|
||||
export class IxConflict extends Error {
|
||||
constructor(message: string, readonly statusCode = 409) { super(message) }
|
||||
@@ -12,6 +14,7 @@ const familyOf = (address: string) => isIP(address.split("/")[0])
|
||||
const host = (address: string) => canonicalBgpPolicyPrefix(address + (isIP(address) === 4 ? "/32" : "/128"))
|
||||
const routePath = (family: number) => family === 4 ? "/ip/route" : "/ipv6/route"
|
||||
const familyName = (family: number) => family === 4 ? "ip" : "ipv6"
|
||||
const prefixIdentifier = (value: string) => createHash("sha256").update(value).digest("hex").slice(0, 12)
|
||||
const sink = {
|
||||
4: { local: "169.254.255.249/30", neighbor: "169.254.255.250" },
|
||||
6: { local: "fd00:ffff:ffff::1/126", neighbor: "fd00:ffff:ffff::2" },
|
||||
@@ -39,7 +42,7 @@ function unique(values: string[], label: string) {
|
||||
requireIx(new Set(values).size === values.length, "Повторяется " + label)
|
||||
}
|
||||
|
||||
function inNetwork(cidr: string, value: string) {
|
||||
export function inIxNetwork(cidr: string, value: string) {
|
||||
const [network, length] = cidr.split("/")
|
||||
const [candidate, candidateLength] = value.split("/")
|
||||
const family = isIP(network)
|
||||
@@ -50,10 +53,91 @@ function inNetwork(cidr: string, value: string) {
|
||||
return block.check(candidate, familyName)
|
||||
}
|
||||
|
||||
const inNetwork = inIxNetwork
|
||||
|
||||
function groupPaths(group: IxSite["groups"][number]) {
|
||||
return group.backup ? [group.primary, group.backup] : [group.primary]
|
||||
}
|
||||
|
||||
function checkedIxHop(path: IxSite["groups"][number]["primary"], namespace: string) {
|
||||
if (path.viaMain && path.probe === path.nextHop) {
|
||||
return { gateway: path.nextHop + "%" + path.interface + "@main", "target-scope": "10", "check-gateway": "ping" }
|
||||
}
|
||||
return { gateway: path.probe + "@" + (path.viaMain ? "main" : namespace), "target-scope": "11", "check-gateway": "ping" }
|
||||
}
|
||||
|
||||
export function ixClientRoutingTable(namespace: string, binding: string) {
|
||||
return namespace + "-p-" + createHash("sha256").update(binding).digest("hex").slice(0, 8)
|
||||
}
|
||||
|
||||
function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["interfaces"][number],
|
||||
add: (path: string, key: string, fields: Record<string, string>) => void) {
|
||||
const policy = binding.linux!
|
||||
const tunnel = (binding.provisionWireguard ?? binding.provisionGre)!
|
||||
const family = familyOf(tunnel.localAddress) as Family
|
||||
const ip = "/" + familyName(family)
|
||||
const raw = ip + "/firewall/raw"
|
||||
const filter = ip + "/firewall/filter"
|
||||
const key = "linux-" + binding.name
|
||||
const privateTable = ixClientRoutingTable(namespace, binding.name)
|
||||
const sources = privateTable + "-src"
|
||||
const permitted = privateTable + "-dst"
|
||||
const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])]
|
||||
const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])]
|
||||
const ingress = { chain: "prerouting", "in-interface": binding.name }
|
||||
const exit = site.groups.find(group => group.id === policy.exit)
|
||||
const paths = exit ? groupPaths(exit) : []
|
||||
for (const address of sourcesCidr) add(ip + "/firewall/address-list", key + "-src-" + prefixIdentifier(address), { address, list: sources })
|
||||
for (const address of destinations) add(ip + "/firewall/address-list", key + "-dst-" + prefixIdentifier(address), { address, list: permitted })
|
||||
add(raw, key + "-disabled", { ...ingress, action: "drop", disabled: String(policy.enabled) })
|
||||
add(raw, key + "-spoof", { ...ingress, "src-address-list": "!" + sources, action: "drop" })
|
||||
add(raw, key + "-destinations", { ...ingress, "dst-address-list": "!" + permitted, action: "drop", disabled: String(!!exit) })
|
||||
add("/" + familyName(family === 4 ? 6 : 4) + "/firewall/raw", key + "-other-family", { ...ingress, action: "drop" })
|
||||
if (binding.provisionWireguard) {
|
||||
const transportFamily = familyOf(binding.provisionWireguard.hubEndpoint ?? tunnel.localAddress) as Family
|
||||
add("/" + familyName(transportFamily) + "/firewall/filter", key + "-wg-listen", {
|
||||
chain: "input", protocol: "udp", "dst-port": String(binding.provisionWireguard.listenPort), action: "accept",
|
||||
...(binding.provisionWireguard.hubEndpoint && { "dst-address": host(binding.provisionWireguard.hubEndpoint) }),
|
||||
disabled: String(!policy.enabled),
|
||||
})
|
||||
}
|
||||
if (binding.provisionGre) {
|
||||
const transport = { chain: "input", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!),
|
||||
action: "accept", disabled: String(!policy.enabled) }
|
||||
add(filter, key + "-ike", { ...transport, protocol: "udp", "dst-port": "500,4500" })
|
||||
add(filter, key + "-esp", { ...transport, protocol: "ipsec-esp" })
|
||||
add(filter, key + "-encrypted-gre", { ...transport, protocol: "gre", "ipsec-policy": "in,ipsec" })
|
||||
}
|
||||
const outbound = { chain: "forward", "src-address-list": sources, action: "accept", disabled: String(!policy.enabled) }
|
||||
const inbound = { chain: "forward", "dst-address-list": sources }
|
||||
add(filter, key + "-established", { ...inbound, "connection-state": "established,related", action: "accept", disabled: String(!policy.enabled) })
|
||||
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
|
||||
action: "accept", disabled: String(!policy.enabled) })
|
||||
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
|
||||
if (!exit) return
|
||||
add("/routing/table", key + "-table", { name: privateTable, fib: "true" })
|
||||
for (const [index, path] of paths.entries()) {
|
||||
add(routePath(family), key + "-default-" + index, {
|
||||
"routing-table": privateTable, "dst-address": defaultRoute[family], ...checkedIxHop(path, namespace), distance: String(10 + index),
|
||||
})
|
||||
}
|
||||
add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
|
||||
add(ip + "/firewall/mangle", key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
|
||||
action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) })
|
||||
const mainPaths = paths.filter(path => path.viaMain)
|
||||
for (const [index, path] of mainPaths.entries()) {
|
||||
add(filter, key + "-wan-" + index, { ...outbound, "out-interface": path.interface })
|
||||
if (family === 4) add("/ip/firewall/nat", key + "-nat-" + index, { chain: "srcnat", "src-address-list": sources,
|
||||
"out-interface": path.interface, action: "masquerade", disabled: String(!policy.enabled) })
|
||||
}
|
||||
if (mainPaths.length) for (const prefix of sourcesCidr) {
|
||||
add(routePath(family), key + "-return-" + prefixIdentifier(prefix), {
|
||||
"routing-table": "main", "dst-address": prefix, gateway: tunnel.peerAddress + "%" + binding.name + "@" + namespace,
|
||||
disabled: String(!policy.enabled),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function validateSite(site: IxSite, otherId?: number) {
|
||||
unique(site.interfaces.map(entry => entry.name), "интерфейс IX")
|
||||
unique(site.groups.map(entry => entry.id), "группа шлюзов")
|
||||
@@ -77,9 +161,37 @@ function validateSite(site: IxSite, otherId?: number) {
|
||||
requireIx(!wireguard.endpointPort || binding.endpoint, "Порт WireGuard требует внешнего адреса")
|
||||
requireIx(!binding.endpoint || wireguard.endpointPort, "Внешний адрес WireGuard требует порта")
|
||||
}
|
||||
const gre = binding.provisionGre
|
||||
if (gre) {
|
||||
requireIx(binding.kind === "gre-ipsec" && binding.linux && inNetwork(gre.localAddress, gre.peerAddress) &&
|
||||
host(gre.localAddress.split("/")[0]) !== host(gre.peerAddress), "Неверные адреса управляемого GRE/IPsec")
|
||||
}
|
||||
if (binding.provisionTransit) {
|
||||
const link = binding.provisionTransit
|
||||
requireIx(binding.kind === "wireguard" && binding.peerServerId && !binding.linux && !wireguard &&
|
||||
inNetwork(link.localAddress, link.remoteAddress) && link.remoteAddress !== link.localAddress.split("/")[0] &&
|
||||
link.remoteEndpoint !== link.localEndpoint && link.remoteWan.viaMain &&
|
||||
isIP(link.remoteWan.nextHop) === isIP(link.remoteAddress),
|
||||
"Неверные параметры управляемого транзита IX")
|
||||
}
|
||||
if (binding.linux) {
|
||||
const tunnel = wireguard ?? gre
|
||||
requireIx(tunnel && !binding.peerServerId, "Linux-клиенту нужен управляемый туннель")
|
||||
const family = familyOf(tunnel.localAddress)
|
||||
requireIx([...binding.linux.destinations, ...binding.prefixes].every(prefix => familyOf(prefix) === family &&
|
||||
Number(prefix.split("/")[1]) > 0), "Префиксы Linux должны совпадать с семейством туннеля и не могут быть default")
|
||||
const group = binding.linux.exit && groups.get(binding.linux.exit)
|
||||
requireIx(!binding.linux.exit || group && familyOf(group.gateway) === family && group.onFailure === "block",
|
||||
"Для Linux нужен выход того же семейства без неявного переключения на общий шлюз")
|
||||
requireIx(!group || groupPaths(group).every(path => path.interface !== binding.name), "Клиентский туннель не может быть своим выходом")
|
||||
}
|
||||
}
|
||||
const probes = new Map<string, string>()
|
||||
const ownedNetworks = site.interfaces.flatMap(binding => binding.prefixes.map(prefix => ({ binding, prefix })))
|
||||
const ownedNetworks = site.interfaces.flatMap(binding => [
|
||||
...binding.prefixes, ...(binding.provisionTransit ? [binding.provisionTransit.localAddress] : []),
|
||||
...(binding.linux ? [host((binding.provisionWireguard ?? binding.provisionGre)!.peerAddress),
|
||||
host((binding.provisionWireguard ?? binding.provisionGre)!.localAddress.split("/")[0])] : []),
|
||||
].map(prefix => ({ binding, prefix })))
|
||||
for (const [index, first] of ownedNetworks.entries()) {
|
||||
requireIx(Number(first.prefix.split("/")[1]) > 0, "Префикс подключения не может быть default route")
|
||||
for (const second of ownedNetworks.slice(0, index)) {
|
||||
@@ -93,7 +205,7 @@ function validateSite(site: IxSite, otherId?: number) {
|
||||
requireIx(!inNetwork(sink[family].local, group.gateway), "Служебный next hop пересекает сеть отбрасывания")
|
||||
if (group.backup) requireIx(group.primary.interface !== group.backup.interface, "Резерв требует другого интерфейса")
|
||||
for (const candidate of groupPaths(group)) {
|
||||
requireIx(bindings.has(candidate.interface), "Шлюз использует необъявленный интерфейс")
|
||||
requireIx(candidate.viaMain ? !bindings.has(candidate.interface) : bindings.has(candidate.interface), "Шлюз использует интерфейс вне своей таблицы")
|
||||
requireIx([candidate.nextHop, candidate.probe].every(address => isIP(address) === family), "Семейства адресов шлюза не совпадают")
|
||||
requireIx(!site.groups.some(entry => host(entry.gateway) === host(candidate.probe) || host(entry.gateway) === host(candidate.nextHop)), "Рекурсивный шлюз не может быть целью пробы или соседом")
|
||||
requireIx(!inNetwork(sink[family].local, candidate.probe) && !inNetwork(sink[family].local, candidate.nextHop), "Путь использует служебную сеть отбрасывания")
|
||||
@@ -154,16 +266,41 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
||||
const otherId = configuration.sites.find(candidate => candidate.serverId !== site.serverId)?.serverId
|
||||
validateSite(site, otherId)
|
||||
const add = (path: string, key: string, fields: Record<string, string>) => {
|
||||
result.push({ serverId: site.serverId, path, fields: { ...fields, comment: namespace + ":" + key } })
|
||||
const nameOnly = ["/ip/ipsec/profile", "/ip/ipsec/proposal", "/ip/ipsec/peer", "/routing/table"].includes(path)
|
||||
result.push({ serverId: site.serverId, path, fields: nameOnly ? fields : { ...fields, comment: namespace + ":" + key } })
|
||||
}
|
||||
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
|
||||
add("/ip/firewall/filter", "gre-in-" + key, { chain: "input", protocol: "gre", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!), "ipsec-policy": "in,none", action: "drop" })
|
||||
add("/ip/firewall/filter", "gre-out-" + key, { chain: "output", protocol: "gre", "src-address": host(binding.localEndpoint!), "dst-address": host(binding.endpoint!), "ipsec-policy": "out,none", action: "drop" })
|
||||
}
|
||||
const dropInterface = ixDiscardInterface(id)
|
||||
for (const [index, binding] of site.interfaces.entries()) {
|
||||
const wireguard = binding.provisionWireguard
|
||||
if (!wireguard) continue
|
||||
add("/interface/wireguard", "wg-" + index, { name: binding.name, "listen-port": String(wireguard.listenPort) })
|
||||
const key = binding.linux ? binding.name : String(index)
|
||||
if (binding.provisionTransit) compileIxTransit(namespace, site, binding, object => result.push(object))
|
||||
if (wireguard) add("/interface/wireguard", "wg-" + key, { name: binding.name, "listen-port": String(wireguard.listenPort),
|
||||
...(binding.linux && { disabled: String(!binding.linux.enabled) }) })
|
||||
const gre = binding.provisionGre
|
||||
if (gre) {
|
||||
const transport = namespace + "-" + key
|
||||
protectGre(binding, key)
|
||||
add("/ip/ipsec/profile", key, { name: transport, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" })
|
||||
add("/ip/ipsec/proposal", key, { name: transport, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" })
|
||||
add("/ip/ipsec/peer", key, { name: transport, address: host(binding.endpoint!), "local-address": binding.localEndpoint!,
|
||||
profile: transport, "exchange-mode": "ike2", passive: "true" })
|
||||
add("/ip/ipsec/identity", "gre-identity-" + key, { peer: transport, "auth-method": "pre-shared-key",
|
||||
secret: "ix-credential:" + gre.credentialId, disabled: String(!binding.linux!.enabled) })
|
||||
add("/ip/ipsec/policy", "gre-policy-" + key, { peer: transport, "src-address": host(binding.localEndpoint!),
|
||||
"dst-address": host(binding.endpoint!), protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: transport })
|
||||
add("/interface/gre", "gre-" + key, { name: binding.name, "local-address": binding.localEndpoint!,
|
||||
"remote-address": binding.endpoint!, "allow-fast-path": "false", disabled: String(!binding.linux!.enabled) })
|
||||
}
|
||||
}
|
||||
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(",") })
|
||||
for (const binding of site.interfaces.filter(binding => binding.linux)) {
|
||||
compileLinuxPolicy(namespace, site, binding, add)
|
||||
}
|
||||
if (site.interfaces.length) {
|
||||
const egress = ixEgressList(id)
|
||||
add("/interface/list", "egress-list", { name: egress })
|
||||
@@ -186,30 +323,38 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
||||
add(filter, "egress-deny-" + family, { chain: "forward", "out-interface-list": egress, action: "drop" })
|
||||
}
|
||||
for (const [index, binding] of site.interfaces.entries()) {
|
||||
const key = binding.linux ? binding.name : String(index)
|
||||
if (binding.natIpv4) add("/ip/firewall/nat", "nat-" + index, { chain: "srcnat", action: "masquerade", "out-interface": binding.name })
|
||||
if (binding.kind === "gre-ipsec") {
|
||||
add("/ip/firewall/filter", "gre-in-" + index, { chain: "input", protocol: "gre", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!), "ipsec-policy": "in,none", action: "drop" })
|
||||
add("/ip/firewall/filter", "gre-out-" + index, { chain: "output", protocol: "gre", "src-address": host(binding.localEndpoint!), "dst-address": host(binding.endpoint!), "ipsec-policy": "out,none", action: "drop" })
|
||||
}
|
||||
if (binding.kind === "gre-ipsec" && !binding.provisionGre) protectGre(binding, key)
|
||||
}
|
||||
}
|
||||
for (const [index, binding] of site.interfaces.entries()) {
|
||||
const wireguard = binding.provisionWireguard
|
||||
if (!wireguard) continue
|
||||
const family = familyOf(wireguard.localAddress)
|
||||
add(family === 4 ? "/ip/address" : "/ipv6/address", "wg-address-" + index, {
|
||||
address: wireguard.localAddress, interface: binding.name, ...(family === 6 ? { advertise: "no" } : {}),
|
||||
const tunnel = wireguard ?? binding.provisionGre
|
||||
if (binding.provisionTransit) result.push(...ixTransitSourceObjects(namespace, site, binding))
|
||||
if (!tunnel) continue
|
||||
const key = binding.linux ? binding.name : String(index)
|
||||
const family = familyOf(tunnel.localAddress)
|
||||
add(family === 4 ? "/ip/address" : "/ipv6/address", (binding.linux ? "client-address-" : "wg-address-") + key, {
|
||||
address: tunnel.localAddress, interface: binding.name, ...(family === 6 ? { advertise: "no" } : {}),
|
||||
})
|
||||
add("/interface/wireguard/peers", "wg-peer-" + index, {
|
||||
if (wireguard) add("/interface/wireguard/peers", "wg-peer-" + key, {
|
||||
interface: binding.name, "public-key": wireguard.peerPublicKey,
|
||||
"allowed-address": [...new Set([host(wireguard.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])].join(","),
|
||||
...(binding.endpoint ? { "endpoint-address": binding.endpoint, "endpoint-port": String(wireguard.endpointPort) } : {}),
|
||||
})
|
||||
for (const prefix of binding.linux ? binding.prefixes : []) {
|
||||
add(routePath(family), "client-network-" + key + "-" + prefixIdentifier(prefix), {
|
||||
"routing-table": namespace, "dst-address": canonicalBgpPolicyPrefix(prefix),
|
||||
gateway: tunnel.peerAddress + "%" + binding.name + "@" + namespace,
|
||||
})
|
||||
}
|
||||
}
|
||||
const groups = new Map(site.groups.map(group => [group.id, group]))
|
||||
const bgpGroups = new Set(site.neighbors.flatMap(peer => peer.type === "public-feed" ? peer.rules.map(rule => rule.group) : [peer.group]))
|
||||
const knownProbes = new Set<string>()
|
||||
const privateNetworks = [...new Set(site.discardNetworks.concat(site.neighbors.filter(peer => peer.type !== "public-feed").flatMap(peer => peer.prefixes)).map(canonicalBgpPolicyPrefix))]
|
||||
const privateNetworks = [...new Set(site.discardNetworks.concat(site.neighbors.filter(peer => peer.type !== "public-feed").flatMap(peer => peer.prefixes),
|
||||
site.interfaces.flatMap(binding => binding.linux?.destinations ?? [])).map(canonicalBgpPolicyPrefix))]
|
||||
for (const family of families) {
|
||||
if (!site.groups.some(group => familyOf(group.gateway) === family) && !privateNetworks.some(prefix => familyOf(prefix) === family)) continue
|
||||
const path = routePath(family)
|
||||
@@ -225,10 +370,14 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
||||
for (const [index, candidate] of distinctPaths.entries()) {
|
||||
const probe = host(candidate.probe)
|
||||
if (!knownProbes.has(probe)) {
|
||||
localRoute("probe-" + knownProbes.size, { "dst-address": probe, gateway: candidate.nextHop + "%" + candidate.interface + "@" + namespace, scope: "10", "target-scope": "10" })
|
||||
const fields = { "dst-address": probe, gateway: candidate.nextHop + "%" + candidate.interface + "@" + (candidate.viaMain ? "main" : namespace),
|
||||
scope: "10", "target-scope": "10" }
|
||||
if (candidate.viaMain && candidate.probe !== candidate.nextHop) {
|
||||
add(path, "probe-main-" + knownProbes.size, { ...fields, "routing-table": "main" })
|
||||
} else localRoute("probe-" + knownProbes.size, fields)
|
||||
knownProbes.add(probe)
|
||||
}
|
||||
localRoute("gw-" + group.id + "-" + index, { "dst-address": host(group.gateway), gateway: via(candidate.probe), scope: "20", "target-scope": "11", "check-gateway": "ping", distance: String(10 + index) })
|
||||
localRoute("gw-" + group.id + "-" + index, { "dst-address": host(group.gateway), ...checkedIxHop(candidate, namespace), scope: "20", distance: String(10 + index) })
|
||||
}
|
||||
localRoute("gw-" + group.id + "-discard", { "dst-address": host(group.gateway), gateway: sink[family].neighbor + "%" + dropInterface + "@" + namespace, scope: "20", "target-scope": "10", distance: "254" })
|
||||
// RouterOS 7.24 resolves addresses rewritten by a BGP input filter in main.
|
||||
@@ -244,7 +393,7 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
||||
}
|
||||
// Compare exit path health directly: a group's final discard next hop must never win as an ordinary exit.
|
||||
for (const [index, candidate] of familyExits.flatMap(groupPaths).entries()) {
|
||||
localRoute("exit-" + family + "-" + index, { "dst-address": defaultRoute[family], gateway: via(candidate.probe), "check-gateway": "ping", "target-scope": "11", distance: String(10 + index) })
|
||||
localRoute("exit-" + family + "-" + index, { "dst-address": defaultRoute[family], ...checkedIxHop(candidate, namespace), distance: String(10 + index) })
|
||||
}
|
||||
localRoute("default-discard-" + family, { "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
|
||||
}
|
||||
@@ -277,6 +426,8 @@ export function compileIxConfiguration(id: string, configuration: IxConfiguratio
|
||||
})
|
||||
}
|
||||
}
|
||||
unique(result.filter(object => object.fields["routing-table"] === "main" && object.fields["dst-address"])
|
||||
.map(object => object.serverId + ":" + object.fields["dst-address"]), "служебный или обратный маршрут IX в main")
|
||||
requireIx(result.length <= 500, "План IX превышает 500 объектов; разделите конфигурацию")
|
||||
return result
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { PoolClient } from "pg"
|
||||
import { isIPv4 } from "node:net"
|
||||
import { ixSegmentConfigurationSchema, type IxConfiguration, type IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../db/index.js"
|
||||
import { audit } from "../modules/mcp/store.js"
|
||||
@@ -64,12 +65,70 @@ export function assertIxRevision(current: IxSegment | null, expected: number) {
|
||||
if ((current?.revision ?? 0) !== expected) throw new IxConflict("Ревизия IX изменилась. Обновите данные и подготовьте новый план")
|
||||
}
|
||||
|
||||
export async function ixReservedRouterIds(id?: string, sql: Pick<PoolClient, "query"> = pool) {
|
||||
const { rows } = await sql.query<{ router_id: string }>(`
|
||||
SELECT site->>'routerId' AS router_id
|
||||
FROM ix_segments s
|
||||
LEFT JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
|
||||
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(s.configuration->'sites','[]'::jsonb) ||
|
||||
COALESCE(r.configuration->'sites','[]'::jsonb)) site
|
||||
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
AND ($1::uuid IS NULL OR s.id<>$1)
|
||||
`, [id ?? null])
|
||||
return new Set(rows.map(row => row.router_id))
|
||||
}
|
||||
|
||||
export async function ixReservedTunnelBindings(serverId: number) {
|
||||
const { rows } = await pool.query<{ configuration: unknown }>(`
|
||||
SELECT s.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
|
||||
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
UNION ALL
|
||||
SELECT r.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
|
||||
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
|
||||
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
`, [serverId])
|
||||
return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites
|
||||
.flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
|
||||
}
|
||||
|
||||
export function nextIxRouterId(used: ReadonlySet<string>) {
|
||||
const [address, mask] = (process.env.MMAPP_IX_ROUTER_ID_POOL ?? "10.255.0.0/16").split("/")
|
||||
const length = Number(mask)
|
||||
if (!isIPv4(address) || !Number.isInteger(length) || length < 16 || length > 30) {
|
||||
throw new IxConflict("Пул Router ID должен быть IPv4-сетью с маской от /16 до /30")
|
||||
}
|
||||
const size = 2 ** (32 - length)
|
||||
const base = address.split(".").reduce((value, part) => value * 256 + Number(part), 0)
|
||||
if (base % size !== 0) throw new IxConflict("Для пула Router ID укажите адрес сети")
|
||||
for (let index = 1; index < size - 1; index++) {
|
||||
const value = base + index
|
||||
const candidate = [value >>> 24, (value >>> 16) & 255, (value >>> 8) & 255, value & 255].join(".")
|
||||
if (!used.has(candidate)) return candidate
|
||||
}
|
||||
throw new IxConflict("Пул Router ID IX исчерпан")
|
||||
}
|
||||
|
||||
export async function assertIxRouterIds(id: string, configuration: IxConfiguration, sql: Pick<PoolClient, "query"> = pool) {
|
||||
const used = await ixReservedRouterIds(id, sql)
|
||||
const existing = await readIxSegment(id, sql)
|
||||
const local = new Set<string>()
|
||||
for (const site of configuration.sites) {
|
||||
const unchanged = existing?.configuration.sites.some(old => old.serverId === site.serverId && old.routerId === site.routerId)
|
||||
if (local.has(site.routerId) || site.routerId === "0.0.0.0" || (site.autoRouterId && !unchanged && used.has(site.routerId))) {
|
||||
throw new IxConflict("Router ID " + site.routerId + " уже используется")
|
||||
}
|
||||
local.add(site.routerId)
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeIxRevision(id: string, expected: number, configuration: IxConfiguration, actor: string, applied: boolean) {
|
||||
const client = await pool.connect()
|
||||
try {
|
||||
await client.query("BEGIN")
|
||||
await admitPartitionWriter(client)
|
||||
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('ix-router-id',0))")
|
||||
await assertIxSites(configuration, client)
|
||||
await assertIxRouterIds(id, configuration, client)
|
||||
const revision = expected + 1
|
||||
const { rows: [row] } = expected === 0
|
||||
? await client.query<SegmentRow>(`INSERT INTO ix_segments(id,name,revision,configuration,applied_revision)
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import type { IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
|
||||
export function ixTransitRemoteInterface(namespace: string, name: string) {
|
||||
return namespace.slice(0, 16) + "-" + name.slice(-12)
|
||||
}
|
||||
|
||||
export function compileIxTransit(namespace: string, site: IxSite, binding: Binding, add: (object: IxRouterObject) => void) {
|
||||
const transit = binding.provisionTransit!
|
||||
const serverId = binding.peerServerId!
|
||||
const remote = ixTransitRemoteInterface(namespace, binding.name)
|
||||
const remoteVrf = remote + "-v"
|
||||
const ipv6 = transit.remoteAddress.includes(":")
|
||||
const ip = ipv6 ? "/ipv6" : "/ip"
|
||||
const hostMask = ipv6 ? "/128" : "/32"
|
||||
const defaultPrefix = ipv6 ? "::/0" : "0.0.0.0/0"
|
||||
const clients = site.interfaces.filter(item => {
|
||||
const group = site.groups.find(group => group.id === item.linux?.exit)
|
||||
return item.linux?.enabled && group && [group.primary.interface, group.backup?.interface].includes(binding.name)
|
||||
})
|
||||
const sources = [...new Set(clients.flatMap(client => [
|
||||
(client.provisionWireguard ?? client.provisionGre)!.peerAddress + hostMask, ...client.prefixes,
|
||||
]).map(canonicalBgpPolicyPrefix))].sort()
|
||||
const hub = transit.localAddress.split("/")[0]
|
||||
const mask = transit.localAddress.split("/")[1]
|
||||
const key = (role: string, kind: "private" | "public") => `ix-transit:${kind}:${transit.credentialId}:${role}`
|
||||
const emit = (node: number, path: string, suffix: string, fields: Record<string, string>) => add({
|
||||
serverId: node, path, fields: { ...fields, comment: namespace + ":transit-" + binding.name + "-" + suffix },
|
||||
})
|
||||
const emitRemote = (path: string, suffix: string, fields: Record<string, string>) => emit(serverId, path, suffix, fields)
|
||||
emitRemote("/interface/wireguard", "wg", {
|
||||
name: remote, "listen-port": String(transit.remotePort), "private-key": key("b", "private"),
|
||||
})
|
||||
emitRemote("/ip/vrf", "vrf", { name: remoteVrf, interfaces: remote })
|
||||
emitRemote(ip + "/address", "address", { interface: remote, address: transit.remoteAddress + "/" + mask,
|
||||
...(ipv6 && { advertise: "no" }) })
|
||||
emitRemote("/interface/wireguard/peers", "peer", {
|
||||
interface: remote, "public-key": key("a", "public"), "allowed-address": [hub + hostMask, ...sources].join(","),
|
||||
"endpoint-address": transit.localEndpoint, "endpoint-port": String(transit.localPort), "persistent-keepalive": "25s",
|
||||
})
|
||||
emitRemote(ip + "/route", "default", { "routing-table": remoteVrf, "dst-address": defaultPrefix,
|
||||
gateway: transit.remoteWan.nextHop + "%" + transit.remoteWan.interface + "@main",
|
||||
})
|
||||
emitRemote(ip + "/route", "default-drop", { "routing-table": remoteVrf, "dst-address": defaultPrefix, blackhole: "yes", distance: "254" })
|
||||
const filter = ip + "/firewall/filter"
|
||||
const srcList = remote + "-src"
|
||||
emitRemote("/ip/firewall/filter", "listen", { chain: "input", protocol: "udp", "src-address": transit.localEndpoint + "/32",
|
||||
"dst-address": transit.remoteEndpoint + "/32", "dst-port": String(transit.remotePort), action: "accept" })
|
||||
emitRemote(filter, "ping", { chain: "input", "in-interface": remoteVrf, protocol: ipv6 ? "icmpv6" : "icmp", "src-address": hub + hostMask, action: "accept" })
|
||||
emitRemote(filter, "deny-management", { chain: "input", "in-interface": remoteVrf, action: "drop" })
|
||||
emitRemote(filter, "out", { chain: "forward", "in-interface": remoteVrf, "out-interface": transit.remoteWan.interface,
|
||||
"src-address-list": srcList, action: "accept" })
|
||||
emitRemote(filter, "return-filter", {
|
||||
chain: "forward", "dst-address-list": srcList, "connection-state": "established,related", action: "accept",
|
||||
})
|
||||
emitRemote(filter, "deny-forward", { chain: "forward", "in-interface": remoteVrf, action: "drop" })
|
||||
emitRemote(filter, "deny-inbound", { chain: "forward", "dst-address-list": srcList, action: "drop" })
|
||||
if (!ipv6) emitRemote("/ip/firewall/nat", "nat", { chain: "srcnat", "out-interface": transit.remoteWan.interface,
|
||||
"src-address-list": srcList, action: "masquerade" })
|
||||
for (const address of [hub + hostMask, ...sources]) {
|
||||
const identity = createHash("sha256").update(address).digest("hex").slice(0, 12)
|
||||
emitRemote(ip + "/firewall/address-list", "client-" + identity, { address, list: srcList })
|
||||
for (const table of address === hub + hostMask ? ["main"] : [remoteVrf, "main"]) emitRemote(ip + "/route", "return-" + table + "-" + identity, {
|
||||
"routing-table": table, "dst-address": address, gateway: hub + "%" + remote + "@" + remoteVrf,
|
||||
})
|
||||
}
|
||||
emit(site.serverId, "/interface/wireguard", "source-wg", {
|
||||
name: binding.name, "listen-port": String(transit.localPort), "private-key": key("a", "private"),
|
||||
})
|
||||
// Source peer/address depend on the local VRF assignment and are emitted by the caller.
|
||||
}
|
||||
|
||||
export function ixTransitSourceObjects(namespace: string, site: IxSite, binding: Binding): IxRouterObject[] {
|
||||
const transit = binding.provisionTransit!
|
||||
const ipv6 = transit.remoteAddress.includes(":")
|
||||
return [
|
||||
{ serverId: site.serverId, path: ipv6 ? "/ipv6/address" : "/ip/address", fields: { address: transit.localAddress, interface: binding.name,
|
||||
...(ipv6 && { advertise: "no" }),
|
||||
comment: namespace + ":transit-" + binding.name + "-source-address" } },
|
||||
{ serverId: site.serverId, path: "/interface/wireguard/peers", fields: {
|
||||
interface: binding.name, "public-key": `ix-transit:public:${transit.credentialId}:b`, "allowed-address": ipv6 ? "::/0" : "0.0.0.0/0",
|
||||
"endpoint-address": transit.remoteEndpoint, "endpoint-port": String(transit.remotePort), "persistent-keepalive": "25s",
|
||||
comment: namespace + ":transit-" + binding.name + "-source-peer",
|
||||
} },
|
||||
{ serverId: site.serverId, path: "/ip/firewall/filter", fields: {
|
||||
chain: "input", action: "accept", protocol: "udp", "src-address": transit.remoteEndpoint + "/32",
|
||||
"dst-address": transit.localEndpoint + "/32", "dst-port": String(transit.localPort),
|
||||
comment: namespace + ":transit-" + binding.name + "-source-listen",
|
||||
} },
|
||||
]
|
||||
}
|
||||
@@ -38,6 +38,19 @@ else {
|
||||
try {
|
||||
await initDatabase();await app.listen({host:"127.0.0.1",port:0})
|
||||
serverId=Number((await pool.query("INSERT INTO servers(name,host,port,use_ssl,enabled,username,password,updated_at) VALUES($1,'127.0.0.1',$2,false,true,'fixture','fixture',$3) RETURNING id",[prefix+"server",address.port,new Date(Date.now()-3_600_000).toISOString()])).rows[0].id)
|
||||
const sampleUrl = `/traffic/servers/${serverId}/live?once=1`
|
||||
const beforeSample = nativeRequests
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1,ether2")).statusCode, 400)
|
||||
assert.equal(nativeRequests, beforeSample)
|
||||
const sample = await app.inject(sampleUrl + "&iface=ether1")
|
||||
assert.equal(sample.statusCode, 200)
|
||||
assert.equal(sample.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(sample.json(), { rxMbps: 0, txMbps: 0, at: sample.json().at, timestampKind: "backend-receipt" })
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
mode = "malformed"
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1")).statusCode, 503)
|
||||
mode = "zero"
|
||||
cases += 3
|
||||
let stream=await open(),event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);assert.equal(event?.data.timestampKind,"backend-receipt");stream.close();cases++
|
||||
for(const kind of ["empty","malformed","partial"]){mode=kind;two=kind==="partial";stream=await open();event=await stream.next();assert.equal(event?.event,"error");stream.close();cases++}
|
||||
mode="fallback";two=true;stream=await open();event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);stream.close();cases++
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
# IX как транзитный узел
|
||||
|
||||
**План для согласования · 23 ноября 2026 · GPT-6.2 Astra**
|
||||
|
||||
Оператор открывает IX-узел, подключает Linux-сервер, выдаёт ему конфигурацию и выбирает выход. В той же карточке он видит, подключился ли клиент, какие сети ему разрешены, каким путём действительно идёт трафик и что произойдёт при отказе. Основная единица работы с пользователем — клиентское подключение. Сегмент сохраняет роль изолированного маршрутизируемого домена.
|
||||
|
||||
## Как подключить VPS с адресом 123.123.123.123
|
||||
|
||||
Ниже показан **предлагаемый** сценарий. `123.123.123.123` — внешний адрес VPS из примера. Внутренние адреса туннеля и имена клиента иллюстративны.
|
||||
|
||||
1. Открыть **Точки обмена трафиком → pl-ix01 → Клиенты → Подключить Linux**. Ввести имя `vps-01` и внешний адрес `123.123.123.123`. Для WireGuard с переменным адресом клиента поле можно оставить пустым. Для GRE/IPsec нужны фиксированные доступные внешние адреса обеих сторон.
|
||||
2. Оставить **WireGuard** и вставить публичный ключ Linux. Альтернатива — выбрать **GRE/IPsec** и выдачу индивидуального IKEv2 PSK. Мастер подставит сегмент, публичный endpoint IX, свободные адреса туннеля и порт. В случае нескольких вариантов оператор выберет нужный. Для нового узла тот же экран предложит создать первый сегмент.
|
||||
3. Выбрать **Доступ → Интернет через этот IX**. Для ограниченного доступа выбрать **Только указанные сети** и указать назначения. Поле **Сети за клиентом** отдельно описывает, какие источники и объявления вправе использовать VPS. BGP, доступ к другим клиентам и управление RouterOS требуют отдельных разрешений. Обычному VPS достаточно адреса внутри туннеля.
|
||||
4. Нажать **Выдать доступ**. Перед кнопкой уже видны клиент, разрешения, устройства, основной и резервный выходы, а также ожидаемое влияние. Backend сохранит намерение, применит конфигурацию и перечитает её с CHR. После этого доступны пакет **Скачать для Linux** и инструкция для установки. Приватный ключ WireGuard остаётся на VPS.
|
||||
5. После установки открыть строку клиента. В ней отображаются handshake WireGuard или IKE/ESP SA, время наблюдения, RX/TX и фактический выход. **Проверить путь** показывает отдельный результат для IPv4 и IPv6. Для подтверждения пути от самого VPS мастер даёт клиентскую проверку доступности и наблюдаемого адреса выхода. Одной пробы с CHR для этого недостаточно.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
v["Linux VPS<br/>123.123.123.123"] -->|"WireGuard или GRE/IPsec"| a["pl-ix01<br/>клиент и его права"]
|
||||
a --> p{"Политика выхода"}
|
||||
p -->|"Локально"| aw["WAN первого IX"]
|
||||
p -->|"Через другой IX"| b["Второй IX"]
|
||||
p -->|"Через ExitNode"| e["arn-gw01"]
|
||||
aw --> inet["Интернет"]
|
||||
b -->|"Его WAN"| inet
|
||||
e -->|"Его WAN"| inet
|
||||
p -->|"Только внутренние сети"| private["Разрешённые префиксы"]
|
||||
```
|
||||
|
||||
Для внешнего сайта с маршрутом по умолчанию оператор видит `vps-01 → pl-ix01 → arn-gw01 → Интернет`. Для более специфичного BGP-префикса в той же карточке может быть другой путь. Второй IX на схеме — пример будущего узла.
|
||||
|
||||
## Что сейчас происходит в продукте
|
||||
|
||||
| Наблюдение | Следствие для оператора |
|
||||
| --- | --- |
|
||||
| Форма “Подключения” принимает имя интерфейса текстом. Списки путей и BGP строятся только из `site.interfaces` текущего черновика. `GET /ix/nodes` возвращает серверы из PostgreSQL. | Даже исправная CHR с `ether1` не наполняет этот список. Успешный полный опрос сам по себе форму не исправит. |
|
||||
| Новый сайт получает пустой `routerId`. Адрес `192.0.2.10` показан как placeholder. | Форма требует вручную придумать обязательный IPv4-идентификатор. |
|
||||
| Вкладка “Linux-клиенты” перечисляет внешние привязки из применённой ревизии. WireGuard уже умеет создать интерфейс и пир. Linux-шаблон использует локальный приватный ключ и `Table = off`. GRE предполагает предварительно созданные GRE и политику IPsec. | Клиента сегодня можно представить через **Конфигурация → Подключения → Внешний сервер**, сохранить, применить и скачать шаблон. Назначить одному VPS понятный профиль прав и выход из его карточки пока нельзя. |
|
||||
| Компилятор создаёт VRF, рекурсивные группы, BGP-фильтры и общие `exits` площадки. Между интерфейсами одного сегмента есть общее разрешение пересылки. `peerServerId` обозначает связь, а объекты компилируются для `site.serverId`. | Одна ссылка на ExitNode ещё не настраивает удалённый конец, обратный маршрут и NAT. Нужны двусторонний план и явная изоляция клиентов. |
|
||||
| REST уже предлагает `plan` и `apply` с проверкой ревизии, оператора и digest. MCP использует общий механизм применения. | Новый мастер может скрыть технические шаги за одной кнопкой. Обязательное подключение MCP в WebUI избыточно. |
|
||||
|
||||
В инвентаре MikrotikManager на 23 ноября, 04:48 UTC, были три JumpHost, один ExitNode `arn-gw01` и один IX `pl-ix01` (ID 5). Home Router на момент чтения отсутствовал. У IX отсутствовала отметка полного опроса, при этом каталог интерфейсов вернул `ether1`, а источник телеметрии показал его в текущей выборке и ряд прежних объектов со статусом `unknown`. Само присутствие `ether1` не доказывает, что это выделенный WAN или что его можно переместить в VRF. Примеры ниже используют этот снимок только для выбора ролей.
|
||||
|
||||
Основание в проекте — [редактор площадки](../app/(main)/ix/ix-site-editor.tsx), [форма узла](../app/(main)/ix/ix-view.tsx), [REST IX](../backend/src/routes/internet-exchange.ts), [компилятор](../backend/src/services/internet-exchange-plan.ts), [выдача Linux-конфигураций](../backend/src/services/internet-exchange-client.ts), [применение и наблюдение](../backend/src/services/internet-exchange-execution.ts).
|
||||
|
||||
## Рабочее место оператора
|
||||
|
||||
```text
|
||||
Точки обмена трафиком pl-ix01 / ix-eu [Подключить Linux]
|
||||
─────────────────────── ──────────────────────────────────────────────────
|
||||
pl-ix01 Клиенты Выходы и резерв Маршруты и BGP Узел
|
||||
Имя Туннель Доступ Выход Состояние
|
||||
vps-01 WG Интернет arn-gw01 Handshake …
|
||||
|
||||
При выборе клиента
|
||||
vps-01 · 123.123.123.123 · адрес в туннеле
|
||||
Права и сети Основной и резервный путь
|
||||
[Изменить доступ] [Сменить выход]
|
||||
[Конфиг Linux] [Проверить путь] [Отозвать…]
|
||||
```
|
||||
|
||||
На широком экране слева тот же выбор серверов, что в “Рекурсивных маршрутах”, “Фильтрах” и “Firewall”. На телефоне — штатный мобильный выбор узла. В карточку ведут и список серверов, и `/ix`. Для прямой ссылки сохраняются выбранные узел, сегмент и клиент. Существующие ссылки на сегменты продолжают открывать нужный контекст. [ServerRailLayout](../components/server-rail-layout.tsx), [рабочее место маршрутов](../app/(main)/recursive-routes/page.tsx).
|
||||
|
||||
| Раздел | Действие с экрана |
|
||||
| --- | --- |
|
||||
| **Клиенты** | Добавить, выдать конфигурацию, сменить права/выход, проверить путь, приостановить, возобновить или отозвать. Фильтр по состоянию и типу туннеля. Видны объём, время последнего обмена, применённая и ожидающая ревизии. |
|
||||
| **Выходы и резерв** | Добавить локальный WAN, другой IX или ExitNode. На карточке выхода видны транспорт, конечный WAN, IPv4/IPv6, возвращаемые клиентские сети, проба, активный путь и клиенты, которых затронет переключение. |
|
||||
| **Маршруты и BGP** | Выбрать клиента/профиль, ввести IP назначения и увидеть совпавший префикс, источник, группу и фактический next hop. Назначить правило “community или разрешённый префикс → группа шлюзов”, посмотреть принятые и отклонённые объявления с причиной. |
|
||||
| **Узел** | Инвентарь CHR с временем чтения, принадлежность интерфейсов, ASN, предложенный Router ID, сегменты, расширенные настройки и история изменений. |
|
||||
|
||||
Быстрые действия с готовым профилем — **Обновить интерфейсы**, **Проверить путь**, **Скачать публичный шаблон**. Выбор готового выхода завершается одной кнопкой **Применить** в том же окне. Для нового выхода с изменениями на двух узлах перед применением показать оба конца и затронутые подключения. Отзыв называет конкретного клиента и подтверждается явно. Повторный клик и повтор HTTP-запроса возвращают состояние той же операции.
|
||||
|
||||
Использовать установленные компоненты проекта. Список клиентов — ReUI Data Grid, подробности — боковая панель по образцу проекта, компактный выбор режима — Button Group. Зелёный статус показывать только с названием подтверждённого факта, например “Handshake 12 с назад”. Истёкшая проба, устаревший снимок и недоступный роутер имеют разные состояния. [Предпросмотр Data Grid](https://reui.io/components/data-grid?ref=mcp), [Button Group](https://reui.io/components/button-group).
|
||||
|
||||
## Что означает “выдать права”
|
||||
|
||||
У подключения есть постоянный ID, владелец сегмента, площадка, имя, транспорт, состояние и ссылка на профиль маршрутизации. При выдаче фиксируются разрешённые источники, назначения и семейства адресов, разрешение выхода в Интернет, доступ к другим клиентам и, если включён, список разрешённых BGP-анонсов. Принятые объявления, разрешённые назначения клиента и `AllowedIPs` на разных концах WG — три разных настройки. Компилятор выводит их из намерения оператора и показывает итог перед применением.
|
||||
|
||||
* **Только сети.** До перечисленных префиксов разрешена пересылка, остальной трафик отбрасывается. Подмена источника, чужие клиенты и управление CHR закрыты по умолчанию. Ограничения действуют на стороне IX, в том числе если клиент вручную изменит Linux-конфиг.
|
||||
* **Интернет.** Разрешён маршрут по умолчанию для выбранного семейства, исключаются служебные диапазоны IX и чужие сети. Доступ между конкретными клиентами или от Home Router/JH добавляется парой разрешений и обратных маршрутов.
|
||||
* **BGP-клиент.** Сессия привязана к его туннелю, ASN и адресному семейству. Импорт ограничен согласованными принадлежащими клиенту префиксами и максимальным количеством, экспорт — договорённым набором. Публичный фид и частный клиент используют разные политики.
|
||||
* **Приостановить, возобновить, отозвать.** Приостановка блокирует проход и анонсы, сохраняя профиль. После отзыва старый ключ/PSK, туннельный доступ и маршруты теряют силу. Ротация выдаёт новую версию, а аудит связывает действие, ревизию и оператора. Второй клиент со своим ключом продолжает работу.
|
||||
|
||||
Права оператора приложения проверяются отдельно. Просмотр сети использует `mm:network:read`, модификации — `mm:network:write` плюс проверку доступа к затронутым узлам. Закрытую часть конфигурации получает только оператор с правом выдачи для клиента либо сам клиент по одноразовому ограниченному по времени получению. Список клиентов, обычное чтение MCP, логи, план RouterOS и журнал ревизий возвращают только публичные поля. Для PSK хранить ссылку на защищённый секрет и его версию, исключить секрет из URL, аудита и HTTP-кэша. Утрата секрета решается ротацией.
|
||||
|
||||
**WireGuard.** Мастер резервирует адреса и подбирает порт с учётом занятых на узле. Публичный ключ VPS задаёт оператор, свой ключ генерирует IX. Пакет содержит `wg-quick` и применимые маршруты. Для полного туннеля обеспечить underlay-путь до endpoint и явно обозначенный способ сохранения управления VPS. Для выборочного режима добавить только разрешённые сети. Проверить доступ после перезагрузки Linux.
|
||||
|
||||
**GRE/IPsec.** Мастер создаёт либо принимает проверенные параметры GRE, IKEv2 в транспортном режиме, соответствующие политики и защиту от открытого GRE. Linux получает согласованный strongSwan-профиль, внутренние адреса, команды или unit для туннеля и маршруты. Проверить обе стороны при потере SA и смене PSK. Внешний IPv4, NAT и разрешения провайдера выявляются на предварительной проверке, а мастер предлагает WireGuard при неподходящих условиях.
|
||||
|
||||
## Выбор выхода и маршрутов
|
||||
|
||||
| Выбор | Прямой путь | Что делает план для обратного направления |
|
||||
| --- | --- | --- |
|
||||
| **Интернет с этого IX** | Клиент → IX → выбранный WAN | Для частного IPv4 включить целевой SNAT на фактическом WAN. Для маршрутизируемого публичного префикса или IPv6 проверить делегирование, обратный маршрут и межсетевой экран. Без подготовки IPv6 пометить его недоступным. |
|
||||
| **Через другой IX** | Клиент → IX A → согласованный транзитный туннель → IX B → его выход | На B подготовить маршрут к сети клиента через A, фильтр и выбранный внешний выход. NAT, если требуется, выполняется только на последнем выходе. Возврат и отсутствие циклов проверить на обеих сторонах. |
|
||||
| **Через ExitNode** | Клиент → IX → транзитный туннель → ExitNode → его WAN | На ExitNode явно создать или проверить peer, форвардинг, обратный маршрут и правила внешнего выхода. В действующие политики JH/других пользователей добавлять только согласованные объекты текущего подключения. |
|
||||
| **Изолированный сегмент** | Клиент → IX → разрешённая внутренняя сеть или другой разрешённый клиент | На обеих сторонах задать маршруты возврата и согласованные ACL. Отсутствие выхода означает отбрасывание внешнего трафика. Подключение Home Router/JH моделируется как доверенная связь с ограниченным импортом и экспортом. |
|
||||
|
||||
Сохранить существующую VRF сегмента и его профиль по умолчанию. Для клиентов с разными выходами требуется самостоятельный контекст выбора маршрута. Первый вариант для стенда — отдельная VRF на **отличающийся профиль маршрутизации** с выделенными логическими туннелями или VLAN на границах. Несколько клиентов могут разделять такой профиль с отдельными ACL и защитой от подмены источника. Массовая смена профиля показывает количество и имена затронутых клиентов. Операция “Сменить выход” для одного клиента переводит только его в выбранный профиль.
|
||||
|
||||
Особый случай — одноинтерфейсный CHR, где `ether1` одновременно WAN и управление. Для выхода с него предложить проверяемый обмен маршрутами между IX VRF и WAN-контекстом с разрешением только трафика профиля, обратным путём и фильтрацией. Назначение общего физического WAN целиком в IX VRF может оборвать доступ к CHR. Подтвердить вариант для RouterOS 7.24.5 отдельным тестом управления, пересылки, SNAT и обратного пути. Пока это не доказано, мастер показывает точную причину и предлагает поддерживаемый выделенный логический uplink. Выделенный интерфейс можно присоединять после проверки владельца, bridge, VRF и зависимых маршрутов. [Документация MikroTik по VRF](https://help.mikrotik.com/docs/spaces/ROS/pages/328206/Virtual%2BRouting%2Band%2BForwarding%2B-%2BVRF).
|
||||
|
||||
**Порядок выбора.** Для авторизованного источника IX выбирает его контекст, проверяет разрешённые назначения и ищет активный маршрут по наиболее длинному префиксу. Специфичный маршрут из BGP или статики направляет пакет в назначенную группу, общий маршрут — на разрешённый выход. Для частного префикса установить защитный маршрут отбрасывания, чтобы при отзыве анонса он не ушёл по публичному default. В UI выводить отдельно намерение, выбранный маршрут RIB/FIB, фактический интерфейс `immediate-gw` и время проверки.
|
||||
|
||||
**Резервирование.** Для каждой группы и семейства использовать уже имеющиеся основной и резервный next hop, закреплённые за своим интерфейсом независимые пробы и рекурсивное разрешение RouterOS. Проверять адрес за проверяемым участком, а не только ближний конец туннеля. Установить защиту от ухода самой пробы через резерв. При отказе обоих путей для частного трафика действует блокировка. Для интернет-профиля оператор может явно выбрать другой разрешённый выход. Проверять весь граф основных и резервных выходов на циклы перед применением. Переключение происходит на CHR при недоступном менеджере. После смены публичного SNAT-адреса существующие TCP-сессии могут оборваться, отдельной проверкой подтвердить новые соединения.
|
||||
|
||||
**Пример BGP.** Для демонстрационного `203.0.113.0/24` и community `65000:120` оператор выбирает группу “Через ARN”. Принятый префикс появляется в таблице нужного профиля, активный next hop переключается вместе с группой. Полученные NLRI не экспортируются другим клиентам автоматически. Существующий компилятор RouterOS уже поддерживает `set gw` на служебный адрес и ограниченную запись для разрешения этого адреса в `main`. Такой служебный маршрут показывать явно и проверять на коллизии. [Компилятор IX](../backend/src/services/internet-exchange-plan.ts), [текущие стендовые сценарии](ix.md).
|
||||
|
||||
## Инвентарь CHR и автоматический Router ID
|
||||
|
||||
* При открытии **Узел** или выборе площадки запросить инвентарь именно этой CHR через IX REST. Переиспользовать существующий сервис каталога и проверяемые чтения RouterOS. Объединить `/interface` с адресами, VRF, bridge-портами, транспортом, маршрутами underlay и владельцем привязки. Старые данные трафика подходят для истории. Для каждого интерфейса показывать имя, тип, состояние, время наблюдения и причину ограничения. Пустой результат, отказ доступа, устаревший снимок и обрыв связи различимы.
|
||||
* Выбрать либо существующий подходящий интерфейс CHR, либо **Создать управляемый туннель**. В маршрутах предлагать только привязки, пригодные для роли. Подтверждать устройство, имя, принадлежность и используемые адреса повторным чтением перед записью. После смены узла сбросить старый выбор и игнорировать запоздалый ответ предыдущего запроса. [Каталог интерфейсов](../backend/src/routes/users.ts), [чтение перед применением](../backend/src/services/internet-exchange-execution.ts).
|
||||
* Сохранённый Router ID площадки имеет приоритет. Для новой площадки backend определяет домен маршрутизации и опрашивает эффективные BGP/OSPF Router ID и `/routing/id`, включая ссылки на именованные ID. Учитывать существующие IX-ревизии, черновики и параллельные резервации. Уже используемый ID можно сохранить у той же логической площадки после сверки владения. Если нужен новый, предложить свободный IPv4 ID из настроенного инфраструктурного пула с проверкой коллизий во всех связанных доменах. При отсутствии пула мастер предлагает выделить диапазон один раз на установку. Выводить источник и допускать проверяемое ручное значение. [Разрешение идентификаторов OSPF](../backend/src/services/ospf-identity-catalog.ts).
|
||||
* Предложение в браузере предварительное. При сохранении атомарно занять ID в PostgreSQL с уникальностью по домену и ID, затем проверить актуальные данные перед применением. Повтор той же операции сохраняет ID. Параллельный запрос получает другой свободный адрес или явный конфликт ручного значения. При неполном инвентаре показывать возраст и неопределённость, разрешать сохранить черновик. Для изменения работающего ID вывести предупреждение о перезапуске BGP-сессии. Резервации освобождаются после проверенного удаления, незавершённая запись резерв удерживает.
|
||||
|
||||
## Изменения в архитектуре
|
||||
|
||||
1. **Контракт и хранение.** Расширить модель сегмента стабильными идентификаторами клиентских подключений, профилей, выходов и межузловых связей. На старте использовать существующие ревизии и эксплуатационные блокировки. Уникальные ресурсы узла (Router ID, адреса туннеля, слушающие порты) резервировать атомарно. Новые поля и миграция совместимы с уже применёнными конфигурациями. Старые привязки проецируются в карточки с исходными именами, владельцем, правами и статусом “настройка из прежней версии”. Отсутствующие данные отмечаются. Переход к новой ACL выполняется через обозримый diff. [Контракты](../packages/contracts/src/internet-exchange.ts), [хранилище ревизий](../backend/src/services/internet-exchange-store.ts).
|
||||
2. **Один сценарий изменения.** WebUI вызывает REST, MCP — зарегистрированные инструменты с его обычными разрешениями. Оба канала используют общую службу планирования и исполнения. Она вычисляет желаемую конфигурацию, зависимости, diff по каждому устройству, проверяет права, состояние и ревизии, применяет и перечитывает объекты. Для секрета — отдельная выдача после успеха. Существующие клиенты REST/MCP сохраняют свои контракты. [IX REST](../backend/src/routes/internet-exchange.ts), [IX MCP](../backend/src/modules/mcp/internet-exchange-actions.ts), [права](../backend/src/lib/permissions.ts).
|
||||
3. **Несколько устройств.** Готовить удалённый конец и обратный маршрут, затем включать пересылку от клиента последним шагом. Для промежуточной ошибки сохранять статусы каждого устройства, исходные значения и владельцев объекта. Повтор перечитывает уже выполненные шаги. При неизвестном результате интерфейс предлагает сверку и продолжение или возврат по проверенному плану. Кнопки должны показывать “Частично применено” и “Требует сверки”. Удаление клиента снимает только принадлежащие ему объекты и ключи, общий выход живёт до последней зависимости.
|
||||
4. **Границы масштаба.** Сейчас контракт допускает до двух площадок на сегмент и до 20 интерфейсов на площадку. Двадцать Linux-клиентов плюс uplink уже выходят за вторую границу при отдельном интерфейсе на клиента. Развести перечни клиентов и площадок, пагинировать каталог, пересмотреть привязанное к интерфейсам ограничение и измерить план/применение по изменённым объектам. Межузловая связь с другим IX или ExitNode имеет собственные два конца и может связывать существующие сегменты. Один общий WireGuard-интерфейс допустим для совместимых политик после проверки изоляции по ключам и адресам.
|
||||
|
||||
## Очерёдность и условия приёмки
|
||||
|
||||
| Этап | Что получит оператор | Чем подтвердим |
|
||||
| --- | --- | --- |
|
||||
| **1. Узел** | Понятная навигация, реальные интерфейсы, автозаполнение Router ID и карта занятых ресурсов. | Стенд показывает `ether1`, WG и GRE. Занятый WAN помечен с причиной. Проверить смену CHR при незавершённом запросе, отказ REST, коллизию двух параллельных выдач, сохранение Router ID после перезапуска. |
|
||||
| **2. Клиент и права** | Добавление Linux, выпуск WG и GRE/IPsec из формы, выдача/ротация/отзыв, отдельные поля доступа и маршрута. | Установить пакет, скачанный из WebUI, на Linux. Проверить реальные пакеты в обе стороны, закрытый GRE при потере SA, подмену источника и чужой префикс, запрет административных сервисов, отзыв только одного из двух клиентов. Проверить права read-only и отсутствие секретов в планах и логах. |
|
||||
| **3. Выходы и BGP** | Локальный выход, выход через вторую IX или ExitNode, смена профиля, рекурсивный резерв и объяснение пути. | Две тестовые CHR 7.24.5 плюс Linux и тестовый получатель. CHR A работает как IX, CHR B последовательно играет роли второго IX и ExitNode. Проверить каждый путь в обе стороны, внешний адрес у получателя, BGP IPv4/IPv6, переключение и возврат основного пути, отказ всех путей, отсутствие утечек в `main`, отдельные выходы для двух клиентов и изолированный режим. Для одноинтерфейсного варианта непрерывно проверять доступ к управлению CHR. |
|
||||
| **4. Совместимость и выпуск** | Старые сегменты открываются, REST и MCP показывают одно состояние. Обновлено руководство по карточке клиента. | На копии старой PostgreSQL проверить миграцию, профиль записи и ревизии. Прогнать повтор/конкуренцию/частичный сбой двух устройств, клиента из старой ревизии, 20+ клиентов с uplink, внешний путь после перезагрузки Linux. Перед тестом независимо подтвердить изолированные устройства, чтобы совпадение IP с рабочим инвентарём не привело к записи в продакшен. |
|
||||
|
||||
Стенд должен раздельно зафиксировать **конфигурацию перечитали**, **туннель поднялся**, **маршрут выбран** и **пакет дошёл и вернулся**. Для каждого транспорта и семейства сохраняются источник, назначение, активный путь, счётчики, наблюдаемый исходящий адрес и результат до, во время и после отказа. Опорные сценарии — [REST WebUI](../backend/scripts/acceptance/ix-web-rest.mts), [две CHR](../backend/scripts/acceptance/ix-two-chr.mts), [GRE и MCP](../backend/scripts/acceptance/ix-gre-mcp.mts). Практическим критерием приёмки служит выдача доступа и смена выхода одного VPS из его карточки, с проверенным результатом и работающим соседним клиентом.
|
||||
+21
-6
@@ -1,10 +1,10 @@
|
||||
# Точки обмена трафиком
|
||||
|
||||
В **Управление → Точки обмена трафиком** оператор создаёт сегмент на сервере типа **IX Node**, сохраняет конфигурацию и подготавливает план через существующее подключение MCP. План отображается в **Планы и операции** и проходит штатное подтверждение. Сохранение черновика не выполняет записи на маршрутизаторах.
|
||||
В **Управление → Точки обмена трафиком** выберите транзитный IX Node, сохраните сегмент и примените план из WebUI. Черновик хранится в PostgreSQL. Запись на CHR начинается после подтверждения плана. MCP использует общий механизм применения и доступен для отдельного управления.
|
||||
|
||||
## Конфигурация сегмента
|
||||
|
||||
- **Площадка** указывает ID выделенной CHR, её локальный ASN и Router ID. Для одного сегмента можно указать до двух площадок.
|
||||
- **Площадка** указывает CHR, локальный ASN и Router ID. Для новой площадки предлагается свободный Router ID из `10.255.0.0/16`. Другой пул можно задать через `MMAPP_IX_ROUTER_ID_POOL`. При повторном открытии отображается сохранённый ID. Ручное значение можно указать в форме. Для одного сегмента можно указать до двух площадок.
|
||||
- **Интерфейс** связывает площадку с WireGuard, GRE/IPsec или выделенным uplink. Для подготовленного вручную интерфейса задайте комментарий `IX:<имя сегмента>`. Интерфейс не должен принадлежать другой VRF или обслуживать статический маршрут в `main`.
|
||||
- **Группа шлюзов** содержит служебный адрес, основной путь с интерфейсом, непосредственно достижимым шлюзом и контрольным адресом. У резерва другой интерфейс и своя проба. `onFailure` выбирает `block` или `segment-exit`.
|
||||
- **BGP-сосед** привязан к интерфейсу площадки. Для публичного фида правила сопоставляют community с группой. Для частного соседа задаются группа и диапазоны, принадлежащие этому подключению. По умолчанию импорт и экспорт отклоняются, если правило не совпало.
|
||||
@@ -55,10 +55,23 @@
|
||||
|
||||
### Доступ конечных Linux-серверов
|
||||
|
||||
На нужной площадке добавьте по одному подключению на сервер. В поле «Удалённый узел» выберите «Внешний сервер». Сохраните черновик, просмотрите изменения и примените их через WebUI. Во вкладке «Linux-клиенты» скачайте конфигурацию конкретного подключения из применённой ревизии.
|
||||
1. Откройте сегмент IX и нажмите **Подключить Linux**. Выберите транспорт и выход VPS. **Только разрешённые сети** направляет в туннель выбранные префиксы, **Интернет с этого IX** выводит трафик через его WAN. Для удалённого выхода выберите конкретный ExitNode или другой IX. Менеджер использует подходящий настроенный выход либо подготовит транзит вместе с клиентом.
|
||||
2. Нажмите **Сохранить**. В окне подтверждения проверьте узлы и изменения RouterOS, затем нажмите **Подтвердить**. Кнопка **Конфиг Linux** в строке клиента выдаёт файлы из применённой ревизии. Отмена до подтверждения оставляет изменения в черновике. Его можно открыть той же кнопкой **Сохранить**.
|
||||
3. В строке клиента нажмите на название выхода, чтобы сменить маршрут или приостановить доступ. В меню действий **Проверить путь** показывает фактический шлюз, а **Отозвать доступ** удаляет клиентское подключение после подтверждения. Во вкладке **Маршрутизация** можно настроить общие выходы и резерв, интерфейсы CHR, статические маршруты и BGP.
|
||||
|
||||
- **WireGuard.** Создайте пару ключей на Linux и внесите в форму публичный ключ. Включите создание интерфейса и пира. Укажите порт, адреса туннеля, внешний адрес IX и префиксы за клиентом. Шаблон `wg-quick` использует `Table = off`. Добавьте на Linux нужные маршруты или настройте BGP по параметрам из карточки.
|
||||
- **GRE/IPsec.** Подготовьте на узле выделенный GRE с отключённым FastPath и обязательной политикой IKEv2/IPsec в транспортном режиме. Задайте оба фиксированных внешних IPv4-адреса в IX. Скачайте шаблон strongSwan, согласуйте предложения и идентификаторы IKE с узлом, подставьте отдельный PSK клиента. После установки IPsec поднимите GRE по командам из вкладки. При использовании статической маршрутизации назначьте согласованный адрес внутри туннеля и добавьте нужные маршруты.
|
||||
- **WireGuard.** IX автоматически создаёт пару ключей Linux. После применения скачайте готовый `.conf` из карточки клиента, сохраните под исходным именем в `/etc/wireguard/` с правами `0600` и запустите `sudo wg-quick up <имя-файла-без-.conf>`. Указанный внешний IP Linux сохраняет исходный путь управления при полном туннеле. Для клиента со своей парой ключей доступен шаблон с полем для его приватного ключа.
|
||||
- **Получение WireGuard через MCP.** Вызовите `mm_wireguard_export_plan` с полями `serverId`, `interfaceName` клиента, `ixSegmentId` и `format: "peer-conf"`. После подтверждения и выполнения плана ссылка на готовый файл доступна авторизованному владельцу подключения 15 минут. Ключ находится только в скачиваемом файле.
|
||||
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. Менеджер создаёт на CHR GRE с выключенным FastPath и IKEv2/IPsec в транспортном режиме. Оператор с правами записи скачивает конфиг strongSwan с индивидуальным PSK и команды настройки Linux. Старые вручную подготовленные подключения остаются доступны по прежнему шаблону.
|
||||
|
||||
### Выход и резерв
|
||||
|
||||
**Интернет с этого IX** использует действующий WAN из `main`. WAN остаётся в своей таблице, для клиента на этом выходе добавляются отдельные правила и обратный маршрут. **Добавить удалённый выход** готовит оба конца межузлового WireGuard с возвратом и IPv4 SNAT на целевом IX или ExitNode. Такой выход доступен в карточке клиента как группа шлюзов. В конфигурации группы можно выбрать другой интерфейс резерва или взять параметры заранее подготовленного выхода.
|
||||
|
||||
При выборе **Только разрешённые сети** клиенту открываются согласованные префиксы, которые маршрутизируются внутри IX. **Проверить путь** показывает FIB и активный next hop. Доступность назначения и фактический внешний адрес проверяйте с Linux.
|
||||
|
||||
Если операция оборвалась после записи части объектов, нажмите **Сохранить** для текущей ревизии. Если обычное сравнение выявит частично применённые изменения, выберите в окне **Сверить и продолжить**. Менеджер проверяет запись о предыдущей попытке и адресатов, перечитывает CHR и предлагает план оставшихся изменений.
|
||||
|
||||
До автоматической выдачи ключей на изолированном стенде с двумя CHR RouterOS 7.24.5 проверены WireGuard и GRE/IKEv2, IPv4 TCP на локальных выходах и блокировка открытого GRE после снятия IPsec. Для выхода через ExitNode получатель увидел смену WAN второй CHR на WAN первой и обратно после восстановления туннеля. В роли второго IX та же пара передала IPv6 с сохранением адреса Linux. Стендовый BGP-анонс выбран через заданный шлюз, после отзыва активировался защитный маршрут отбрасывания. Автоматическая выдача WireGuard проверена через REST и MCP с временной PostgreSQL и имитацией RouterOS.
|
||||
|
||||
### Удаление сегмента
|
||||
|
||||
@@ -66,7 +79,9 @@
|
||||
|
||||
## MCP и ввод в эксплуатацию
|
||||
|
||||
`mm_ix_segments_list` и `mm_ix_segment_get` читают конфигурацию и наблюдения в разрешённой области. `mm_ix_change_plan` готовит изменение, `mm_ix_restore_plan` готовит восстановление сохранённой ревизии. Применение, сверка и журнал общие с остальными функциями MCP.
|
||||
`mm_ix_segments_list` и `mm_ix_segment_get` читают конфигурацию и наблюдения в разрешённой области. `mm_ix_inventory_get` читает интерфейсы узла, `mm_ix_linux_path_get` показывает маршруты клиента. `mm_ix_change_plan` готовит изменение, `mm_ix_restore_plan` готовит восстановление сохранённой ревизии. Применение, сверка и журнал общие с остальными функциями MCP.
|
||||
|
||||
Перед запуском стендовых сценариев SSH задайте `MMAPP_IX_CHR_HOSTS` двумя IPv4-адресами выделенной пары и проверьте, что они отсутствуют в рабочем инвентаре.
|
||||
|
||||
Перед запуском backend оператор применяет миграцию `0058_internet_exchange.sql` штатной подготовкой базы. Для подписанного PostgreSQL-профиля используется **source59**. Он добавляет в каталог три таблицы IX, сохраняет профиль source58 как точного предшественника и связывает новый профиль с хешем миграций.
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { isTrafficLiveSample } from "@/hooks/use-traffic-live"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export interface GreTrafficTarget {
|
||||
edgeId: string
|
||||
serverId: string
|
||||
iface: string
|
||||
}
|
||||
|
||||
type Rate = { bps: number; bpsFwd: number; bpsRev: number; receivedAt: number }
|
||||
const MAX_CONCURRENT_READS = 4
|
||||
const REFRESH_MS = 8_000
|
||||
const MAX_SAMPLE_AGE_MS = 30_000
|
||||
|
||||
export function useMapGreTraffic(backendUrl: string, targets: GreTrafficTarget[]) {
|
||||
const key = JSON.stringify(targets)
|
||||
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
|
||||
|
||||
useEffect(() => {
|
||||
const scope: GreTrafficTarget[] = JSON.parse(key)
|
||||
if (!scope.length) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const run = async () => {
|
||||
if (document.hidden) {
|
||||
timer = setTimeout(run, REFRESH_MS)
|
||||
return
|
||||
}
|
||||
for (let offset = 0; offset < scope.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
|
||||
const batch = await Promise.all(scope.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ edgeId, serverId, iface }) => {
|
||||
try {
|
||||
const query = new URLSearchParams({ iface, once: "1" })
|
||||
const sample = await requestJson<unknown>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(6_000)]),
|
||||
cache: "no-store",
|
||||
})
|
||||
if (isTrafficLiveSample(sample)) {
|
||||
const bpsFwd = sample.rxMbps * 1_000_000
|
||||
const bpsRev = sample.txMbps * 1_000_000
|
||||
return { edgeId, rate: { bps: bpsFwd + bpsRev, bpsFwd, bpsRev, receivedAt: Date.now() } }
|
||||
}
|
||||
} catch {
|
||||
// One unavailable interface cannot hide readings on other links.
|
||||
}
|
||||
return { edgeId }
|
||||
}))
|
||||
if (controller.signal.aborted) return
|
||||
setSnapshot(previous => {
|
||||
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
|
||||
for (const { edgeId, rate } of batch) {
|
||||
if (rate) rates.set(edgeId, rate)
|
||||
else rates.delete(edgeId)
|
||||
}
|
||||
return { backendUrl, key, rates }
|
||||
})
|
||||
}
|
||||
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
|
||||
}
|
||||
void run()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [backendUrl, key])
|
||||
|
||||
return (edgeId: string) => {
|
||||
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
|
||||
return rate && Date.now() - rate.receivedAt <= MAX_SAMPLE_AGE_MS ? rate : undefined
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,14 @@ export interface TrafficLiveSample {
|
||||
timestampKind?: "backend-receipt"
|
||||
}
|
||||
|
||||
export function isTrafficLiveSample(value: unknown): value is TrafficLiveSample {
|
||||
const sample = value as Partial<TrafficLiveSample> | null
|
||||
return !!sample && typeof sample.rxMbps === "number" && Number.isFinite(sample.rxMbps) && sample.rxMbps >= 0 &&
|
||||
typeof sample.txMbps === "number" && Number.isFinite(sample.txMbps) && sample.txMbps >= 0 &&
|
||||
typeof sample.at === "string" && Number.isFinite(Date.parse(sample.at)) &&
|
||||
(sample.timestampKind === undefined || sample.timestampKind === "backend-receipt")
|
||||
}
|
||||
|
||||
function parseSseBlock(block: string): { event: string; data: string } {
|
||||
let event = "message"
|
||||
const dataLines: string[] = []
|
||||
@@ -90,8 +98,8 @@ export function useTrafficLive(opts: {
|
||||
if (!raw.trim()) continue
|
||||
const ev = parseSseBlock(raw)
|
||||
if (ev.event === "sample" && ev.data) {
|
||||
const parsed = JSON.parse(ev.data) as TrafficLiveSample
|
||||
if (!parsed || !Number.isFinite(parsed.rxMbps) || !Number.isFinite(parsed.txMbps) || parsed.rxMbps < 0 || parsed.txMbps < 0 || typeof parsed.at !== "string" || !Number.isFinite(Date.parse(parsed.at)) || parsed.timestampKind !== undefined && parsed.timestampKind !== "backend-receipt") {
|
||||
const parsed: unknown = JSON.parse(ev.data)
|
||||
if (!isTrafficLiveSample(parsed)) {
|
||||
throw new Error("Некорректные данные live-потока")
|
||||
}
|
||||
awaitSample()
|
||||
|
||||
+20
-20
@@ -8,6 +8,10 @@ export interface MatchedNetflowHop {
|
||||
bytes: number
|
||||
}
|
||||
|
||||
export interface GreNetflowHop extends MatchedNetflowHop {
|
||||
exactInterface: boolean
|
||||
}
|
||||
|
||||
function ifaceNorm(s: string | undefined): string {
|
||||
return (s ?? "").trim().toLowerCase()
|
||||
}
|
||||
@@ -40,45 +44,41 @@ export function hopHasRate(h: MatchedNetflowHop | undefined): h is MatchedNetflo
|
||||
return h != null && Number.isFinite(h.bps) && h.bps > 0
|
||||
}
|
||||
|
||||
export function formatNetflowRate(hop: MatchedNetflowHop): string {
|
||||
export function formatNetflowRate<T extends Pick<MatchedNetflowHop, "bps">>(hop: T): string {
|
||||
return fmtRate(hop.bps / 1_000_000)
|
||||
}
|
||||
|
||||
export function formatNetflowDir(hop: MatchedNetflowHop): string {
|
||||
export function formatNetflowDir(hop: Pick<MatchedNetflowHop, "bpsFwd" | "bpsRev">): string {
|
||||
return `↓${fmtRate(hop.bpsFwd / 1_000_000)} ↑${fmtRate(hop.bpsRev / 1_000_000)}`
|
||||
}
|
||||
|
||||
/** GRE: сначала имя интерфейса туннеля на любом конце, иначе пара узлов. */
|
||||
/** Собственный интерфейс GRE даёт точную привязку, совпадение пары узлов — только оценку. */
|
||||
export function matchNetflowForGreEdge(
|
||||
edge: {
|
||||
tunnel: { name: string }
|
||||
tunnel: { name: string; serverId: string }
|
||||
fromServer: { id: string }
|
||||
toServer: { id: string }
|
||||
},
|
||||
hops: FlowMapHop[],
|
||||
): MatchedNetflowHop | undefined {
|
||||
): GreNetflowHop | undefined {
|
||||
const name = ifaceNorm(edge.tunnel.name)
|
||||
const fromId = String(edge.fromServer.id)
|
||||
const toId = String(edge.toServer.id)
|
||||
if (name) {
|
||||
const ifaceHits = hops.filter((h) =>
|
||||
h.kind === "iface"
|
||||
&& ifaceNorm(h.iface) === name
|
||||
&& (h.fromId === fromId || h.fromId === toId),
|
||||
)
|
||||
if (ifaceHits.length) return mergeDirected(ifaceHits, fromId)
|
||||
const greNamed = hops.filter((h) =>
|
||||
h.kind === "gre"
|
||||
&& ifaceNorm(h.iface) === name
|
||||
&& (h.fromId === fromId || h.fromId === toId || h.toId === fromId || h.toId === toId),
|
||||
)
|
||||
if (greNamed.length) return mergeDirected(greNamed, fromId)
|
||||
}
|
||||
const ownerId = edge.tunnel.serverId
|
||||
const peerId = ownerId === fromId ? toId : fromId
|
||||
const want = pairKey(fromId, toId)
|
||||
if (name) {
|
||||
const local = hops.filter((h) => h.kind === "iface" && h.fromId === ownerId && ifaceNorm(h.iface) === name)
|
||||
if (local.length) return { ...mergeDirected(local, fromId), exactInterface: true }
|
||||
const named = hops.filter((h) =>
|
||||
h.kind === "gre" && h.fromId === ownerId && h.toId === peerId && ifaceNorm(h.iface) === name,
|
||||
)
|
||||
if (named.length) return { ...mergeDirected(named, fromId), exactInterface: true }
|
||||
}
|
||||
const pairHits = hops.filter((h) =>
|
||||
h.kind === "gre" && Boolean(h.toId) && pairKey(h.fromId, h.toId) === want,
|
||||
)
|
||||
if (pairHits.length) return mergeDirected(pairHits, fromId)
|
||||
if (pairHits.length) return { ...mergeDirected(pairHits, fromId), exactInterface: false }
|
||||
return undefined
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ const path = z.object({
|
||||
interface: interfaceName,
|
||||
nextHop: address,
|
||||
probe: address,
|
||||
viaMain: z.boolean().optional(),
|
||||
}).strict()
|
||||
|
||||
const group = z.object({
|
||||
@@ -26,6 +27,7 @@ const group = z.object({
|
||||
|
||||
const wireguardProvision = z.object({
|
||||
peerPublicKey: z.string().regex(/^[A-Za-z0-9+/]{43}=$/),
|
||||
credentialId: z.string().uuid().optional(),
|
||||
listenPort: z.number().int().min(1).max(65535),
|
||||
localAddress: prefix,
|
||||
peerAddress: address,
|
||||
@@ -33,6 +35,31 @@ const wireguardProvision = z.object({
|
||||
endpointPort: z.number().int().min(1).max(65535).optional(),
|
||||
}).strict()
|
||||
|
||||
const greProvision = z.object({
|
||||
localAddress: prefix,
|
||||
peerAddress: address,
|
||||
credentialId: z.string().uuid(),
|
||||
}).strict()
|
||||
|
||||
const linuxPolicy = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
enabled: z.boolean(),
|
||||
destinations: z.array(prefix).max(64),
|
||||
exit: key.optional(),
|
||||
peerEndpoint: address.optional(),
|
||||
}).strict()
|
||||
|
||||
const transitProvision = z.object({
|
||||
localEndpoint: z.ipv4(),
|
||||
remoteEndpoint: z.ipv4(),
|
||||
localAddress: prefix,
|
||||
remoteAddress: address,
|
||||
localPort: wireguardProvision.shape.listenPort,
|
||||
remotePort: wireguardProvision.shape.listenPort,
|
||||
remoteWan: path,
|
||||
credentialId: z.string().uuid(),
|
||||
}).strict()
|
||||
|
||||
const interfaceBinding = z.object({
|
||||
name: interfaceName,
|
||||
kind: z.enum(["wireguard", "gre-ipsec", "uplink"]),
|
||||
@@ -41,6 +68,9 @@ const interfaceBinding = z.object({
|
||||
endpoint: address.optional(),
|
||||
natIpv4: z.boolean().optional(),
|
||||
provisionWireguard: wireguardProvision.optional(),
|
||||
provisionGre: greProvision.optional(),
|
||||
provisionTransit: transitProvision.optional(),
|
||||
linux: linuxPolicy.optional(),
|
||||
prefixes: z.array(prefix).max(128).default([]),
|
||||
}).strict()
|
||||
|
||||
@@ -67,7 +97,8 @@ const site = z.object({
|
||||
serverId,
|
||||
autonomousSystem: asn,
|
||||
routerId: z.ipv4(),
|
||||
interfaces: z.array(interfaceBinding).max(20).default([]),
|
||||
autoRouterId: z.boolean().optional(),
|
||||
interfaces: z.array(interfaceBinding).max(80).default([]),
|
||||
groups: z.array(group).max(24).default([]),
|
||||
exits: z.array(key).max(2).default([]),
|
||||
routes: z.array(z.object({ prefix, group: key }).strict()).max(250).default([]),
|
||||
@@ -92,6 +123,59 @@ export type IxSite = z.infer<typeof site>
|
||||
export type IxConfiguration = z.infer<typeof ixSegmentConfigurationSchema>
|
||||
export type IxChange = z.infer<typeof ixChangeSchema>
|
||||
|
||||
const ixTransitOptions = z.object({
|
||||
targetServerId: serverId,
|
||||
name: key,
|
||||
localEndpoint: z.ipv4(),
|
||||
remoteEndpoint: z.ipv4(),
|
||||
family: z.union([z.literal(4), z.literal(6)]).default(4),
|
||||
probe: address.optional(),
|
||||
}).strict()
|
||||
|
||||
export const ixLinuxClientRequest = z.object({
|
||||
revision: z.number().int().positive(),
|
||||
serverId,
|
||||
interfaceName: interfaceName.optional(),
|
||||
name: linuxPolicy.shape.name,
|
||||
enabled: z.boolean().default(true),
|
||||
kind: z.enum(["wireguard", "gre-ipsec"]),
|
||||
hubEndpoint: address,
|
||||
peerEndpoint: address.optional(),
|
||||
peerPublicKey: wireguardProvision.shape.peerPublicKey.optional(),
|
||||
localAddress: prefix.optional(),
|
||||
peerAddress: address.optional(),
|
||||
prefixes: z.array(prefix).max(64).default([]),
|
||||
destinations: linuxPolicy.shape.destinations.default([]),
|
||||
exit: key.optional(),
|
||||
transit: ixTransitOptions.optional(),
|
||||
rotate: z.boolean().optional(),
|
||||
}).strict().refine(input => !input.transit || !input.exit || input.exit === input.transit.name,
|
||||
{ path: ["exit"], message: "Выход клиента должен совпадать с выбранным транзитом" })
|
||||
|
||||
export type IxLinuxClientRequest = z.infer<typeof ixLinuxClientRequest>
|
||||
|
||||
export const ixTransitRequest = ixTransitOptions.extend({
|
||||
revision: z.number().int().positive(),
|
||||
serverId,
|
||||
})
|
||||
|
||||
export type IxTransitRequest = z.infer<typeof ixTransitRequest>
|
||||
|
||||
export interface IxNodeInventory {
|
||||
observedAt: string
|
||||
routerId: string | null
|
||||
interfaces: Array<{
|
||||
name: string
|
||||
type: string
|
||||
running: boolean
|
||||
disabled: boolean
|
||||
addresses: string[]
|
||||
restriction: string | null
|
||||
}>
|
||||
wireguardPorts: number[]
|
||||
defaultRoutes: Array<{ family: 4 | 6; gateway: string; interface: string }>
|
||||
}
|
||||
|
||||
export interface IxSegment {
|
||||
id: string
|
||||
revision: number
|
||||
@@ -109,6 +193,7 @@ export interface IxRouterObject {
|
||||
export interface IxWebPlan {
|
||||
revision: number
|
||||
digest: string
|
||||
resume?: boolean
|
||||
changes: Array<IxRouterObject & { action: "create" | "update" | "delete"; target?: string; placeBefore?: string }>
|
||||
}
|
||||
|
||||
@@ -116,6 +201,11 @@ export interface IxLinuxBinding {
|
||||
serverId: number
|
||||
interfaceName: string
|
||||
kind: "wireguard" | "gre-ipsec"
|
||||
name?: string
|
||||
managedWireguard?: boolean
|
||||
enabled?: boolean
|
||||
policy?: IxSite["interfaces"][number]["linux"]
|
||||
connection?: { state: "connected" | "waiting" | "unknown"; observedAt: string; rx?: string; tx?: string }
|
||||
}
|
||||
|
||||
export interface IxLinuxAccess {
|
||||
@@ -139,3 +229,10 @@ export interface IxSiteObservation {
|
||||
routes: Array<{ prefix: string; gateway: string; immediateGateway: string | null; active: boolean }>
|
||||
neighbors: Array<{ name: string; established: boolean }>
|
||||
}
|
||||
|
||||
export interface IxLinuxPath {
|
||||
observedAt: string
|
||||
table: string
|
||||
policy: string | null
|
||||
routes: IxSiteObservation["routes"]
|
||||
}
|
||||
+153
-17
@@ -1,3 +1,4 @@
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { expect, test } from "@playwright/test"
|
||||
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
|
||||
@@ -24,6 +25,8 @@ test("IX: редактирование и применение сохранён
|
||||
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 (/\/api\/ix\/nodes\/\d+\/inventory$/.test(path)) return json({ observedAt, routerId: "10.255.0.1", defaultRoutes: [], wireguardPorts: [],
|
||||
interfaces: [{ name: "wg-member", type: "wg", running: true, disabled: false, addresses: [], restriction: null }] })
|
||||
if (path.startsWith("/api/mcp/")) {
|
||||
mcpCalls.push(path)
|
||||
return route.fulfill({ status: 503, json: { error: "MCP недоступен" } })
|
||||
@@ -78,24 +81,30 @@ test("IX: редактирование и применение сохранён
|
||||
await expect(page.getByRole("heading", { name: "ix-central" })).toBeFocused()
|
||||
await page.screenshot({ path: testInfo.outputPath("ix-detail-desktop.png"), animations: "disabled" })
|
||||
|
||||
await expect(page.getByRole("tab", { name: "Linux-клиенты" })).toHaveAttribute("aria-selected", "true")
|
||||
await expect(page.getByRole("tab", { name: "План изменений" })).toHaveCount(0)
|
||||
await page.setViewportSize({ width: 390, height: 760 })
|
||||
await page.getByRole("tab", { name: "Маршрутизация" }).click()
|
||||
await page.getByLabel("Локальный ASN", { exact: true }).first().fill("64513")
|
||||
await page.getByText("Подключения · 1", { exact: true }).click()
|
||||
await page.getByRole("button", { name: "wg-member", exact: true }).click()
|
||||
await page.getByLabel("Префиксы подключения").fill("2001:db8:120::/48")
|
||||
await page.getByText("Группы шлюзов · 0", { exact: true }).first().click()
|
||||
await page.getByRole("button", { name: "Добавить группу шлюзов" }).click()
|
||||
await page.getByRole("button", { name: "Добавить группу шлюзов" }).first().click()
|
||||
await page.getByLabel("Имя группы шлюзов").fill("member")
|
||||
await page.getByLabel("Служебный адрес шлюза").fill("2001:db8:ff::1")
|
||||
await page.getByLabel("Адрес следующего шлюза").fill("2001:db8::2")
|
||||
await page.getByLabel("Контрольный адрес").fill("2001:db8::2")
|
||||
await page.getByText("Статические маршруты · 0", { exact: true }).first().click()
|
||||
await page.getByRole("button", { name: "Добавить маршрут" }).click()
|
||||
await page.getByRole("button", { name: "Добавить маршрут" }).first().click()
|
||||
await page.getByLabel("Префикс маршрута").fill("2001:db8:120::/48")
|
||||
const save = page.getByRole("button", { name: "Сохранить черновик" })
|
||||
const save = page.getByRole("button", { name: "Сохранить", exact: true })
|
||||
await save.scrollIntoViewIfNeeded()
|
||||
await expect(save).toBeInViewport()
|
||||
await save.click()
|
||||
await expect(page.getByText("Черновик сохранён")).toBeVisible()
|
||||
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
|
||||
await expect(dialog).toBeVisible()
|
||||
expect(applies).toBe(0)
|
||||
await dialog.getByRole("button", { name: "Отмена" }).click()
|
||||
await expect(page.getByText(/Изменения сохранены в черновике/)).toBeVisible()
|
||||
expect(applies).toBe(0)
|
||||
expect(segment.configuration.sites[0]).toMatchObject({
|
||||
autonomousSystem: 64513,
|
||||
interfaces: [{ name: "wg-member", prefixes: ["2001:db8:120::/48"] }],
|
||||
@@ -104,17 +113,12 @@ test("IX: редактирование и применение сохранён
|
||||
})
|
||||
expect(segment.configuration.sites[1]).toEqual(configuration.sites[1])
|
||||
|
||||
await page.getByRole("tab", { name: "Маршруты и BGP" }).click()
|
||||
await expect(page.getByText("2001:db8:120::/48")).toBeVisible()
|
||||
await expect(page.getByText("BGP 1 из 1")).toBeVisible()
|
||||
await page.getByRole("tab", { name: "План изменений" }).click()
|
||||
await page.getByRole("button", { name: "Построить предпросмотр" }).click()
|
||||
await expect(page.getByText("Ревизия 2 · операций RouterOS: 1")).toBeVisible()
|
||||
await expect(page.getByText("/ipv6/route", { exact: true })).toBeVisible()
|
||||
await page.getByRole("button", { name: "Применить план" }).click()
|
||||
await expect(page.getByRole("alertdialog")).toBeVisible()
|
||||
await save.click()
|
||||
await expect(dialog.getByText("/ipv6/route", { exact: true })).toBeVisible()
|
||||
expect(segment.revision).toBe(2)
|
||||
expect(applies).toBe(0)
|
||||
await page.getByRole("button", { name: "Применить", exact: true }).click()
|
||||
await dialog.getByRole("button", { name: "Подтвердить", exact: true }).click()
|
||||
await expect(page.getByText("Конфигурация IX применена")).toBeVisible()
|
||||
expect(segment.appliedRevision).toBe(3)
|
||||
expect(applies).toBe(1)
|
||||
@@ -122,7 +126,7 @@ test("IX: редактирование и применение сохранён
|
||||
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()
|
||||
await page.getByRole("button", { 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()
|
||||
@@ -169,3 +173,135 @@ test("IX: черновик удаляется после подтвержден
|
||||
await expect(page.getByText("Нет сегментов IX")).toBeVisible()
|
||||
expect(deleted).toBe(true)
|
||||
})
|
||||
|
||||
test("IX: новый сегмент сохраняется одним подтверждением, ошибки сравнения можно исправить", async ({ page }) => {
|
||||
let stores = 0, applies = 0
|
||||
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-new", sites: [
|
||||
{ serverId: 1, autonomousSystem: 64512, routerId: "10.255.0.5", autoRouterId: true },
|
||||
] })
|
||||
const segment = { id, revision: 1, appliedRevision: null, configuration, updatedAt: observedAt }
|
||||
const digest = "d".repeat(64)
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", async route => {
|
||||
const req = route.request(), path = new URL(req.url()).pathname
|
||||
const json = (body: unknown) => route.fulfill({ json: body })
|
||||
if (path === "/api/auth/config") return json({ required: false })
|
||||
if (path === "/api/ix/nodes") return json({ items: [nodes[0]] })
|
||||
if (path === "/api/ix/segments" && req.method() === "POST") {
|
||||
const change = ixChangeSchema.parse(req.postDataJSON())
|
||||
expect(change.configuration.sites[0]).toMatchObject({ serverId: 1, autoRouterId: true })
|
||||
stores++
|
||||
return json({ segment })
|
||||
}
|
||||
if (path === "/api/ix/segments") return json({ items: [] })
|
||||
if (path.endsWith("/plan")) return req.postDataJSON().resume
|
||||
? json({ revision: 1, digest, resume: true, changes: [] })
|
||||
: route.fulfill({ status: 409, json: { error: "Требуется сверка" } })
|
||||
if (path.endsWith("/apply")) {
|
||||
expect(req.postDataJSON()).toEqual({ revision: 1, digest, resume: true })
|
||||
applies++
|
||||
return json({ segment: { ...segment, revision: 2, appliedRevision: 2 } })
|
||||
}
|
||||
return json({ items: [] })
|
||||
})
|
||||
await page.goto("/ix")
|
||||
await page.getByRole("button", { name: "Добавить сегмент" }).click()
|
||||
await page.getByLabel("Имя сегмента").fill("ix-new")
|
||||
await page.getByRole("button", { name: "Сохранить", exact: true }).click()
|
||||
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
|
||||
await expect(dialog.getByText("Требуется сверка")).toBeVisible()
|
||||
await dialog.getByRole("button", { name: "Сверить и продолжить" }).click()
|
||||
await expect(dialog.getByText(/RouterOS уже настроена/)).toBeVisible()
|
||||
expect(applies).toBe(0)
|
||||
await dialog.getByRole("button", { name: "Подтвердить" }).click()
|
||||
await expect(page.getByRole("button", { name: "Подключить Linux" })).toBeVisible()
|
||||
expect(stores).toBe(1)
|
||||
expect(applies).toBe(1)
|
||||
})
|
||||
|
||||
for (const mode of ["WAN IX", "новый ExitNode", "ExitNode с двумя WAN-адресами"]) test("IX: VPS подключается через " + mode, async ({ page }, testInfo) => {
|
||||
const remote = mode !== "WAN IX", manual = mode === "ExitNode с двумя WAN-адресами"
|
||||
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-vps", sites: [
|
||||
{ serverId: 1, autonomousSystem: 64512, routerId: "10.255.0.1", autoRouterId: true },
|
||||
] })
|
||||
let segment = { id, revision: 1, appliedRevision: 1, configuration, updatedAt: observedAt }
|
||||
const digest = "c".repeat(64)
|
||||
let client: { name: string; kind: "wireguard"; serverId: number; interfaceName: string; managedWireguard: boolean } | undefined
|
||||
const configFile = "[Interface]\nPrivateKey = TEST_PRIVATE_KEY\n[Peer]\nAllowedIPs = 0.0.0.0/0\n"
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", async route => {
|
||||
const req = route.request(), url = new URL(req.url()), path = url.pathname
|
||||
const json = (body: unknown) => route.fulfill({ json: body })
|
||||
if (path === "/api/auth/config") return json({ required: false })
|
||||
if (path === "/api/ix/nodes") return json({ items: nodes, peers: [...nodes, { id: 3, name: "exit-arn", type: "exit-node", enabled: true }] })
|
||||
if (path === "/api/ix/nodes/3/inventory") return json({ interfaces: [{ name: "wan", disabled: false, addresses: manual ? ["192.0.2.12/24", "192.0.2.13/24"] : ["192.0.2.13/24"] }],
|
||||
defaultRoutes: [{ family: 4, interface: "wan" }] })
|
||||
if (path === "/api/ix/nodes/1/inventory") return json({ observedAt, routerId: "10.255.0.1", wireguardPorts: [],
|
||||
interfaces: [{ name: "ether1", type: "ether", running: true, disabled: false, addresses: ["192.0.2.11/24"], restriction: "Интерфейс используется в таблице main" }],
|
||||
defaultRoutes: [{ family: 4, gateway: "192.0.2.1", interface: "ether1" }] })
|
||||
if (path === "/api/ix/segments") return json({ items: [segment] })
|
||||
if (path === `/api/ix/segments/${id}/linux` && req.method() === "POST") {
|
||||
expect(req.postDataJSON()).toMatchObject({ name: "vps-01", kind: "wireguard", hubEndpoint: "192.0.2.11",
|
||||
peerEndpoint: "123.123.123.123", ...(remote ? { transit: { targetServerId: 3, localEndpoint: "192.0.2.11", remoteEndpoint: "192.0.2.13", family: 4 } } : { exit: "local-wan" }) })
|
||||
expect(req.postDataJSON()).not.toHaveProperty("peerPublicKey")
|
||||
client = { name: "vps-01", kind: "wireguard", serverId: 1, interfaceName: "il-vps", managedWireguard: true }
|
||||
const exit = remote ? req.postDataJSON().transit.name : "ix-wan4"
|
||||
segment = { ...segment, revision: 2, configuration: ixSegmentConfigurationSchema.parse({
|
||||
...configuration, sites: [{ ...configuration.sites[0], interfaces: [
|
||||
{ name: "il-vps", kind: "wireguard", linux: { name: "vps-01", enabled: true, destinations: [], exit } },
|
||||
...(remote ? [{ name: "it-to-exit", kind: "wireguard", peerServerId: 3 }] : []),
|
||||
], groups: [{ id: exit, gateway: "198.19.253.5", onFailure: "block",
|
||||
primary: { interface: remote ? "it-to-exit" : "ether1", nextHop: "192.0.2.1", probe: "192.0.2.1", viaMain: !remote } }] }],
|
||||
}) }
|
||||
return json({ segment, interfaceName: client.interfaceName })
|
||||
}
|
||||
if (path === `/api/ix/segments/${id}/linux/credential`) {
|
||||
expect(req.method()).toBe("POST")
|
||||
expect(req.postDataJSON()).toEqual({ serverId: 1, interfaceName: "il-vps" })
|
||||
return json({ kind: "wireguard", revision: 3, filename: "vps.conf", template: configFile })
|
||||
}
|
||||
if (path === `/api/ix/segments/${id}/linux`) {
|
||||
return json({ revision: segment.appliedRevision, items: segment.appliedRevision === 3 && client ? [client] : [] })
|
||||
}
|
||||
if (path.endsWith("/plan")) return json({ revision: 2, digest, changes: [{ serverId: 1, action: "create", path: "/interface/wireguard", fields: {} }] })
|
||||
if (path.endsWith("/apply")) {
|
||||
expect(req.postDataJSON()).toEqual({ revision: 2, digest })
|
||||
segment = { ...segment, revision: 3, appliedRevision: 3 }
|
||||
return json({ segment })
|
||||
}
|
||||
expect(path.startsWith("/api/mcp/")).toBe(false)
|
||||
return json({})
|
||||
})
|
||||
await page.goto("/ix")
|
||||
await page.getByRole("button", { name: "ix-vps", exact: true }).click()
|
||||
await expect(page.getByRole("tab", { name: "Linux-клиенты" })).toHaveAttribute("aria-selected", "true")
|
||||
await page.getByRole("button", { name: "Подключить Linux" }).click()
|
||||
await page.getByLabel("Имя клиента").fill("vps-01")
|
||||
await page.getByLabel("Внешний адрес Linux").fill("123.123.123.123")
|
||||
await expect(page.getByLabel("Публичный ключ Linux")).toBeHidden()
|
||||
await page.getByLabel("Выход трафика").click()
|
||||
await page.getByRole("option", { name: remote ? "Через exit-arn · ExitNode" : "Интернет с этого IX" }).click()
|
||||
await expect(page.getByLabel("Внешний адрес IX")).toHaveValue("192.0.2.11")
|
||||
if (remote) await expect(page.getByText(/IX создаст туннель до exit-arn/)).toBeVisible()
|
||||
if (manual) {
|
||||
await expect(page.getByRole("button", { name: "Сохранить", exact: true })).toBeDisabled()
|
||||
await page.getByLabel("IPv4 выходного узла").fill("192.0.2.13")
|
||||
}
|
||||
await page.screenshot({ path: testInfo.outputPath("ix-connect-linux.png"), animations: "disabled" })
|
||||
await page.getByRole("button", { name: "Сохранить", exact: true }).click()
|
||||
await page.getByRole("dialog", { name: "Подтвердите сохранение" }).getByRole("button", { name: "Подтвердить" }).click()
|
||||
const download = page.waitForEvent("download")
|
||||
await page.getByRole("button", { name: "Получить конфиг vps-01" }).click()
|
||||
const file = await download
|
||||
expect(file.suggestedFilename()).toBe("vps.conf")
|
||||
expect(await readFile((await file.path())!, "utf8")).toBe(configFile)
|
||||
await expect(page.getByText("TEST_PRIVATE_KEY")).toHaveCount(0)
|
||||
const editExit = page.getByRole("button", { name: "Доступ и выход клиента vps-01" })
|
||||
await expect(editExit).toContainText(remote ? "Через exit-arn" : "Интернет с этого IX")
|
||||
if (remote) {
|
||||
await editExit.click()
|
||||
await page.getByLabel("Выход трафика").click()
|
||||
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveCount(1)
|
||||
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveAttribute("aria-selected", "true")
|
||||
}
|
||||
})
|
||||
@@ -31,7 +31,7 @@ test("Карта: выбранный GRE обновляется и неизве
|
||||
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
|
||||
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
|
||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
|
||||
|
||||
@@ -3,6 +3,54 @@ const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes
|
||||
const flowPath="/api/traffic/flow/map-hops"
|
||||
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
|
||||
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
|
||||
|
||||
for (const reverse of [false, true]) test(`Карта: GRE без NetFlow своего интерфейса показывает текущие RX/TX RouterOS, reverse=${reverse}`, async ({ page }) => {
|
||||
const exit = { ...server, name: "ARN", type: "exit-node" }
|
||||
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
|
||||
const owner = reverse ? exit : jump
|
||||
const peer = reverse ? jump : exit
|
||||
const tunnel = { id: String(owner.id) + ":*d", serverId: String(owner.id), name: reverse ? "MSK-IHOR" : "SWE-VEESP", enabled: true, status: "up",
|
||||
localAddress: owner.host, remoteAddress: peer.host, localInnerIp: "10.0.0.1", remoteInnerIp: "10.0.0.2",
|
||||
poolId: "", ipsec: { secret: "" }, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit",
|
||||
clampTcpMss: true, allowFastPath: false, comment: "" }
|
||||
const estimate = { fromId: "1", fromLabel: "ARN", toId: "2", toLabel: "MSK-02", kind: "gre", iface: "other-gre",
|
||||
bytes: 300, bps: 8, bpsFwd: 8, bpsRev: 0 }
|
||||
const exact = { fromId: String(owner.id), fromLabel: owner.name, toId: "", toLabel: "", kind: "iface", iface: tunnel.name,
|
||||
bytes: 3_750_000, bps: 100_000, bpsFwd: 100_000, bpsRev: 0 }
|
||||
let exactNetflow = false
|
||||
let liveReads = 0
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
if (/\/traffic\/servers\/\d+\/live$/.test(url.pathname)) {
|
||||
expect(url.pathname).toBe(`/api/traffic/servers/${owner.id}/live`)
|
||||
expect(url.searchParams.get("iface")).toBe(tunnel.name)
|
||||
expect(url.searchParams.get("once")).toBe("1")
|
||||
liveReads++
|
||||
return route.fulfill({ json: { rxMbps: 0.16168, txMbps: 0.119224, at: "2026-11-23T07:20:36Z", timestampKind: "backend-receipt" } })
|
||||
}
|
||||
const json = {
|
||||
"/api/auth/config": { required: false },
|
||||
"/api/servers": [exit, jump],
|
||||
"/api/filters/gre-tunnels": { tunnels: [tunnel], failures: [] },
|
||||
"/api/uptime/speed-probes": { probes: [] },
|
||||
[flowPath]: { ...empty, live: true, hops: [estimate, { ...exact, fromId: String(peer.id), fromLabel: peer.name }, ...(exactNetflow ? [exact] : [])] },
|
||||
}[url.pathname] ?? {}
|
||||
return route.fulfill({ json })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const live = page.getByRole("button", { name: "Текущий трафик GRE " + tunnel.name })
|
||||
await expect(live).toContainText("281 Кбит/с")
|
||||
await expect(live).toContainText("Live GRE")
|
||||
await live.click()
|
||||
await expect(page.getByText("Текущий RX/TX GRE", { exact: true })).toBeVisible()
|
||||
expect(liveReads).toBeGreaterThan(0)
|
||||
|
||||
exactNetflow = true
|
||||
await page.getByRole("button", { name: "Обновить", exact: true }).click()
|
||||
await expect(live).toHaveCount(0)
|
||||
await expect(page.getByRole("button", { name: "Поток NetFlow между узлами" })).toContainText("100 Кбит/с")
|
||||
})
|
||||
|
||||
for(const malformed of [false,true])test("Карта: NetFlow отказ и повтор "+malformed,async({page})=>{
|
||||
let failing=true
|
||||
const recovered=malformed?{...empty,rangeMinutes:2,windowSec:120,sourceWindow:{requestedMinutes:5,effectiveMinutes:2}}:empty
|
||||
|
||||
Reference in new issue
Block a user