Compare commits

...
5 Commits
Author SHA1 Message Date
Denozordec 31f75a8eed feat(ix): включать действующие интерфейсы в группы резервирования
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m40s
Docker images / frontend-image (push) Successful in 3m56s
Docker images / updater-image (push) Successful in 2m38s
Docker images / netflow-agent-image (push) Successful in 33s
Docker images / backend-image (push) Successful in 5m2s
Docker images / publish-release (push) Successful in 11s
Docker images / notify-webhook (push) Successful in 2s
2026-11-24 00:56:00 +07:00
Denozordec 2a759ae5e5 fix(ci): зарегистрировать операции оператора и запускать тесты резервирования
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Canceled after 3m3s
Docker images / backend-image (push) Canceled after 0s
Docker images / frontend-image (push) Canceled after 0s
Docker images / updater-image (push) Canceled after 0s
Docker images / netflow-agent-image (push) Canceled after 0s
Docker images / publish-release (push) Canceled after 0s
Docker images / notify-webhook (push) Canceled after 0s
2026-11-24 00:48:04 +07:00
Denozordec fad89c7059 fix(ci): учесть маршруты групп туннелей в реестре покрытия
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Failing after 4m9s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 4m7s
Docker images / updater-image (push) Successful in 2m15s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
2026-11-24 00:38:57 +07:00
Denozordec 350ae34862 feat(ix): добавить управление группами туннелей для резервирования и балансировки
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Failing after 4m0s
Docker images / backend-image (push) Skipped
Docker images / frontend-image (push) Successful in 3m55s
Docker images / updater-image (push) Successful in 2m11s
Docker images / netflow-agent-image (push) Successful in 37s
Docker images / publish-release (push) Skipped
Docker images / notify-webhook (push) Skipped
2026-11-24 00:29:50 +07:00
Denozordec 676be13251 fix(ix): открыть добавление протокола из формы клиента
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m31s
Docker images / frontend-image (push) Successful in 3m20s
Docker images / updater-image (push) Successful in 1m56s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 3m4s
Docker images / publish-release (push) Successful in 13s
Docker images / notify-webhook (push) Successful in 2s
2026-11-23 21:48:52 +07:00
21 changed files with 1295 additions and 113 deletions

No files matched your search

+208
View File
@@ -0,0 +1,208 @@
"use client"
import { useEffect, useState, type ReactNode } from "react"
import type { IxBondBundle, IxBondCandidate, IxBondCatalog, IxBondEdit, IxBondMode, IxSavedBond, IxSegment } from "@mmapp/contracts/internet-exchange"
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Field, FieldLabel } from "@/components/ui/field"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { requestJson } from "@/shared/api/http-client"
import { nodeLabel, type IxNode } from "./ix-view"
import { IxExistingTransport } from "./ix-existing-transport"
const modes = [
{ value: "failover", label: "Основной и резервные" },
{ value: "equal", label: "Параллельно, поровну" },
{ value: "weighted", label: "Параллельно, по весам" },
] as const
type Member = IxBondEdit["members"][number]
type Ref = Pick<Member, "segmentId" | "interfaceName" | "serverId">
export type IxRowBondAction = (binding: Pick<Ref, "interfaceName" | "serverId">) => { label: string; open: () => void } | undefined
const memberKey = (m: Pick<Member, "segmentId" | "interfaceName" | "serverId">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
const memberRef = ({ segmentId, serverId, appliedRevision, interfaceName }: IxBondCandidate): Member => ({ segmentId, serverId, appliedRevision, interfaceName, weight: 1 })
const modeLabel = (mode: IxBondMode) => modes.find(item => item.value === mode)?.label
export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly, download, live, children }: {
segmentId: string; segments: IxSegment[]; backendUrl: string; nodes: IxNode[]; readOnly: boolean; live: boolean
download: (filename: string, text: string) => void
children: (action: IxRowBondAction, catalog: IxBondCatalog) => ReactNode
}) {
const [catalog, setCatalog] = useState<IxBondCatalog>({ groups: [], candidates: [] })
const [reload, setReload] = useState(0)
const [draft, setDraft] = useState<IxBondEdit | null>(null)
const [direct, setDirect] = useState("")
const [error, setError] = useState("")
const [busy, setBusy] = useState(false)
const [remove, setRemove] = useState(false)
const [confirmedMembers, setConfirmedMembers] = useState("")
const [importing, setImporting] = useState(false)
const [initialInterface, setInitialInterface] = useState<Pick<Ref, "serverId" | "interfaceName">>()
useEffect(() => {
if (!live) return
const ctl = new AbortController()
void requestJson<IxBondCatalog>(backendUrl, "/api/ix/linux-bonds", { signal: ctl.signal })
.then(result => { if (!ctl.signal.aborted) setCatalog(result) })
.catch(e => { if (!ctl.signal.aborted) setError(e.message) })
return () => ctl.abort()
}, [backendUrl, segmentId, reload, live])
const available = new Map(catalog.candidates.map(c => [memberKey(c), c]))
for (const m of [...catalog.groups.flatMap(g => g.members), ...(draft?.members ?? [])]) {
if (!m.existing) continue
const segment = segments.find(s => s.id === m.segmentId)
available.set(memberKey(m), { ...m, ...m.existing, name: m.existing.linuxInterface, segmentName: segment?.configuration.name ?? m.segmentId,
appliedRevision: segment?.appliedRevision ?? m.appliedRevision, destinations: [...new Set(m.existing.destinations)].sort() })
}
const label = (c: IxBondCandidate) => [c.name, c.segmentName, nodeLabel(nodes, c.serverId), c.kind === "wireguard" ? "WG" : "GRE/IPsec", c.endpoint, c.interfaceName].join(" · ")
function open(group?: IxSavedBond, first?: IxBondCandidate) {
setError("")
setRemove(false)
setConfirmedMembers("")
setImporting(false)
setInitialInterface(undefined)
setDirect(group?.directCidrs.join("\n") ?? "")
setDraft(group ? {
id: group.id, revision: group.revision, name: group.name, mode: group.mode, directCidrs: group.directCidrs,
members: group.members.map(m => ({ ...m, appliedRevision: available.get(memberKey(m))?.appliedRevision ?? m.appliedRevision })),
} : { revision: 0, name: first?.name ?? "", mode: "failover", members: first ? [memberRef(first)] : [], directCidrs: [] })
}
async function perform(action: () => Promise<void>) {
if (busy || readOnly) return
setBusy(true)
setError("")
try { await action() } catch (e) { setError(e instanceof Error ? e.message : "Ошибка операции с группой") }
finally { setBusy(false) }
}
const patch = (fields: Partial<IxBondEdit>) => setDraft(old => old && { ...old, ...fields })
const ownedGroups = catalog.groups.filter(g => g.members.some(m => m.segmentId === segmentId))
const previous = catalog.groups.find(g => g.id === draft?.id)
const owner = previous?.ownerSegmentId ?? segmentId
const root = "/api/ix/segments/" + owner + "/linux-bonds"
const occupied = new Set(catalog.groups.filter(g => g.id !== draft?.id).flatMap(g => g.members.map(memberKey)))
const selected = (draft?.members ?? []).flatMap(m => available.get(memberKey(m)) ?? [])
const identity = previous?.clientId ?? selected.find(m => m.clientId)?.clientId
const first = selected[0]
const choices = catalog.candidates.filter(c => c.destinations.length && !occupied.has(memberKey(c)) && (!identity || !c.clientId || c.clientId === identity) &&
(!first || c.address.includes(":") === first.address.includes(":") && JSON.stringify(c.destinations) === JSON.stringify(first.destinations) &&
!selected.some(m => [m.address, m.probe].some(ip => ip === c.address || ip === c.probe))) &&
!draft?.members.some(m => memberKey(m) === memberKey(c)))
.map(c => ({ value: memberKey(c), label: label(c) }))
const needsConfirmation = selected.length > 1 && selected.some(c => !c.clientId && !previous?.members.some(m => memberKey(m) === memberKey(c)))
const selectionKey = selected.map(memberKey).sort().join(",")
const issue = error && <p role="alert" className="text-sm text-destructive">{error}</p>
const rows = children(binding => {
const k = memberKey({ ...binding, segmentId })
const current = ownedGroups.find(g => g.members.some(m => memberKey(m) === k))
const candidate = available.get(k)
if (current) return { label: "Открыть группу «" + current.name + "»", open: () => open(current) }
if (candidate?.destinations.length) return { label: "Создать группу с этим туннелем", open: () => open(undefined, candidate) }
const site = segments.find(s => s.id === segmentId)?.configuration.sites.find(s => s.serverId === binding.serverId)
const saved = site?.interfaces.find(b => b.name === binding.interfaceName)
if (saved && saved.kind !== "uplink" && !saved.peerServerId && !saved.linux && !saved.provisionWireguard && !saved.provisionGre &&
!saved.provisionTransit && !site?.neighbors.some(p => p.binding === saved.name)) {
return { label: "Создать группу с этим туннелем", open: () => { open(); setInitialInterface(binding); setImporting(true) } }
}
}, catalog)
if (!live) return <>{rows}</>
return <>{rows}<Frame spacing="sm">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<FrameTitle>Группы туннелей VPS</FrameTitle>
{!readOnly && <Button size="sm" variant="outline" onClick={() => open()}>Создать группу</Button>}
</FrameHeader>
<FramePanel className="grid gap-3">
{!draft && issue}
{!ownedGroups.length && <p className="text-sm text-muted-foreground">Туннели этого сегмента используются отдельно.</p>}
{ownedGroups.map(g => <div key={g.id} className="grid gap-1.5">
<span className="font-medium">{g.name} · {modeLabel(g.mode)}</span>
<ol className="grid gap-1 text-sm">{g.members.map((m, i) => {
const c = available.get(memberKey(m))
const role = g.mode === "failover" ? (i ? "Резерв " + i : "Основной") : "Вес " + (g.mode === "weighted" ? m.weight : 1)
return <li key={memberKey(m)}>{role} · {c ? label(c) : m.interfaceName + " · недоступен"}
{c && c.appliedRevision !== m.appliedRevision ? " · изменена ревизия" : ""}</li>
})}</ol>
{!readOnly && <div className="flex flex-wrap gap-2">
<Button size="sm" variant="outline" disabled={busy} onClick={() => open(g)}>Изменить</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
const bundle = await requestJson<IxBondBundle>(backendUrl, "/api/ix/segments/" + g.ownerSegmentId + "/linux-bonds/" + g.id + "/export",
{ method: "POST", body: JSON.stringify({ revision: g.revision }) })
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
})}>Скачать для ix-client</Button>
</div>}
</div>)}
{!!ownedGroups.length && <p className="text-sm text-muted-foreground">Импортируйте JSON в ix-client на VPS и сверьте выбранные локальные интерфейсы. Активный путь показывает TUI клиента.</p>}
</FramePanel>
<Sheet open={!!draft} onOpenChange={value => !value && !busy && setDraft(null)}>
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-xl">
<SheetHeader><SheetTitle>Группа туннелей VPS</SheetTitle>
<SheetDescription>Выберите применённые подключения одного VPS. В режиме резервирования первый туннель в списке основной.</SheetDescription>
</SheetHeader>
{draft && <form className="flex min-h-0 flex-1 flex-col" onSubmit={e => {
e.preventDefault()
if (importing || needsConfirmation && confirmedMembers !== selectionKey) return
void perform(async () => {
await requestJson(backendUrl, root, { method: "POST", body: JSON.stringify({ ...draft,
directCidrs: direct.split(/[\s,]+/).filter(Boolean) }) })
setDraft(null); setReload(n => n + 1)
})
}}>
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
{issue}
<Field><FieldLabel htmlFor="ix-bond-name">Имя группы</FieldLabel><Input id="ix-bond-name" value={draft.name} required maxLength={80} onChange={e => patch({ name: e.target.value })} /></Field>
<Field><FieldLabel htmlFor="ix-bond-mode">Режим</FieldLabel>
<Select value={draft.mode} items={[...modes]} onValueChange={v => v && patch({ mode: v })}>
<SelectTrigger id="ix-bond-mode"><SelectValue /></SelectTrigger>
<SelectContent>{modes.map(m => <SelectItem key={m.value} value={m.value}>{m.label}</SelectItem>)}</SelectContent>
</Select></Field>
{draft.members.map((m, index) => {
const candidate = available.get(memberKey(m))
return <div key={memberKey(m)} className="grid gap-2 rounded-md border p-2 text-sm">
<span>{index + 1}. {candidate ? label(candidate) : m.interfaceName + " · недоступен"}</span>
{draft.mode === "weighted" && <Field><FieldLabel htmlFor={"ix-bond-weight-" + index}>Вес</FieldLabel>
<Input id={"ix-bond-weight-" + index} type="number" min={1} max={100} required value={m.weight}
onChange={e => patch({ members: draft.members.map((item, n) => n === index ? { ...item, weight: Number(e.target.value) } : item) })} /></Field>}
<div className="flex gap-2">
<Button size="sm" variant="outline" type="button" disabled={!index} onClick={() => {
const members = [...draft.members]; members.splice(index - 1, 0, ...members.splice(index, 1)); patch({ members })
}}>Выше</Button>
<Button size="sm" variant="outline" type="button" onClick={() => patch({ members: draft.members.filter((_, i) => i !== index) })}>Исключить</Button>
</div>
</div>
})}
<Field><FieldLabel htmlFor="ix-bond-member">Добавить туннель этого VPS</FieldLabel>
<Select<string> key={draft.members.length} value={null} items={choices} disabled={!choices.length || draft.members.length >= 16} onValueChange={v => {
const c = v && available.get(v)
if (c) patch({ members: [...draft.members, memberRef(c)] })
}}>
<SelectTrigger id="ix-bond-member"><SelectValue placeholder="Выберите интерфейс" /></SelectTrigger>
<SelectContent alignItemWithTrigger={false}>{choices.map(c => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}</SelectContent>
</Select></Field>
{!choices.length && draft.members.length < 2 && <p className="text-sm text-muted-foreground">Для второго туннеля нужны другой внутренний адрес, то же семейство и одинаковые назначения. Проверьте привязку к VPS и применение подключения на его площадке.</p>}
{importing ? <IxExistingTransport backendUrl={backendUrl} segments={segments} segmentId={segmentId} nodes={nodes} initial={initialInterface}
members={[...draft.members, ...catalog.groups.filter(g => g.id !== draft.id).flatMap(g => g.members)]} destinations={first?.destinations ?? []}
cancel={() => setImporting(false)} add={m => { patch({ members: [...draft.members, m] }); setImporting(false) }} />
: <Button type="button" variant="outline" disabled={draft.members.length >= 16} onClick={() => { setInitialInterface(undefined); setImporting(true) }}>Добавить из интерфейсов RouterOS</Button>}
{needsConfirmation && <Field orientation="horizontal"><Checkbox id="ix-bond-same-vps" checked={confirmedMembers === selectionKey}
onCheckedChange={checked => setConfirmedMembers(checked ? selectionKey : "")} />
<FieldLabel htmlFor="ix-bond-same-vps">Подтверждаю, что выбранные интерфейсы настроены на одном VPS</FieldLabel></Field>}
<Field><FieldLabel htmlFor="ix-bond-direct">Прямой выход для сетей (CIDR)</FieldLabel>
<Textarea id="ix-bond-direct" rows={3} value={direct} onChange={e => setDirect(e.target.value)} /></Field>
</div>
<SheetFooter>
<Button type="submit" disabled={busy || readOnly || importing || draft.members.length < 2 || needsConfirmation && confirmedMembers !== selectionKey}>Сохранить</Button>
{draft.id && <Button type="button" variant="outline" disabled={busy || readOnly} onClick={() => {
if (!remove) { setRemove(true); return }
void perform(async () => {
await requestJson(backendUrl, root + "/" + draft.id, { method: "DELETE", body: JSON.stringify({ revision: draft.revision }) })
setDraft(null); setReload(n => n + 1)
})
}}>{remove ? "Подтвердить удаление группы" : "Удалить группу"}</Button>}
<Button type="button" variant="outline" disabled={busy} onClick={() => setDraft(null)}>Отмена</Button>
</SheetFooter>
</form>}
</SheetContent>
</Sheet>
</Frame></>
}
+68
View File
@@ -0,0 +1,68 @@
"use client"
import { useState } from "react"
import { ixExistingTransportSchema, type IxBondEdit, type IxSegment } 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 { Textarea } from "@/components/ui/textarea"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
type Member = IxBondEdit["members"][number]
export function IxExistingTransport({ backendUrl, segmentId, segments, nodes, members, destinations, initial, add, cancel }: {
backendUrl: string; segmentId: string; segments: IxSegment[]; nodes: IxNode[]; members: Member[]; destinations: string[]
add: (ref: Member) => void; cancel: () => void
initial?: Pick<Member, "serverId" | "interfaceName">
}) {
const sites = segments.filter(s => s.appliedRevision).flatMap(segment => segment.configuration.sites.map(site => ({
value: segment.id + "/" + site.serverId, label: segment.configuration.name + " · " + nodeLabel(nodes, site.serverId), segment, site,
})))
const [selection, setSelection] = useState(sites.find(s => s.segment.id === segmentId && (!initial || s.site.serverId === initial.serverId))?.value ?? "")
const site = sites.find(s => s.value === selection)
const inventory = useIxNodeInventory(backendUrl, site?.site.serverId ?? 0, site?.segment.id)
const [iface, setIface] = useState(initial?.interfaceName ?? "")
const [linuxInterface, setLinuxInterface] = useState("")
const [probe, setProbe] = useState("")
const [address, setAddress] = useState("")
const [endpoint, setEndpoint] = useState("")
const [peer, setPeer] = useState("")
const [routes, setRoutes] = useState(destinations.join("\n"))
const interfaces = (inventory.inventory?.interfaces ?? []).filter(i => /^(wg|wireguard|gre|gre-tunnel)$/.test(i.type) && !i.disabled && i.addresses.length &&
!site?.site.interfaces.some(b => b.name === i.name && (b.linux || b.provisionWireguard || b.provisionGre || b.provisionTransit || b.peerServerId)) &&
!site?.site.neighbors.some(p => p.binding === i.name) && !members.some(m => m.serverId === site?.site.serverId && m.interfaceName === i.name))
const active = interfaces.find(i => i.name === iface)
const wg = active?.type === "wg" || active?.type === "wireguard"
const probes = active?.addresses.map(a => a.split("/")[0]) ?? []
const selectedProbe = probes.includes(probe) ? probe : probes[0] ?? ""
const input = ixExistingTransportSchema.safeParse({ ...(wg ? { kind: "wireguard", clientPublicKey: peer.trim() } : { kind: "gre-ipsec", remoteEndpoint: peer.trim() }),
linuxInterface: linuxInterface.trim(), probe: selectedProbe, address: address.trim(), endpoint: endpoint.trim(), destinations: routes.trim().split(/[\s,]+/) })
return <div className="grid gap-3 rounded-md border p-3">
<Field><FieldLabel htmlFor="ix-adopt-site">Площадка и узел IX</FieldLabel>
<Select value={selection} items={sites} onValueChange={v => { setSelection(v ?? ""); setIface(""); setProbe(""); setPeer(""); setEndpoint("") }}>
<SelectTrigger id="ix-adopt-site"><SelectValue /></SelectTrigger><SelectContent>{sites.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent>
</Select></Field>
<Field><FieldLabel htmlFor="ix-adopt-interface">Интерфейс RouterOS</FieldLabel>
<Select value={iface || null} items={interfaces.map(i => ({ value: i.name, label: i.name }))} onValueChange={v => {
setIface(v ?? ""); setProbe(interfaces.find(i => i.name === v)?.addresses[0]?.split("/")[0] ?? ""); setPeer("")
}}><SelectTrigger id="ix-adopt-interface"><SelectValue placeholder="Выберите WG или GRE" /></SelectTrigger>
<SelectContent>{interfaces.map(i => <SelectItem value={i.name} key={i.name}>{i.name}</SelectItem>)}</SelectContent></Select>
<FieldDescription>{inventory.error ?? (inventory.loading ? "Читаем интерфейсы узла…" : "Доступны включённые интерфейсы с внутренним IP. Настройки RouterOS сохраняются.")}</FieldDescription></Field>
{active && <>
<Field><FieldLabel htmlFor="ix-adopt-linux">Имя интерфейса на VPS</FieldLabel><Input id="ix-adopt-linux" value={linuxInterface} onChange={e => setLinuxInterface(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-probe">Адрес IX внутри туннеля</FieldLabel>
<Select value={selectedProbe} items={probes.map(value => ({ value, label: value }))} onValueChange={v => setProbe(v ?? "")}>
<SelectTrigger id="ix-adopt-probe"><SelectValue /></SelectTrigger><SelectContent>{probes.map(v => <SelectItem key={v} value={v}>{v}</SelectItem>)}</SelectContent>
</Select></Field>
<Field><FieldLabel htmlFor="ix-adopt-address">Адрес VPS внутри туннеля</FieldLabel><Input id="ix-adopt-address" value={address} onChange={e => setAddress(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-endpoint">Внешний адрес IX</FieldLabel><Input id="ix-adopt-endpoint" value={endpoint} onChange={e => setEndpoint(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-peer">{wg ? "Публичный ключ WireGuard VPS" : "Внешний IPv4 VPS"}</FieldLabel><Input id="ix-adopt-peer" value={peer} onChange={e => setPeer(e.target.value)} /></Field>
<Field><FieldLabel htmlFor="ix-adopt-routes">Назначения через туннель (CIDR)</FieldLabel><Textarea id="ix-adopt-routes" rows={2} value={routes} onChange={e => setRoutes(e.target.value)} /></Field>
</>}
<div className="flex gap-2"><Button type="button" variant="outline" size="sm" disabled={!site || !active || !input.success} onClick={() => {
if (input.success && site?.segment.appliedRevision && active) add({ segmentId: site.segment.id, serverId: site.site.serverId,
appliedRevision: site.segment.appliedRevision, interfaceName: active.name, existing: input.data, weight: 1 })
}}>Включить в список</Button><Button type="button" size="sm" variant="ghost" onClick={cancel}>Отмена выбора</Button></div>
</div>
}
+98 -47
View File
@@ -3,7 +3,7 @@
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 type { IxBondCatalog, 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"
@@ -19,9 +19,10 @@ import { Textarea } from "@/components/ui/textarea"
import { isIpv4String } from "@/lib/gre-endpoint-resolve"
import { publicEndpoint, transitName } from "./ix-exits"
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
import type { IxRowBondAction } from "./ix-client-bonds"
type Binding = IxSite["interfaces"][number]
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean }
type ClientSelection = { site: IxSite; binding: Binding; addProtocol?: boolean; chooseTransport?: boolean }
type FormState = {
serverId: number
name: string
@@ -35,9 +36,20 @@ type FormState = {
destinations: string
exit: string
enabled: boolean
transitLocal: string
transitRemote: string
}
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
const protocols = [
{ kind: "wireguard", label: "WireGuard" },
{ kind: "gre-ipsec", label: "GRE/IPsec" },
] as const
function hasCompanion(site: IxSite, binding: Binding) {
const clientId = binding.linux?.clientId
return !!clientId && site.interfaces.some(item => item.kind !== binding.kind && item.linux?.clientId === clientId)
}
function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
@@ -45,39 +57,59 @@ function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
}
function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
function ClientForm({ segment, edit, setAddProtocol, nodes, backendUrl, catalog, busy, save, cancel }: {
segment: IxSegment; edit: ClientSelection | null; nodes: IxNode[]; backendUrl: string
catalog: IxBondCatalog
setAddProtocol: (add: boolean) => void
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
}) {
const existing = edit?.binding
const companion = edit?.addProtocol ? existing : undefined
const binding = companion ? undefined : existing
const [form, setForm] = useState<FormState>(() => ({
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
name: existing?.linux?.name ?? "",
kind: companion ? (companion.kind === "wireguard" ? "gre-ipsec" : "wireguard")
: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
key: binding?.provisionWireguard?.credentialId ? "" : binding?.provisionWireguard?.peerPublicKey ?? "",
localAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.localAddress ?? "",
peerAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.peerAddress ?? "",
prefixes: binding?.prefixes.join("\n") ?? "", destinations: binding?.linux?.destinations.join("\n") ?? "",
exit: binding?.linux?.exit ?? "isolated", enabled: binding?.linux?.enabled ?? true,
}))
const paired = !!edit && hasCompanion(edit.site, edit.binding)
const initialForm = (addProtocol: boolean): FormState => {
const current = addProtocol ? undefined : existing
const tunnel = current?.provisionWireguard ?? current?.provisionGre
return {
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
name: existing?.linux?.name ?? "",
kind: addProtocol ? (existing?.kind === "wireguard" ? "gre-ipsec" : "wireguard")
: current?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
hub: existing?.localEndpoint ?? existing?.provisionWireguard?.hubEndpoint ?? "",
peer: existing?.linux?.peerEndpoint ?? existing?.endpoint ?? "",
key: current?.provisionWireguard?.credentialId ? "" : current?.provisionWireguard?.peerPublicKey ?? "",
localAddress: tunnel?.localAddress ?? "", peerAddress: tunnel?.peerAddress ?? "",
prefixes: current?.prefixes.join("\n") ?? "", destinations: current?.linux?.destinations.join("\n") ?? "",
exit: current?.linux?.exit ?? "isolated", enabled: current?.linux?.enabled ?? true,
transitLocal: "", transitRemote: "",
}
}
const [currentForm, setCurrentForm] = useState(() => initialForm(false))
const [companionForm, setCompanionForm] = useState(() => initialForm(true))
const form = companion ? companionForm : currentForm
const setForm = companion ? setCompanionForm : setCurrentForm
const wireguard = form.kind !== "gre-ipsec"
const gre = form.kind !== "wireguard"
const [rotate, setRotate] = useState(false)
const [vpsId, setVpsId] = useState("")
const currentGroup = edit && catalog.groups.find(g => g.members.some(m => m.segmentId === segment.id &&
m.serverId === edit.site.serverId && m.interfaceName === edit.binding.name))
const currentVps = currentGroup?.clientId ?? existing?.linux?.clientId
const knownVps = useMemo(() => {
const labels = new Map<string, string>()
for (const c of catalog.candidates) if (c.clientId) labels.set(c.clientId, c.name + " · " + c.segmentName)
for (const group of catalog.groups) labels.set(group.clientId, group.name)
if (currentVps && !labels.has(currentVps)) labels.set(currentVps, existing?.linux?.name ?? "Текущий VPS")
return [...labels].map(([value, label]) => ({ value, label: label + " · " + value.slice(0, 8) }))
}, [catalog, currentVps, existing])
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 hub = form.hub.trim() || suggested
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
const localEndpoint = transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
const remoteEndpoint = transitRemote.trim() || publicEndpoint(target.inventory)
const localEndpoint = form.transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
const remoteEndpoint = form.transitRemote.trim() || publicEndpoint(target.inventory)
const family = form.kind !== "both" && form.peerAddress.includes(":") ? 6 : 4
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
@@ -101,6 +133,7 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
if (!valid || busy) return
void save({
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
vpsClientId: !companion && vpsId && vpsId !== currentVps ? vpsId : undefined,
kind: wireguard ? "wireguard" : "gre-ipsec", additionalGre: form.kind === "both" || undefined, companionOf: companion?.name,
hubEndpoint: hub, peerEndpoint: form.peer.trim() || undefined,
peerPublicKey: wireguard ? form.key.trim() || undefined : undefined,
@@ -109,12 +142,19 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
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,
enabled: form.enabled, rotate: !!binding && 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" readOnly={!!companion} required onChange={event => patch({ name: event.target.value })} /></Field>
{!companion && !!knownVps.length && <Field><FieldLabel htmlFor="ix-linux-vps">Привязка к VPS</FieldLabel>
<Select value={vpsId || currentVps || "separate"} disabled={!!currentGroup} items={[{ value: "separate", label: "Отдельное подключение" }, ...knownVps]}
onValueChange={v => setVpsId(v && v !== "separate" ? v : "")}>
<SelectTrigger id="ix-linux-vps"><SelectValue /></SelectTrigger>
<SelectContent>{!currentVps && <SelectItem value="separate">Отдельное подключение</SelectItem>}
{knownVps.map(v => <SelectItem key={v.value} value={v.value}>{v.label}</SelectItem>)}</SelectContent>
</Select>{currentGroup && <FieldDescription>Привязка задана группой «{currentGroup.name}».</FieldDescription>}</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" })}>
@@ -124,23 +164,27 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
<Field>
<FieldTitle id="ix-linux-transport">Протоколы подключения</FieldTitle>
<ButtonGroup aria-labelledby="ix-linux-transport" className="max-w-full">
<Button type="button" size="sm" variant={wireguard ? "secondary" : "outline"} aria-pressed={wireguard}
disabled={!!edit || form.kind === "wireguard"}
onClick={() => patch({ kind: wireguard ? "gre-ipsec" : "both" })}>WireGuard</Button>
<Button type="button" size="sm" variant={gre ? "secondary" : "outline"} aria-pressed={gre}
disabled={!!edit || form.kind === "gre-ipsec"}
onClick={() => patch({ kind: gre ? "wireguard" : "both" })}>GRE/IPsec</Button>
{protocols.map(({ kind, label }) => {
const choosing = !!companion && edit?.chooseTransport
const selected = choosing ? form.kind === kind : paired || !!companion || form.kind === "both" || form.kind === kind
return <Button key={kind} type="button" size="sm" variant={selected ? "secondary" : "outline"} aria-pressed={selected}
disabled={busy || (choosing ? form.kind === kind : existing ? paired || existing.kind === kind : form.kind === kind)}
onClick={() => choosing ? patch({ kind }) : existing ? setAddProtocol(!companion)
: patch({ kind: form.kind === "both" ? (kind === "wireguard" ? "gre-ipsec" : "wireguard") : "both" })}>{label}</Button>
})}
</ButtonGroup>
{form.kind === "both" ? <FieldDescription>Оба туннеля получат свои адреса в одной VRF сегмента.</FieldDescription>
: companion ? <FieldDescription>Второй туннель добавится в ту же VRF. Выход и сети можно выбрать отдельно.</FieldDescription>
: !edit && <FieldDescription>Можно отметить оба протокола.</FieldDescription>}
: companion ? <FieldDescription>Настройки ниже относятся к новому туннелю в той же VRF.</FieldDescription>
: paired ? <FieldDescription>Оба протокола настроены. Здесь редактируется {binding?.kind === "gre-ipsec" ? "GRE/IPsec" : "WireGuard"}.</FieldDescription>
: edit ? <FieldDescription>Выберите второй протокол, чтобы добавить туннель в ту же VRF.</FieldDescription>
: <FieldDescription>Можно отметить оба протокола.</FieldDescription>}
</Field>
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={gre} onChange={event => patch({ peer: event.target.value })} />
<FieldDescription>{gre ? "Фиксированный IPv4 на VPS для GRE/IPsec. Ответы на SSH по этому адресу пойдут напрямую." : form.exit === "isolated"
? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
<Select value={form.exit} items={exits} onValueChange={value => { if (value) { patch({ exit: value }); setTransitLocal(""); setTransitRemote("") } }}>
<Select value={form.exit} items={exits} onValueChange={value => { if (value) patch({ exit: value, transitLocal: "", transitRemote: "" }) }}>
<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>
@@ -148,10 +192,10 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
</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)} />
<Input id="ix-transit-target" value={form.transitRemote} onChange={event => patch({ transitRemote: 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>}
<Input id="ix-transit-source" value={localEndpoint} onChange={event => patch({ transitLocal: event.target.value })} /></Field>}
{form.exit === "isolated" && destinationsField}
<details className="grid gap-3" key={form.serverId + ":" + origin.loading + ":" + gre}
open={!origin.loading && (!hub || gre && !isIpv4String(hub)) || undefined}>
@@ -181,16 +225,17 @@ function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
</div>}
</div>
<SheetFooter>{(gre || !form.key) && <p className="text-sm text-muted-foreground">После подтверждения файлы подключения будут доступны в таблице.</p>}
<Button type="submit" disabled={!valid || busy}>Сохранить</Button>
<Button type="submit" disabled={!valid || busy}>{companion ? "Добавить туннель" : "Сохранить"}</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 }: {
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect, bondAction, catalog }: {
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
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
inspect: (binding: IxLinuxBinding) => void
bondAction: IxRowBondAction; catalog: IxBondCatalog
}) {
const [open, setOpen] = useState(false)
const [edit, setEdit] = useState<ClientSelection | null>(null)
@@ -205,7 +250,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
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>
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)} · {row.original.interfaceName}</span>
</div> },
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
@@ -221,7 +266,9 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
} },
{ id: "state", header: "Состояние", size: 160, cell: ({ row }) => {
const binding = row.original
if (!binding.policy) return <Badge variant="secondary">Прежняя настройка</Badge>
if (!binding.policy) return <div className="grid gap-1"><Badge className="w-fit" variant="secondary">Прежняя настройка</Badge>
{!catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === binding.serverId && c.interfaceName === binding.interfaceName) &&
<span className="text-xs text-muted-foreground">Параметры ручного туннеля проверяются при добавлении из RouterOS.</span>}</div>
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>
@@ -237,27 +284,30 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
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 paired = !!saved?.linux?.clientId && site?.interfaces.some(item =>
item.kind !== saved.kind && item.linux?.clientId === saved.linux?.clientId)
const paired = !!site && !!saved && hasCompanion(site, saved)
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
const bond = !readOnly && bondAction(binding)
return <div className="flex flex-wrap gap-1">
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName) +
(paired ? binding.kind === "wireguard" ? " · WireGuard" : " · GRE/IPsec" : "")}
onClick={() => view(live)}>Конфиг Linux</Button>}
{binding.policy && (live || !readOnly && saved?.linux) && <DropdownMenu>
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + binding.name} />}>
{(bond || binding.policy && (live || !readOnly && saved?.linux)) && <DropdownMenu>
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + (binding.name ?? binding.interfaceName)} />}>
<EllipsisIcon aria-hidden />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{live && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
{!readOnly && site && saved?.linux && !paired && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true }); setOpen(true) }}>Добавить другой протокол</DropdownMenuItem>}
{bond && <DropdownMenuItem onClick={bond.open}>{bond.label}</DropdownMenuItem>}
{live && (binding.policy || catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === live.serverId && c.interfaceName === live.interfaceName)) &&
<DropdownMenuItem onClick={() => view(live, true)}>Конфиг для группы ix-client</DropdownMenuItem>}
{live?.policy && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
{!readOnly && site && saved?.linux && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true, chooseTransport: true }); setOpen(true) }}>Добавить туннель</DropdownMenuItem>}
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
</DropdownMenuContent>
</DropdownMenu>}
</div>
} },
], [nodes, applied, segment.configuration.sites, readOnly, busy, view, revoke, inspect])
], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates])
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns,
getRowId: row => row.serverId + ":" + row.interfaceName })
return <Frame spacing="sm" className="min-w-0">
@@ -273,11 +323,12 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
</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?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
<SheetHeader><SheetTitle>{edit?.chooseTransport ? "Добавить туннель" : edit?.addProtocol ? "Добавить другой протокол" : edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
</SheetHeader>
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} busy={busy}
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} catalog={catalog} busy={busy}
setAddProtocol={addProtocol => setEdit(selection => selection && { ...selection, addProtocol })}
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
</SheetContent>
</Sheet>
+17 -10
View File
@@ -23,6 +23,7 @@ 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"
import { IxClientBonds } from "./ix-client-bonds"
type Tab = "configuration" | "routes" | "linux"
@@ -74,7 +75,7 @@ export default function IxPage() {
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 [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding & { transportOnly: boolean }) | null>(null)
const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null)
const [review, setReview] = useState("")
const [reviewError, setReviewError] = useState("")
@@ -261,22 +262,23 @@ export default function IxPage() {
setLinuxBindings(items)
}
async function exportLinux(binding: IxLinuxBinding) {
async function exportLinux(binding: IxLinuxBinding, transportOnly = false) {
if (!selected) return
setLinux(null)
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
if (transportOnly) query.set("transportOnly", "true")
if (binding.managedWireguard && write) {
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
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 }))
post({ serverId: binding.serverId, interfaceName: binding.interfaceName, ...(transportOnly && { transportOnly }) }))
: await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
setLinux({ ...binding, ...access })
setLinux({ ...binding, ...access, transportOnly })
}
async function inspectLinux(binding: IxLinuxBinding) {
@@ -465,12 +467,15 @@ export default function IxPage() {
</TabsContent>
<TabsContent value="linux" className="grid min-w-0 gap-3">
{selected ? <IxLinuxClients key={selected.id} segment={selected} nodes={peers} backendUrl={backendUrl}
{selected ? <IxClientBonds key={selected.id + ":" + selected.appliedRevision} segmentId={selected.id} segments={segments}
backendUrl={backendUrl} nodes={peers} readOnly={!write || busy || dirty} live={live} download={download}>
{(bondAction, catalog) => <IxLinuxClients segment={selected} nodes={peers} backendUrl={backendUrl} bondAction={bondAction} catalog={catalog}
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="После сохранения можно подключать клиентов." />}
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
inspect={binding => void perform(() => inspectLinux(binding))} />}
</IxClientBonds>
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
{linuxPath && <Frame spacing="sm">
<FrameHeader>
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
@@ -489,7 +494,9 @@ export default function IxPage() {
<FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription>
</FrameHeader>
<FramePanel className="grid min-w-0 gap-3">
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard"
<p className="text-sm text-muted-foreground">{linux.transportOnly
? "Подготовьте туннель на VPS с указанным именем интерфейса. Маршруты назначит ix-client после включения группы."
: linux.kind === "wireguard"
? linux.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
: linux.policy && write ? "Скачайте оба файла в одну папку на VPS. Скрипт установит профиль strongSwan и поднимет GRE. SSH по внешнему IPv4 VPS останется прямым."
+28
View File
@@ -464,6 +464,13 @@
],
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
},
{
"method": "GET",
"path": "/api/ix/linux-bonds",
"status": "excluded",
"operations": [],
"reason": "Каталог для формы выбора туннелей одного VPS в WebUI. Оператор сопоставляет подключения разных площадок со своими локальными интерфейсами."
},
{
"method": "GET",
"path": "/api/ix/nodes",
@@ -1618,6 +1625,27 @@
"operations": [],
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux-bonds",
"status": "excluded",
"operations": [],
"reason": "WebUI сохраняет выбранные оператором интерфейсы и порядок путей для последующего импорта и подтверждения в локальном ix-client."
},
{
"method": "DELETE",
"path": "/api/ix/segments/:id/linux-bonds/:bondId",
"status": "excluded",
"operations": [],
"reason": "Оператор удаляет сохранённое описание группы из WebUI. Снятие политики на самом VPS подтверждается отдельно в ix-client."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/linux-bonds/:bondId/export",
"status": "excluded",
"operations": [],
"reason": "Оператор скачивает JSON группы из WebUI и локально сопоставляет его с интерфейсами VPS в ix-client."
},
{
"method": "POST",
"path": "/api/ix/segments/:id/plan",
+2 -1
View File
@@ -60,6 +60,7 @@
"test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts",
"test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts",
"test": "node scripts/test.mjs",
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts",
"test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts",
"test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts",
"test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts",
@@ -68,7 +69,7 @@
"test:containers": "tsx src/services/containers-live.test.ts && tsx src/services/containers-state.test.ts && tsx src/services/container-removal.test.ts && tsx src/routes/containers-state.test.ts",
"test:certificates": "tsx src/services/certificate-installation.test.ts && tsx src/services/certificate-renew-collector.test.ts && tsx src/services/certificate-issue-execution.test.ts && tsx src/services/certificate-issue-request.test.ts && tsx src/routes/certificates-issue.test.ts && tsx src/services/certificate-issue-dto.test.ts && tsx src/services/certificate-parse.test.ts && tsx src/services/certificates-state.test.ts && tsx src/routes/certificates-state.test.ts && tsx src/services/acme-settings-test.test.ts && tsx src/services/acme-settings-update-model.test.ts && tsx src/modules/mcp/acme-settings-actions.test.ts",
"test:system-database": "tsx src/services/bounded-database-dump.test.ts && tsx src/services/database-dump-connection.test.ts && tsx src/services/system-database-partition-restore.test.ts && tsx src/services/system-database-cache.test.ts && tsx src/services/database-background-work.test.ts && tsx src/services/database-request-gate.test.ts && tsx --test src/services/detached-database-admission.test.ts && tsx src/services/traffic-flow-worker-shutdown.test.ts && tsx src/services/system-database-restore-execution.test.ts && tsx src/services/system-database-operation.test.ts && tsx src/services/system-database-schema-readiness.test.ts && tsx --test src/routes/mcp-oauth-database-admission.test.ts && tsx src/routes/system-database.test.ts && tsx src/plugins/auth.system-database.test.ts && tsx src/services/database-control-archive-boundary.test.ts && tsx src/db/database-schema-control-model.test.ts && tsx src/db/database-schema-control.test.ts && tsx src/db/controlled-migrations.test.ts && tsx src/db/controlled-schema-verification.test.ts && tsx --test src/db/migration-data-inventory.test.ts && tsx --test src/services/database-maintenance-startup.test.ts && tsx --test src/services/database-restore-audit.test.ts && tsx --test src/services/database-maintenance-resolution.test.ts && tsx --test scripts/database-maintenance-resolution.test.mts && tsx src/db/database-runtime-schema.test.ts",
"test:all": "npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
"test:all": "npm run test:ix && npm run test:logs && npm run test:probes && npm run test:exec && npm run test:alert-engine && npm run test:alerts-telegram && npm run test:auth && npm run test:wireguard && npm run test:ipsec && npm run test:traffic-rate && npm run test:traffic-flow && npm run test:users && npm run test:pg && npm run test:sidebar-counts && npm run test:backups && npm run test:scheduler && npm run test:live-maps && npm run test:ospf-optimizer && npm run test:recursive-routes && npm run test:config-sync && npm run test:ros-file && npm run test:containers && npm run test:certificates && npm run test:netflow-settings && npm run test:netflow-purge && npm run test:evolution && npm run test:system-database && npm run test:server-privacy && npm run test:mcp:module-completion && npm run test:mcp:loopback-agent && npm run test:server-probe-management && npm run test:server-poll-management && npm run test:mcp:routing-authority && npm run test:mcp:native-readers && npm run test:mcp:chr-acquisition && npm run test:mcp:shared-context && npm run test:mcp:telemetry-configuration",
"test:server-privacy": "tsx ../packages/contracts/src/servers.test.ts && tsx src/routes/server-secrets-sql.test.ts && tsx --test src/services/server-connection-test.test.ts",
"test:mcp:flow-rebuild:pg": "node scripts/test-mcp-postgres.mjs --flow-rebuild-mcp",
"test:mcp:flow-host-keys:pg": "node scripts/test-mcp-postgres.mjs --flow-host-keys",
+122 -7
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"
import { createPrivateKey, createPublicKey, randomBytes, randomUUID } from "node:crypto"
import { mkdtemp } from "node:fs/promises"
import { createServer } from "node:http"
import { mkdtemp, writeFile } from "node:fs/promises"
import { createServer, type RequestListener } from "node:http"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { setTimeout as delay } from "node:timers/promises"
@@ -23,7 +23,8 @@ Object.assign(process.env, {
})
await pg.initialise()
await pg.start()
const rows: Record<string, Record<string, string>[]> = {
type RouterRows = Record<string, Record<string, string>[]>
const rows: RouterRows = {
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }],
"/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }],
@@ -34,7 +35,8 @@ let writes = 0
let deletes = 0
let failPutAt = -1
let failDeleteAt = -1
const router = createServer(async (request, response) => {
const fixtureHubPublicKey = Buffer.alloc(32, 11).toString("base64")
const serveRouter = (rows: RouterRows): RequestListener => async (request, response) => {
try {
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
let result: unknown
@@ -44,7 +46,7 @@ const router = createServer(async (request, response) => {
let raw = ""
for await (const chunk of request) raw += chunk
const { "place-before": place, ...fields } = JSON.parse(raw)
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": "B".repeat(43) + "=" }),
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": fixtureHubPublicKey }),
".id": "*" + (++writes + 1).toString(16).toUpperCase() }
const list = rows[path] ??= []
const index = list.findIndex(entry => entry[".id"] === place)
@@ -83,7 +85,16 @@ const router = createServer(async (request, response) => {
response.statusCode = 500
response.end(JSON.stringify({ error: String(error) }))
}
})
}
const router = createServer(serveRouter(rows))
const backupRows: RouterRows = {
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
"/interface": [{ ".id": "*2", name: "ether1", type: "ether", running: "true" }],
"/ip/address": [{ ".id": "*3", interface: "ether1", address: "198.51.100.20/24" }],
"/ip/route": [{ ".id": "*4", "routing-table": "main", "dst-address": "0.0.0.0/0",
gateway: "198.51.100.1%ether1", "immediate-gw": "198.51.100.1%ether1", active: "true" }],
}
const backupRouter = createServer(serveRouter(backupRows))
const { initDatabase } = await import("../../src/db/bootstrap.js")
const { pool } = await import("../../src/db/index.js")
let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined
@@ -369,6 +380,8 @@ try {
const bindings = paired.segment.configuration.sites[0].interfaces
const [wireguard, greBinding] = bindings
assert.ok(wireguard.linux.clientId)
const original = resumed.segment.configuration.sites[0].interfaces[0]
assert.deepEqual(wireguard, { ...original, linux: { ...original.linux, clientId: wireguard.linux.clientId } })
assert.equal(wireguard.linux.clientId, greBinding.linux.clientId)
assert.notEqual(wireguard.provisionWireguard.peerAddress, greBinding.provisionGre.peerAddress)
const foreignRoute = { ".id": "*FE", "routing-table": "main", "dst-address": "198.51.100.0/24",
@@ -391,6 +404,26 @@ try {
assert(greCredential.setup.indexOf(" lookup main\n") < greCredential.setup.indexOf("swanctl --initiate"))
assert.equal((await post(managedPath + "/linux/credential", clientKey, 200)).template, credential.template)
const bondPath = managedPath + "/linux-bonds"
const bondInput = { revision: 0, name: "mixed", mode: "weighted", directCidrs: ["192.0.2.0/24"],
members: [wireguard, greBinding].map((binding, i) => ({ segmentId: managed.id, serverId: clientKey.serverId,
interfaceName: binding.name, weight: i ? 1 : 3, appliedRevision: pairedApplied.segment.revision })) }
await post(bondPath, bondInput, 403, reader)
const bond = await post(bondPath, bondInput, 200)
assert.equal(bond.clientId, wireguard.linux.clientId)
await post(bondPath, bondInput, 409)
const bundlePath = bondPath + "/" + bond.id + "/export"
const bundle = await post(bundlePath, { revision: 1 }, 200)
assert.deepEqual(bundle.members.map(member => [member.kind, member.weight]), [["wireguard", 3], ["gre-ipsec", 1]])
assert.equal(bundle.members[0].peerPublicKey, fixtureHubPublicKey)
assert.deepEqual(bundle.destinations, ["0.0.0.0/0"])
assert(!JSON.stringify(bundle).includes(privateKey))
if (process.env.IX_BOND_TEST_EXPORT) {
await writeFile(process.env.IX_BOND_TEST_EXPORT, JSON.stringify(bundle, null, 2) + "\n", { flag: "wx" })
}
await post(bundlePath, { revision: 1 }, 403, reader)
await post(managedPath + "/removal-plan", { revision: pairedApplied.segment.revision }, 409)
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])
@@ -400,6 +433,18 @@ try {
const beforeStage = writes
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
assert(!Object.hasOwn(stagedRemote.segment.configuration, "linuxBonds"))
assert.deepEqual(await post(bundlePath, { revision: 1 }, 200), bundle)
const racing = await Promise.all(["equal", "failover"].map(mode => fetch(origin + "/api/ix/segments" + bondPath, {
method: "POST", headers: { authorization: "Bearer " + writer, "content-type": "application/json" },
body: JSON.stringify({ ...bondInput, id: bond.id, revision: 1, mode }),
})))
assert.deepEqual(racing.map(r => r.status).sort(), [200, 409])
const revised = await racing.find(r => r.ok)!.json()
assert.equal(revised.revision, 2)
await post(bundlePath, { revision: 1 }, 409)
await post(bondPath + "/" + bond.id, { revision: 2 }, 204, writer, "DELETE")
await post(bundlePath, { revision: 2 }, 409)
assert.equal(writes, beforeStage)
assert.equal(stagedRemote.segment.revision, appliedRevision + 1)
assert.equal(stagedRemote.segment.appliedRevision, appliedRevision)
@@ -421,14 +466,84 @@ try {
assert.ok(added[0].linux.clientId)
assert.equal(added[0].linux.clientId, added[1].linux.clientId)
await new Promise<void>(resolve => backupRouter.listen(0, "127.0.0.1", resolve))
const { rows: [secondIx] } = await pool.query(`INSERT INTO servers
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
VALUES('owned-bond-peer','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`,
[(backupRouter.address() as { port: number }).port])
const secondSegment = (await post("", { revision: 0, configuration: { name: "ix-web-bond-peer", sites: [
{ serverId: Number(secondIx.id), autonomousSystem: 64513, routerId: "192.0.2.8" },
] } }, 200)).segment
const secondPath = "/" + secondSegment.id
const secondInput = { ...clientInput, hubEndpoint: "198.51.100.20", serverId: Number(secondIx.id), revision: secondSegment.revision }
await post(secondPath + "/linux", { ...secondInput, vpsClientId: randomUUID() }, 409)
const existingPair = await post(secondPath + "/linux", { ...secondInput, additionalGre: true }, 200)
const initialPairPlan = await post(secondPath + "/plan", { revision: existingPair.segment.revision }, 200)
const appliedPair = (await post(secondPath + "/apply", { revision: existingPair.segment.revision, digest: initialPairPlan.digest }, 200)).segment
const [oldWg, oldGre] = appliedPair.configuration.sites[0].interfaces
assert.notEqual(oldWg.linux.clientId, bond.clientId)
const changeIdentity = { ...secondInput, interfaceName: oldWg.name, vpsClientId: bond.clientId, revision: appliedPair.revision }
const secondWg = await post(secondPath + "/linux", changeIdentity, 200)
const newTunnel = secondWg.segment.configuration.sites[0].interfaces[0]
assert.deepEqual(newTunnel, { ...oldWg, linux: { ...oldWg.linux, clientId: bond.clientId } })
assert.deepEqual(secondWg.segment.configuration.sites[0].interfaces[1], oldGre)
assert.notEqual(newTunnel.provisionWireguard.peerAddress, wireguard.provisionWireguard.peerAddress)
const secondaryPlan = await post(secondPath + "/plan", { revision: secondWg.segment.revision }, 200)
assert.deepEqual(secondaryPlan.changes, [])
const secondaryApplied = (await post(secondPath + "/apply", { revision: secondWg.segment.revision, digest: secondaryPlan.digest }, 200)).segment
const cross = await post(bondPath, { ...bondInput, members: [bondInput.members[0], {
segmentId: secondSegment.id, appliedRevision: secondaryApplied.revision, serverId: secondInput.serverId, interfaceName: secondWg.interfaceName, weight: 1,
}] }, 200)
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 409)
const groupedChange = await post(secondPath + "/linux", { ...changeIdentity, vpsClientId: oldGre.linux.clientId, revision: secondaryApplied.revision }, 409)
assert.match(groupedChange.error, /исключите подключение/)
const crossBundle = await post(bondPath + "/" + cross.id + "/export", { revision: 1 }, 200)
assert.equal(crossBundle.members[1].address, newTunnel.provisionWireguard.peerAddress)
await post(bondPath + "/" + cross.id, { revision: 1 }, 204, writer, "DELETE")
const ownPublicKey = Buffer.alloc(32, 29).toString("base64")
const manualVrf = backupRows["/ip/vrf"]
const manualGrePolicy = { "src-address": "198.51.100.20/32", "dst-address": "192.0.2.22/32", protocol: "gre", action: "encrypt", level: "require", tunnel: "false" }
backupRows["/interface/wireguard"].push({ name: "pre-wg", "public-key": fixtureHubPublicKey })
backupRows["/interface/wireguard/peers"].push({ interface: "pre-wg", "public-key": ownPublicKey, "allowed-address": "10.7.0.2/32" })
backupRows["/interface/gre"].push({ name: "pre-gre", "local-address": "198.51.100.20", "remote-address": "192.0.2.22", "allow-fast-path": "false" })
backupRows["/ip/ipsec/policy"].push(manualGrePolicy)
backupRows["/ip/address"].push({ interface: "pre-wg", address: "10.7.0.1/30" }, { interface: "pre-gre", address: "10.8.0.1/30" })
const refs = ["pre-wg", "pre-gre"].map((interfaceName, i) => ({ interfaceName, segmentId: secondSegment.id, serverId: secondInput.serverId,
appliedRevision: secondaryApplied.revision, weight: 1, existing: { linuxInterface: i ? "gre-manual" : "wg0", address: "10." + (7 + i) + ".0.2",
probe: "10." + (7 + i) + ".0.1", endpoint: "198.51.100.20", destinations: ["10.250.0.0/24"],
...(i ? { kind: "gre-ipsec", remoteEndpoint: "192.0.2.22" } : { kind: "wireguard", clientPublicKey: ownPublicKey }) } }))
const manualPath = secondPath + "/linux-bonds"
const manualInput = { ...bondInput, name: "existing", members: refs }
const beforeManual = JSON.stringify(backupRows)
const writesBeforeManual = writes
await post(manualPath, manualInput, 403, reader)
await post(manualPath, { ...manualInput, members: [{ ...refs[0], existing: { ...refs[0].existing, clientPublicKey: fixtureHubPublicKey } }, refs[1]] }, 409)
manualVrf.unshift({ name: "another-vrf", interfaces: "pre-wg" })
await post(manualPath, manualInput, 409)
manualVrf.shift()
const manual = await post(manualPath, manualInput, 200)
const manualExport = manualPath + "/" + manual.id + "/export"
const result = await post(manualExport, { revision: 1 }, 200)
assert.deepEqual(result.members.map(p => p.interfaceName), ["wg0", "gre-manual"])
assert.equal(result.members[0].peerPublicKey, fixtureHubPublicKey)
manualGrePolicy.level = "use"
await post(manualExport, { revision: 1 }, 409)
manualGrePolicy.level = "require"
await post(manualPath + "/" + manual.id, { revision: 1 }, 204, writer, "DELETE")
assert.equal(writes, writesBeforeManual)
assert.equal(JSON.stringify(backupRows), beforeManual)
await post(secondPath + "/removal-plan", { revision: secondaryApplied.revision }, 200)
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, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true }))
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true, bothProtocolsInOneVrf: true,
mixedBondExport: true, crossSegmentBond: true, concurrentBondEdits: true, existingRouterOsTunnels: true }))
} finally {
await mcp?.close()
await app?.close()
await new Promise<void>(resolve => router.close(() => resolve()))
if (backupRouter.listening) await new Promise<void>(resolve => backupRouter.close(() => resolve()))
await pool.end()
await pg.stop()
}
+4
View File
@@ -9,6 +9,10 @@ assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length
assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter")
const implemented = new Set(listActions().map(action => action.operation.id))
const ixInterfaceRoutes = new Set([
"GET /api/ix/linux-bonds",
"POST /api/ix/segments/:id/linux-bonds",
"DELETE /api/ix/segments/:id/linux-bonds/:bondId",
"POST /api/ix/segments/:id/linux-bonds/:bondId/export",
"GET /api/ix/nodes",
"GET /api/ix/segments/:id/linux",
"GET /api/ix/topology",
+35 -6
View File
@@ -1,16 +1,17 @@
import { randomUUID } from "node:crypto"
import type { FastifyPluginAsync } from "fastify"
import { z } from "zod"
import { ixChangeSchema, ixLinuxClientRequest, ixTransitRequest, type IxWebPlan } from "@mmapp/contracts/internet-exchange"
import { ixBondEditSchema, 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 { withApplicationCollectorLock, withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { withConfigurationActor } from "../services/config-mutation-policy.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"
import { changeIxBond, exportIxBond, inspectIxBondImports, ixBondCatalog } from "../services/internet-exchange-bonds.js"
const paging = z.object({
limit: z.coerce.number().int().min(1).max(100).default(25),
@@ -65,6 +66,34 @@ const ixRoutes: FastifyPluginAsync = async app => {
const input = paging.parse(request.query)
return { items: await listIxSegments(input.limit, input.offset) }
})
app.get("/ix/linux-bonds", async () => ixBondCatalog())
app.post("/ix/segments/:id/linux-bonds", async request => {
const { id } = segmentParams.parse(request.params)
const edit = ixBondEditSchema.parse(request.body)
await inspectIxBondImports(id, edit)
return withApplicationMutationLock(() => changeIxBond(id, edit, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
})
app.delete("/ix/segments/:id/linux-bonds/:bondId", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision } = planRequest.parse(request.body)
await withApplicationMutationLock(() => changeIxBond(id, { id: bondId, revision }, request.authUser?.id ?? "local-operator"), { waitMs: 5000 })
return reply.code(204).send()
})
app.post("/ix/segments/:id/linux-bonds/:bondId/export", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision } = planRequest.parse(request.body)
const scope = { deadlineAt: Date.now() + 90_000 }
const token = await captureVerifiedRestRequest(request, scope)
const authorize = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = await authorize()
return withApplicationCollectorLock(async () => {
const bundle = await exportIxBond(id, bondId, revision, authorize)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
await authorize()
reply.header("Cache-Control", "no-store")
return bundle
})
})
app.get("/ix/nodes", async () => {
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"),
@@ -96,12 +125,12 @@ const ixRoutes: FastifyPluginAsync = async app => {
app.get("/ix/segments/:id/linux", async request => {
const { id } = z.object({ id: z.string().uuid() }).parse(request.params)
const query = z.union([
z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) }).strict(),
z.object({ serverId: z.coerce.number().positive().int().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/), transportOnly: z.literal("true").optional() }).strict(),
z.object({}).strict(),
]).parse(request.query)
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName) : listIxLinuxClients(segment)
return "serverId" in query ? readIxLinuxClient(segment, query.serverId, query.interfaceName, false, query.transportOnly === "true") : listIxLinuxClients(segment)
})
app.post("/ix/segments/:id/linux", async request => {
const { id } = segmentParams.parse(request.params)
@@ -129,13 +158,13 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
const { id } = segmentParams.parse(request.params)
const { serverId, interfaceName } = clientKey.parse(request.body)
const { serverId, interfaceName, transportOnly } = clientKey.extend({ transportOnly: z.boolean().optional() }).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)
const access = await readIxLinuxClient(segment, serverId, interfaceName, true, transportOnly)
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")
@@ -0,0 +1,55 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import type { IxBondCandidate, IxBondEdit, IxSavedBond } from "@mmapp/contracts/internet-exchange"
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
import { bondCandidates, resolveBondMembers } from "./internet-exchange-bonds.js"
const owner = "a213a2c7-53cd-4325-8e43-e2d953cd761b"
const other = "5c1364bd-6147-46ea-b726-273a7e933302"
const client = "5a7fa65a-f94f-475a-96cd-a2ece0ed77ce"
const primary: IxBondCandidate = { segmentId: owner, appliedRevision: 3, serverId: 5, segmentName: "eu",
interfaceName: "wg-vps", name: "alpha", kind: "wireguard", probe: "10.255.0.1", address: "10.255.0.2", endpoint: "192.0.2.1", destinations: ["0.0.0.0/0"] }
const backup: IxBondCandidate = { ...primary, segmentId: other, segmentName: "asia", clientId: client,
serverId: 6, kind: "gre-ipsec", interfaceName: "gre-vps", probe: "10.255.0.5", address: "10.255.0.6" }
const edit: IxBondEdit = { name: "vps", mode: "weighted", directCidrs: [], revision: 0,
members: [primary, backup].map(({ segmentId, appliedRevision, serverId, interfaceName }, i) =>
({ segmentId, appliedRevision, serverId, interfaceName, weight: i ? 1 : 3 })) }
test("cross-segment members retain order, declared VPS identity and revision", () => {
const { members, clientId } = resolveBondMembers(edit, [backup, primary], [], owner)
assert.deepEqual(members, [primary, backup])
assert.equal(clientId, client)
const saved: IxSavedBond = { ...edit, id: other, ownerSegmentId: owner, revision: 1, clientId }
assert.throws(() => resolveBondMembers(edit, [primary, backup], [saved], owner), /уже входит/)
assert.equal(resolveBondMembers(saved, [primary, backup], [saved], owner, saved).clientId, client)
})
test("reject stale, revoked, foreign-client and conflicting routing paths", () => {
const invalid: Array<[IxBondCandidate, RegExp]> = [
[{ ...backup, appliedRevision: 4 }, /изменилось/],
[{ ...backup, destinations: ["198.51.100.0/24"] }, /назначения/],
[{ ...backup, address: primary.probe }, /внутренние адреса/],
]
for (const [candidate, reason] of invalid) {
assert.throws(() => resolveBondMembers(edit, [primary, candidate], [], owner), reason)
}
assert.throws(() => resolveBondMembers(edit, [primary], [], owner), /недоступно/)
assert.throws(() => resolveBondMembers(edit, [{ ...primary, clientId: owner }, backup], [], owner), /разными VPS/)
assert.throws(() => resolveBondMembers(edit, [primary, backup], [], client), /текущего сегмента/)
})
test("existing static WireGuard exports keep their applied prefixes; external GRE and BGP remain independent", () => {
const config = ixSegmentConfigurationSchema.parse({ name: "legacy", sites: [{ serverId: 5, autonomousSystem: 64512,
routerId: "192.0.2.1", interfaces: [
{ kind: "wireguard", name: "wg-static", provisionWireguard: { listenPort: 31820, hubEndpoint: primary.endpoint,
localAddress: primary.probe + "/30", peerAddress: primary.address, peerPublicKey: Buffer.alloc(32, 3).toString("base64") } },
{ kind: "gre-ipsec", name: "gre-manual", localEndpoint: primary.endpoint, endpoint: "198.51.100.8", prefixes: ["10.7.0.0/24"] },
] }] })
const [candidate] = bondCandidates(owner, 7, config)
assert.deepEqual(bondCandidates(owner, 7, config).map(c => c.interfaceName), ["wg-static"])
assert.deepEqual(candidate.destinations, ["10.7.0.0/24"])
assert.equal(candidate.clientId, undefined)
config.sites[0].neighbors.push({ id: "bgp", binding: "wg-static", type: "member", remoteAs: 64513,
address: primary.address, localAddress: primary.probe, prefixes: [], exportPrefixes: [], rules: [], limit: 10 })
assert.deepEqual(bondCandidates(owner, 7, config), [])
})
@@ -0,0 +1,176 @@
import { randomUUID } from "node:crypto"
import { isIP } from "node:net"
import type { PoolClient } from "pg"
import {
ixBondBundleSchema, ixSavedBondSchema, ixSegmentConfigurationSchema, type IxBondCandidate,
type IxBondEdit, type IxSavedBond, type IxConfiguration, type IxBondBundle,
} from "@mmapp/contracts/internet-exchange"
import { pool } from "../db/index.js"
import { audit } from "../modules/mcp/store.js"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName } from "./internet-exchange-client.js"
import { readIxLinuxClient, verifyIxExistingTransport } from "./internet-exchange-execution.js"
import { IxConflict } from "./internet-exchange-plan.js"
import { ixReservedTunnelBindings, readIxSegment } from "./internet-exchange-store.js"
import { admitPartitionWriter } from "./partition-write-transaction.js"
type Query = Pick<PoolClient, "query">
type MemberRef = IxBondEdit["members"][number]
const visible = "(s.configuration->>'deleted') IS DISTINCT FROM 'true'"
const key = (m: Pick<MemberRef, "segmentId" | "serverId" | "interfaceName">) => [m.segmentId, m.serverId, m.interfaceName].join("/")
export function bondCandidates(segmentId: string, appliedRevision: number, config: IxConfiguration): IxBondCandidate[] {
return config.sites.flatMap(site => site.interfaces.flatMap(binding => {
const kind = ixLinuxBindingKind(binding)
const linux = binding.linux
const tunnel = binding.provisionWireguard ?? binding.provisionGre
if (!kind || linux?.enabled === false || !tunnel || binding.peerServerId) return []
if (!linux && (kind !== "wireguard" || site.neighbors.some(peer => peer.binding === binding.name))) return []
const family = isIP(tunnel.peerAddress)
const routes = linux ? linux.destinations : ixLegacyWireguardRoutes(config, binding)
const destinations = linux?.exit ? [family === 6 ? "::/0" : "0.0.0.0/0"]
: [...new Set(routes.map(canonicalBgpPolicyPrefix))].sort()
if (!linux && (!destinations.length || destinations.length > 64 || destinations.some(cidr => isIP(cidr.split("/")[0]) !== family))) return []
return [{
segmentId, appliedRevision, segmentName: config.name, serverId: site.serverId, interfaceName: binding.name,
name: linux?.name ?? binding.name, clientId: linux?.clientId, kind, address: tunnel.peerAddress, probe: tunnel.localAddress.split("/")[0],
endpoint: (binding.provisionWireguard?.hubEndpoint ?? binding.localEndpoint)!,
destinations,
}]
}))
}
async function candidates(sql: Query, ids?: string[], refs: MemberRef[] = []) {
const { rows } = await sql.query(`SELECT s.id,s.applied_revision,r.configuration FROM ix_segments s
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE ${visible} AND ($1::uuid[] IS NULL OR s.id=ANY($1)) ORDER BY s.name,s.id`, [ids ?? null])
return rows.flatMap(row => {
const config = ixSegmentConfigurationSchema.parse(row.configuration)
const result = bondCandidates(row.id, row.applied_revision, config)
for (const ref of refs) {
const path = ref.existing
if (!path || ref.segmentId !== row.id) continue
const site = config.sites.find(s => s.serverId === ref.serverId)
const binding = site?.interfaces.find(b => b.name === ref.interfaceName)
if (!site || binding && (binding.peerServerId || binding.provisionTransit || binding.provisionWireguard || binding.provisionGre || binding.linux ||
binding.kind !== path.kind) || result.some(c => key(c) === key(ref)) || site.neighbors.some(p => p.binding === ref.interfaceName)) {
throw new IxConflict("Интерфейс занят клиентом, BGP либо принадлежит другому узлу: " + ref.interfaceName)
}
result.push({ ...ref, ...path, segmentName: config.name, appliedRevision: row.applied_revision, name: path.linuxInterface,
destinations: [...new Set(path.destinations.map(canonicalBgpPolicyPrefix))].sort() })
}
return result
})
}
export async function inspectIxBondImports(ownerId: string, edit: IxBondEdit) {
if (!edit.members.some(m => m.existing)) return
const [available, groups] = await Promise.all([candidates(pool, [...new Set(edit.members.map(m => m.segmentId))], edit.members), savedGroups(pool)])
resolveBondMembers(edit, available, groups, ownerId, groups.find(g => g.id === edit.id && g.ownerSegmentId === ownerId))
for (const m of edit.members) if (m.existing) await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing)
}
async function savedGroups(sql: Query, ownerId?: string): Promise<IxSavedBond[]> {
const { rows } = await sql.query(`SELECT item FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') item
WHERE ${visible} AND ($1::uuid IS NULL OR s.id=$1) ORDER BY s.id`, [ownerId ?? null])
return rows.map(row => ixSavedBondSchema.parse(row.item))
}
export async function ixBondCatalog() {
const [groups, available] = await Promise.all([savedGroups(pool), candidates(pool)])
return { groups, candidates: available }
}
export function resolveBondMembers(edit: IxBondEdit, available: IxBondCandidate[], groups: IxSavedBond[], ownerId: string, previous?: IxSavedBond) {
const routerInterface = (m: MemberRef) => m.serverId + "/" + m.interfaceName
const occupied = new Set(groups.filter(g => g.id !== previous?.id).flatMap(g => g.members.map(routerInterface)))
const owned = new Map(available.map(m => [key(m), m]))
const addresses = new Set<string>()
const linuxNames = new Set<string>()
const members = edit.members.map(member => {
const label = member.interfaceName
const found = owned.get(key(member))
if (!found || found.appliedRevision !== member.appliedRevision) throw new IxConflict("Подключение изменилось или недоступно: " + label)
if (occupied.has(routerInterface(member))) throw new IxConflict("Интерфейс уже входит в группу: " + label)
occupied.add(routerInterface(member))
const linuxName = found.existing?.linuxInterface ?? ixLinuxInterfaceName(found.kind === "wireguard" ? "ixw" : "ixg", found.serverId, { name: found.interfaceName })
if (linuxNames.has(linuxName)) throw new IxConflict("Имя интерфейса на VPS повторяется: " + linuxName)
linuxNames.add(linuxName)
for (const address of [found.address, found.probe]) {
const host = canonicalBgpPolicyPrefix(address + (isIP(address) === 6 ? "/128" : "/32"))
if (addresses.has(host)) throw new IxConflict("Назначьте разные внутренние адреса участникам группы: " + address)
addresses.add(host)
}
return found
})
const first = members[0]
if (!members.some(m => m.segmentId === ownerId)) throw new IxConflict("Выберите подключение из текущего сегмента")
if (!first?.destinations.length || members.some(m => isIP(m.address) !== isIP(first.address) ||
JSON.stringify(m.destinations) !== JSON.stringify(first.destinations))) {
throw new IxConflict("Участникам нужны одинаковые непустые назначения и одно семейство адресов")
}
const identities = new Set(members.flatMap(m => m.clientId ? [m.clientId] : []))
if (previous) identities.add(previous.clientId)
if (identities.size > 1) throw new IxConflict("Выбранные подключения зарегистрированы за разными VPS")
return { members, clientId: [...identities][0] ?? randomUUID() }
}
export async function changeIxBond(ownerId: string, edit: IxBondEdit | { id: string; revision: number }, actor: string) {
const sql = await pool.connect()
try {
await sql.query("BEGIN")
await admitPartitionWriter(sql)
// A member can belong to only one group, including groups owned by another segment.
await sql.query("SELECT pg_advisory_xact_lock(hashtextextended('ix-linux-bonds',0))")
if (!await readIxSegment(ownerId, sql)) throw new IxConflict("Сегмент IX не найден", 404)
const groups = await savedGroups(sql)
const previous = groups.find(group => group.ownerSegmentId === ownerId && group.id === edit.id)
if (edit.id && !previous) throw new IxConflict("Группа не найдена", 404)
if ((previous?.revision ?? 0) !== edit.revision) throw new IxConflict("Группа изменилась. Обновите данные")
let next: IxSavedBond | null = null
if ("members" in edit) {
const available = await candidates(sql, [...new Set(edit.members.map(m => m.segmentId))], edit.members)
const { clientId } = resolveBondMembers(edit, available, groups, ownerId, previous)
for (const m of edit.members) if (m.existing && (await ixReservedTunnelBindings(m.serverId, m.segmentId, sql)).some(b => b.name === m.interfaceName)) {
throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + m.interfaceName)
}
next = ixSavedBondSchema.parse({ ...edit, id: previous?.id ?? randomUUID(), ownerSegmentId: ownerId, clientId,
revision: edit.revision + 1, directCidrs: [...new Set(edit.directCidrs.map(canonicalBgpPolicyPrefix))] })
}
const owned = groups.filter(group => group.ownerSegmentId === ownerId && group.id !== edit.id)
if (next) owned.push(next)
const result = await sql.query(`UPDATE ix_segments s SET configuration=jsonb_set(configuration,'{linuxBonds}',$2::jsonb)
WHERE s.id=$1 AND ${visible}`, [ownerId, JSON.stringify(owned)])
if (result.rowCount !== 1) throw new IxConflict("Сегмент IX недоступен")
await audit(sql, actor, next ? "ix.bond.saved" : "ix.bond.removed", null, { ownerId, id: next?.id ?? edit.id, revision: next?.revision ?? edit.revision })
await sql.query("COMMIT")
return next
} catch (error) {
await sql.query("ROLLBACK").catch(() => {})
throw error
} finally { sql.release() }
}
export async function exportIxBond(ownerId: string, id: string, revision: number, authorize: () => Promise<unknown>): Promise<IxBondBundle> {
const group = (await savedGroups(pool, ownerId)).find(g => g.id === id)
if (!group || group.revision !== revision) throw new IxConflict("Группа отсутствует или её ревизия изменилась")
const segments = [...new Set(group.members.map(m => m.segmentId))]
const { members } = resolveBondMembers(group, await candidates(pool, segments, group.members), [], ownerId, group)
const result = []
for (const [index, m] of members.entries()) {
await authorize()
const segment = await readIxSegment(m.segmentId)
if (!segment || segment.appliedRevision !== m.appliedRevision) throw new IxConflict("Изменилась площадка " + m.segmentName)
const access = m.existing ? { filename: m.existing.linuxInterface,
hubPublicKey: await verifyIxExistingTransport(m.segmentId, m.serverId, m.interfaceName, m.existing) }
: await readIxLinuxClient(segment, m.serverId, m.interfaceName)
result.push({ kind: m.kind, interfaceName: m.existing ? m.existing.linuxInterface : access.filename.replace(/\.conf$/, ""), address: m.address, probe: m.probe,
endpoint: m.endpoint, weight: group.mode === "weighted" ? group.members[index].weight : 1,
...(m.kind === "wireguard" && { peerPublicKey: access.hubPublicKey }) })
}
const bundle = ixBondBundleSchema.parse({ version: 1, id, revision, name: group.name, clientId: group.clientId, mode: group.mode,
destinations: members[0].destinations, directCidrs: group.directCidrs, members: result })
await authorize()
return bundle
}
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto"
import { isIP } from "node:net"
import type { IxSite } from "@mmapp/contracts/internet-exchange"
import type { IxConfiguration, IxSite } from "@mmapp/contracts/internet-exchange"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import { IxConflict } from "./internet-exchange-plan.js"
@@ -12,11 +12,16 @@ export function ixLinuxBindingKind(binding: Binding) {
return null
}
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Binding) {
export function ixLegacyWireguardRoutes(configuration: IxConfiguration, binding: Binding) {
return configuration.sites.flatMap(site => site.interfaces
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
}
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Pick<Binding, "name">) {
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
}
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>") {
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>", transportOnly = false) {
const config = binding.provisionWireguard
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
@@ -29,8 +34,8 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
"[Interface]",
"Address = " + address(config.peerAddress),
"PrivateKey = " + privateKey,
binding.linux ? "Table = auto" : "Table = off",
...(binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
binding.linux && !transportOnly ? "Table = auto" : "Table = off",
...(!transportOnly && 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",
] : []),
@@ -44,7 +49,7 @@ export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string
].join("\n")
}
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string) {
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string, transportOnly = false) {
const hub = binding.localEndpoint
const client = binding.endpoint
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
@@ -68,6 +73,30 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
"swanctl --initiate --child " + id + " --timeout 20",
"ip tunnel add " + greParameters,
]
const addressCommand = tunnel && "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id
const transportSetup = transportOnly && tunnel && [
'conf="$(dirname -- "$0")/' + id + '.conf"',
'unit=/etc/systemd/system/ix-gre-' + id + '.service',
'profile=/etc/swanctl/conf.d/' + id + '.conf',
'if [ ! -r "$conf" ]; then echo "Положите ' + id + '.conf рядом со скриптом."; exit 1; fi',
'candidate=$(mktemp)',
'trap \'rm -f "$candidate"\' EXIT',
'cat >"$candidate" <<\'IX_GRE_UNIT\'',
"[Unit]", "Description=IX Client GRE/IPsec " + id, "Wants=network-online.target", "After=network-online.target strongswan.service",
"Requires=strongswan.service", "[Service]", "Type=oneshot", "RemainAfterExit=yes",
"ExecStartPre=/usr/sbin/swanctl --load-all",
"ExecStart=/bin/sh -ec '/usr/sbin/ip tunnel add " + greParameters + '; trap "/usr/sbin/ip link del dev ' + id +
'" EXIT; /usr/sbin/' + addressCommand + "; /usr/sbin/ip link set " + id + " up; trap - EXIT'",
"ExecStop=/usr/sbin/ip link del dev " + id,
"[Install]", "WantedBy=multi-user.target", "IX_GRE_UNIT",
'if [ -e "$unit" ] && ! cmp -s "$candidate" "$unit"; then echo "Служба уже принадлежит другой конфигурации."; exit 1; fi',
'if [ -e "$profile" ] && ! cmp -s "$conf" "$profile"; then echo "Профиль strongSwan отличается от существующего."; exit 1; fi',
'if [ ! -e "$unit" ] && ip link show dev ' + id + ' >/dev/null 2>&1; then echo "Интерфейс уже существует."; exit 1; fi',
'install -d -m 0700 /etc/swanctl/conf.d',
'if [ ! -e "$profile" ]; then install -m 0600 "$conf" "$profile"; fi',
'install -m 0644 "$candidate" "$unit"',
"systemctl daemon-reload", "systemctl enable --now ix-gre-" + id + ".service",
].join("\n")
return {
filename: id + ".conf",
template: [
@@ -107,7 +136,7 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
"}",
"",
].join("\n"),
setup: (tunnel ? [
setup: transportSetup || (tunnel ? [
'conf="$(dirname -- "$0")/' + id + '.conf"',
'if [ ! -r "$conf" ]; then echo "Положите файл ' + id + '.conf рядом со скриптом" >&2; exit 1; fi',
'if ip link show dev ' + id + ' >/dev/null 2>&1; then echo "GRE уже поднят" >&2; exit 1; fi',
@@ -122,7 +151,7 @@ export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: {
"trap cleanup 0",
...managementRules.map(([ip, selector]) => ip + " rule add pref " + management + " " + selector),
...common,
"ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id,
addressCommand!,
"ip link set " + id + " up",
...[...new Set([
tunnel.localAddress.split("/")[0] + (family === 4 ? "/32" : "/128"),
@@ -9,9 +9,10 @@ import { getServerRowById, type ServerRow } from "../modules/servers/repository/
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.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 { archiveIxSegment, assertIxBondClientAssignments, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, assertIxSegmentWithoutBonds, ixBondClientId, ixKnownVpsClient, ixReservedLinuxPoolBlocks, 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"
import { ixGreClientTemplate, ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
import { ixWireguardPublicKey, type IxExistingTransport } from "@mmapp/contracts/internet-exchange"
type NativeRow = Record<string, string>
type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete">
@@ -260,17 +261,18 @@ export async function assignIxRouterIds(id: string, configuration: IxConfigurati
}
export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) {
if (input.vpsClientId && !await ixKnownVpsClient(input.vpsClientId)) throw new IxConflict("VPS больше не зарегистрирован в применённой конфигурации IX")
if (input.additionalGre && (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4)) {
throw new IxConflict("Для подключения по обоим протоколам укажите два внешних IPv4-адреса", 400)
}
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
const companion = input.companionOf && site?.interfaces.find(binding => binding.name === input.companionOf && binding.linux)
if (input.companionOf && !companion) throw new IxConflict("Исходное подключение Linux не найдено", 404)
const existingId = companion ? companion.linux?.clientId : undefined
if (companion && (companion.kind === input.kind || existingId &&
site?.interfaces.some(binding => binding.linux?.clientId === existingId && binding.kind === input.kind))) {
throw new IxConflict("Этот протокол уже подключён для клиента")
if (input.interfaceName && input.vpsClientId) {
const groupVps = await ixBondClientId(segment.id, input.serverId, input.interfaceName)
if (groupVps && groupVps !== input.vpsClientId) throw new IxConflict("Сначала исключите подключение из действующей группы VPS")
}
const existingId = companion ? companion.linux?.clientId ?? await ixBondClientId(segment.id, input.serverId, companion.name) : undefined
const name = companion ? companion.linux!.name : input.name
const first = await configureIxLinuxTunnel(segment, { ...input, name })
const second = input.additionalGre ? await configureIxLinuxTunnel({ ...segment, configuration: first.configuration }, {
@@ -278,14 +280,14 @@ export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxC
}) : undefined
const result = second ?? first
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
const clientId = existingId ?? currentId ?? (companion || second ? randomUUID() : undefined)
const clientId = existingId ?? input.vpsClientId ?? currentId ?? (companion || second ? randomUUID() : undefined)
if (!clientId) return result
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
return { interfaceName: first.interfaceName, configuration: {
...result.configuration,
sites: result.configuration.sites.map(site => site.serverId !== input.serverId ? site : {
...site, interfaces: site.interfaces.map(binding =>
binding.linux && (siblings.has(binding.name) || binding.linux.clientId === clientId)
binding.linux && (siblings.has(binding.name) || !input.vpsClientId && binding.linux.clientId === clientId)
? { ...binding, linux: { ...binding.linux, name, clientId } } : binding),
}),
} }
@@ -304,11 +306,13 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
let localAddress = input.localAddress ?? currentTunnel?.localAddress
let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress
if (!localAddress && !peerAddress) {
const occupiedBlocks = await ixReservedLinuxPoolBlocks()
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) {
if (occupiedBlocks.has(index)) continue
const base = "10.254." + (index >> 8) + "."
const next = base + ((index & 255) + 1) + "/30"
if (used.some(network => inIxNetwork(network, next) || inIxNetwork(next, network))) continue
@@ -361,6 +365,10 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
localAddress, peerAddress, hubEndpoint: input.hubEndpoint }
} else {
if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400)
if (site.interfaces.some(item => item !== previous && item.kind === "gre-ipsec" &&
item.localEndpoint === input.hubEndpoint && item.endpoint === input.peerEndpoint)) {
throw new IxConflict("Эта пара внешних адресов уже используется для GRE/IPsec")
}
binding.endpoint = input.peerEndpoint
binding.localEndpoint = input.hubEndpoint
binding.provisionGre = { localAddress, peerAddress,
@@ -472,6 +480,59 @@ function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: Nat
return gre
}
/** Inspect operator-owned transports without running the provisioning or VRF planner. */
export async function verifyIxExistingTransport(segmentId: string, serverId: number, name: string, path: IxExistingTransport) {
const client = await requiredIxNode(serverId)
const addrPath = (address: string) => isIP(address) === 4 ? "/ip/address" : "/ipv6/address"
const readAddresses = (ip: string) => readRows(client, addrPath(ip), ["address", "network", "interface", "vrf", "disabled", "invalid"])
const [addresses, vrfs, reserved] = await Promise.all([readAddresses(path.probe), readRows(client, "/ip/vrf", ["name", "interfaces", "disabled"]), ixReservedTunnelBindings(serverId, segmentId)])
if (reserved.some(b => b.name === name)) throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + name)
const sameIP = (a: string | undefined, b: string) => !!a && isIP(a) === isIP(b) &&
inIxNetwork(b + (isIP(b) === 4 ? "/32" : "/128"), a)
const local = addresses.find(row => !isTrue(row.disabled) && !isTrue(row.invalid) && row.interface === name && sameIP(row.address?.split("/")[0], path.probe))
if (!local) throw new IxConflict("Адрес IX для проверки не назначен интерфейсу " + name)
const allowedVrf = (value: string) => value === "main" || value === ixNamespace(segmentId)
if (local.vrf) {
if (!allowedVrf(local.vrf)) throw new IxConflict("Адрес принадлежит другой VRF: " + name)
} else {
const names = new Set((await readRows(client, "/interface", ["name"])).map(row => row.name))
let owner: string | undefined
for (const row of vrfs.filter(v => !isTrue(v.disabled))) {
const selectors = row.interfaces?.split(",") ?? []
if (selectors.some(s => s === name || s === "all")) { owner = row.name; break }
// Older RouterOS may omit address.vrf. An unexpanded list could match before main.
if (selectors.some(s => s !== "none" && !names.has(s))) break
}
if (!owner || !allowedVrf(owner)) throw new IxConflict("Не подтверждена принадлежность интерфейса VRF узла: " + name)
}
if (path.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns)])
const gre = verifyGreBinding({ name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }, interfaces, policies)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс отключён: " + name)
if (!sameIP(local.network, path.address) && !inIxNetwork(local.address, path.address)) {
const routes = await readRows(client, isIP(path.address) === 4 ? "/ip/route" : "/ipv6/route", ["dst-address", "gateway", "immediate-gw", "disabled"])
const host = path.address + (isIP(path.address) === 4 ? "/32" : "/128")
if (!routes.some(r => !isTrue(r.disabled) && r["dst-address"] === host &&
[r.gateway, r["immediate-gw"]].some(gw => gw?.split("@")[0] === name || gw?.split("%")[1]?.split("@")[0] === name))) {
throw new IxConflict("Адрес VPS не подтверждён подсетью или хост-маршрутом GRE: " + name)
}
}
return undefined
}
const [wireguard, peers, outer] = await Promise.all([readRows(client, "/interface/wireguard", ["name", "public-key", "disabled"]),
readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "allowed-address", "disabled"]),
addrPath(path.endpoint) === addrPath(path.probe) ? addresses : readAddresses(path.endpoint)])
if (!outer.some(r => !isTrue(r.disabled) && !isTrue(r.invalid) && r.interface !== name && sameIP(r.address?.split("/")[0], path.endpoint))) {
throw new IxConflict("Внешний адрес WireGuard не найден на узле IX")
}
const hub = wireguard.find(r => r.name === name && !isTrue(r.disabled))
const peer = peers.find(r => r.interface === name && !isTrue(r.disabled) && r["public-key"] === path.clientPublicKey &&
r["allowed-address"]?.split(",").some(cidr => cidr.includes("/") && inIxNetwork(cidr.trim(), path.address)))
if (!peer || !ixWireguardPublicKey.safeParse(hub?.["public-key"]).success) throw new IxConflict("Не подтверждены WireGuard, публичный ключ VPS или allowed-address на " + name)
return hub!["public-key"]
}
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[], knownObjects: IxRouterObject[]) {
for (const site of configuration.sites) {
const device = devices.find(entry => entry.serverId === site.serverId)!
@@ -556,6 +617,7 @@ async function resolveIxCredentials(id: string, objects: IxRouterObject[], exist
}
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null, resume = false): Promise<IxNativeChange> {
if (configuration) await assertIxBondClientAssignments(id, configuration)
for (const site of configuration?.sites ?? []) for (const binding of site.interfaces) {
const wg = binding.provisionWireguard
if (!wg?.credentialId) continue
@@ -615,12 +677,13 @@ async function assertIxResume(id: string, revision: number, native: IxNativeChan
function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) {
const namespace = ixNamespace(id)
const managed = previous.filter(object => object.serverId === device.serverId)
const known = new Set(managed.map(objectMarker))
const known = new Set(managed.filter(object => object.fields.comment).map(objectMarker))
const named = new Set(managed.filter(object => !object.fields.comment && object.fields.name).map(objectMarker))
const interfaces = new Set(managed.filter(object => ["/interface/wireguard", "/interface/bridge", "/ip/vrf"].includes(object.path))
.map(object => object.fields.name))
for (const [path, rows] of Object.entries(device.rows)) {
if (path === "/interface") continue // RouterOS mirrors WireGuard and bridge objects here.
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) &&
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) && !named.has(marker(path, row.name ?? "")) &&
(row.comment?.startsWith(namespace + ":") || row["routing-table"] === namespace ||
[row.interface, row.bridge, row["in-interface"], row["out-interface"], ...(row.gateway?.split(/[@%]/) ?? [])].some(value => interfaces.has(value)) ||
[row["in-interface-list"], row["out-interface-list"]].includes(ixEgressList(id)) ||
@@ -631,6 +694,7 @@ function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouter
}
export async function prepareIxRemoval(id: string, revision: number) {
await assertIxSegmentWithoutBonds(id)
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
assertIxRevision(segment, revision)
@@ -793,7 +857,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
})) }
}
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false): Promise<IxLinuxAccess> {
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = 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)
@@ -825,7 +889,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
}
}
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential) }
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential, transportOnly) }
}
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
@@ -837,8 +901,7 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
}
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))
: ixLegacyWireguardRoutes(configuration, binding)
let privateKey: string | undefined
if (includeCredential) {
const wg = binding.provisionWireguard
@@ -854,7 +917,8 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
...clientInfo,
kind: "wireguard",
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey),
hubPublicKey: iface?.["public-key"],
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey, transportOnly),
}
}
@@ -904,6 +968,7 @@ export async function removeIxSegment(id: string, revision: number, expectedDige
authorize = assertVerifiedConfigurationAccess) {
return withApplicationMutationLock(async () => {
await authorize()
await assertIxSegmentWithoutBonds(id)
const segment = await readIxSegment(id)
assertIxRevision(segment, revision)
const applied = segment?.appliedRevision ? await readIxRevision(id, segment.appliedRevision) : null
@@ -14,7 +14,8 @@ interface SegmentRow {
updated_at: Date
}
const columns = "id,revision,applied_revision,configuration,updated_at"
// VPS bond metadata has its own revision and never enters a RouterOS plan or segment export.
const columns = "id,revision,applied_revision,(configuration - 'linuxBonds') AS configuration,updated_at"
const visible = "(configuration->>'deleted') IS DISTINCT FROM 'true'"
function segment(row: SegmentRow): IxSegment {
return { id: row.id, revision: row.revision, appliedRevision: row.applied_revision,
@@ -41,6 +42,46 @@ export async function isIxSegmentArchived(id: string, revision: number) {
return rowCount === 1
}
export async function assertIxSegmentWithoutBonds(id: string) {
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true'
AND (s.id=$1::uuid OR EXISTS (SELECT FROM jsonb_array_elements(g->'members') m WHERE m->>'segmentId'=$1::text))
LIMIT 1`, [id])
if (rowCount) throw new IxConflict("Сначала исключите сегмент из групп туннелей Linux")
}
export async function ixBondClientId(segmentId: string, serverId: number, interfaceName: string) {
const { rows } = await pool.query<{ id: string }>(`SELECT g->>'clientId' AS id FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND g->'members' @> $1::jsonb LIMIT 1`,
[JSON.stringify([{ segmentId, serverId, interfaceName }])])
return rows[0]?.id
}
export async function ixKnownVpsClient(id: string) {
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND
(s.configuration->'linuxBonds' @> $1::jsonb OR r.configuration->'sites' @> $2::jsonb) LIMIT 1`,
[JSON.stringify([{ clientId: id }]), JSON.stringify([{ interfaces: [{ linux: { clientId: id, enabled: true } }] }])])
return !!rowCount
}
export async function assertIxBondClientAssignments(segmentId: string, configuration: IxConfiguration) {
const assignments = configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux?.clientId
? [{ server_id: site.serverId, iface: binding.name, client_id: binding.linux.clientId }] : []))
if (!assignments.length) return
const { rowCount } = await pool.query(`SELECT 1 FROM ix_segments s
CROSS JOIN LATERAL jsonb_array_elements(s.configuration->'linuxBonds') g
CROSS JOIN LATERAL jsonb_array_elements(g->'members') m
JOIN jsonb_to_recordset($2::jsonb) AS a(server_id bigint, iface text, client_id uuid)
ON m->>'serverId' = a.server_id::text AND m->>'interfaceName' = a.iface
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND m->>'segmentId'=$1 AND g->>'clientId'<>a.client_id::text LIMIT 1`,
[segmentId, JSON.stringify(assignments)])
if (rowCount) throw new IxConflict("Сначала исключите подключение из действующей группы VPS")
}
export async function readIxRevision(id: string, revision: number) {
const { rows: [row] } = await pool.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, revision])
if (!row) throw new IxConflict("Ревизия IX не найдена", 404)
@@ -78,19 +119,36 @@ export async function ixReservedRouterIds(id?: string, sql: Pick<PoolClient, "qu
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'
export async function ixReservedTunnelBindings(serverId: number, excludeSegmentId?: string, sql: Pick<PoolClient, "query"> = pool) {
const { rows } = await sql.query<{ configuration: unknown }>(`
SELECT s.configuration - 'linuxBonds' AS configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
WHERE d.server_id=$1 AND ($2::uuid IS NULL OR s.id<>$2) 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])
WHERE d.server_id=$1 AND ($2::uuid IS NULL OR s.id<>$2) AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
`, [serverId, excludeSegmentId ?? null])
return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites
.flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
}
export async function ixReservedLinuxPoolBlocks() {
const { rows } = await pool.query<{ address: string }>(`
SELECT DISTINCT address
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
CROSS JOIN LATERAL jsonb_array_elements(site->'interfaces') binding
CROSS JOIN LATERAL (VALUES
(split_part(COALESCE(binding->'provisionWireguard'->>'localAddress',binding->'provisionGre'->>'localAddress'),'/',1)),
(COALESCE(binding->'provisionWireguard'->>'peerAddress',binding->'provisionGre'->>'peerAddress'))) hosts(address)
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true' AND binding ? 'linux' AND address LIKE '10.254.%'`)
return new Set(rows.map(row => {
const [, , third, last] = row.address.split(".").map(Number)
return third * 256 + (last & ~3)
}))
}
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)
@@ -134,7 +192,8 @@ export async function writeIxRevision(id: string, expected: number, configuratio
? await client.query<SegmentRow>(`INSERT INTO ix_segments(id,name,revision,configuration,applied_revision)
VALUES ($1,$2,$3,$4::jsonb,$5) ON CONFLICT DO NOTHING RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied ? revision : null])
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb,
: await client.query<SegmentRow>(`UPDATE ix_segments SET name=$2,revision=$3,configuration=$4::jsonb ||
CASE WHEN configuration ? 'linuxBonds' THEN jsonb_build_object('linuxBonds', configuration->'linuxBonds') ELSE '{}'::jsonb END,
applied_revision=CASE WHEN $5::boolean THEN $3 ELSE applied_revision END,updated_at=now()
WHERE id=$1 AND revision=$6 AND ${visible} RETURNING ${columns}`,
[id, configuration.name, revision, JSON.stringify(configuration), applied, expected])
@@ -0,0 +1,42 @@
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { test } from "node:test"
import { ixBondBundleSchema, type IxSite } from "@mmapp/contracts/internet-exchange"
import { ixGreClientTemplate, ixWireguardClientTemplate } from "./internet-exchange-client.js"
const bundle = ixBondBundleSchema.parse(JSON.parse(readFileSync(
new URL("../../../packages/contracts/testdata/ix-bond-v1.json", import.meta.url), "utf8")))
test("the shared ix-client fixture accepts weighted members and rejects overlapping tunnel addresses", () => {
assert.deepEqual(bundle.members.map(path => path.weight), [3, 1])
const changed = structuredClone(bundle)
changed.members[0].probe = changed.members[1].address
assert.equal(ixBondBundleSchema.safeParse(changed).success, false)
const invalidKey = structuredClone(bundle)
invalidKey.members[0].peerPublicKey = "B".repeat(43) + "="
assert.equal(ixBondBundleSchema.safeParse(invalidKey).success, false)
})
test("group transport brings up an encrypted link without claiming routes used by other members", () => {
const [wg, gre] = bundle.members
const linux = { name: bundle.name, enabled: true, exit: "wan", destinations: [], peerEndpoint: "192.0.2.99" }
const binding: IxSite["interfaces"][number] = {
name: "wg-test", kind: "wireguard", linux, prefixes: [], provisionWireguard: {
listenPort: 51820, endpointPort: 51820, localAddress: wg.probe + "/30", peerAddress: wg.address,
hubEndpoint: wg.endpoint, peerPublicKey: wg.peerPublicKey!,
},
}
const wgConfig = ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations, undefined, true)
assert.match(wgConfig, /Table = off/)
assert.doesNotMatch(wgConfig, /PostUp|PreDown/)
assert.match(wgConfig, /0\.0\.0\.0\/0/)
assert.match(ixWireguardClientTemplate(binding, wg.peerPublicKey!, bundle.destinations), /Table = auto/)
const greConfig = ixGreClientTemplate({ name: "gre-test", kind: "gre-ipsec", linux, prefixes: [],
localEndpoint: gre.endpoint, endpoint: linux.peerEndpoint, provisionGre: {
localAddress: gre.probe + "/30", peerAddress: gre.address, credentialId: bundle.id,
} }, 17, undefined, undefined, true)
assert.match(greConfig.template, /start_action = trap/)
assert.match(greConfig.setup, /systemctl enable --now ix-gre-/)
assert.match(greConfig.setup, /ExecStart=.*ip address add 10\.123\.2\.2\/32/)
assert.doesNotMatch(greConfig.setup, /ip -[46] rule|route replace|secret =/)
})
+13 -1
View File
@@ -61,9 +61,21 @@
- **WireGuard.** IX автоматически создаёт пару ключей Linux. После применения скачайте готовый `.conf` из карточки клиента, сохраните под исходным именем в `/etc/wireguard/` с правами `0600` и запустите `sudo wg-quick up <имя-файла-без-.conf>`. Указанный внешний IP Linux сохраняет исходный путь управления при полном туннеле. Для клиента со своей парой ключей доступен шаблон с полем для его приватного ключа.
- **Получение WireGuard через MCP.** Вызовите `mm_wireguard_export_plan` с полями `serverId`, `interfaceName` клиента, `ixSegmentId` и `format: "peer-conf"`. После подтверждения и выполнения плана ссылка на готовый файл доступна авторизованному владельцу подключения 15 минут. Ключ находится только в скачиваемом файле.
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании или выберите **Добавить другой протокол** в действиях клиента. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
- **Два протокола.** Отметьте WireGuard и GRE/IPsec при создании. Для существующего клиента откройте **Доступ и выход**, выберите свободный протокол и нажмите **Добавить туннель**. Туннели имеют отдельные адреса и ключи, входят в одну VRF сегмента на выбранном IX, настраиваются и отключаются отдельно. Для второго туннеля по умолчанию предложен доступ к разрешённым сетям. Если на VPS одновременно запущены оба туннеля с маршрутом по умолчанию, сгенерированные правила GRE направляют обычный трафик через GRE.
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. После применения скачайте конфиг strongSwan и скрипт GRE в одну папку на VPS. На Ubuntu установите `charon-systemd strongswan-swanctl`, запустите `sudo systemctl start strongswan` и выполните показанную в карточке команду `sudo sh ./…-setup.sh`. Скрипт копирует профиль с правами `0600`, устанавливает IKEv2/IPsec, создаёт GRE и использует отдельную таблицу для туннельных маршрутов. Транспорт до IX и ответы с внешнего IPv4 VPS, включая SSH, идут по основной таблице Linux.
### Несколько туннелей на одном VPS
1. В **Linux-клиенты** откройте меню действующего подключения и выберите **Создать группу с этим туннелем**. Интерфейс уже будет первым в списке. Для участника существующей группы это же меню открывает её редактор. Ключи VPS и CHR при создании группы сохраняются. Для нового транспорта откройте меню клиента и скачайте **Конфиг для группы ix-client**.
2. Добавьте второе подключение одного VPS. Старые управляемые подключения без идентификатора VPS можно выбрать вместе, подтвердив их принадлежность одному серверу. Для исправления прежней привязки свободного подключения откройте **Доступ и выход → Привязка к VPS**, выберите VPS и сохраните ревизию. У всех участников должны различаться внутренние IP-адреса VPS и IX и совпадать семейство адресов и сети назначения. В режиме резервирования первым поставьте основной, затем резервы в порядке предпочтения. В параллельном режиме задайте равное распределение или веса. В прямые исключения внесите сети, к которым VPS должен обращаться через WAN.
3. Нажмите **Скачать для ix-client** и импортируйте JSON группы через **B → I**. Если имя интерфейса на VPS отличается от имени в JSON, ix-client сопоставит существующий транспорт по адресам и параметрам пира. Проверьте найденное локальное имя и соответствие туннеля в предварительном просмотре **F2**. Нажмите **Enter** для применения и **Y** для подтверждения. Без подтверждения через 60 секунд восстановится предыдущая конфигурация. Одиночные интерфейсы можно продолжать использовать отдельно.
**Интерфейсы, созданные вручную на CHR и VPS.** Пользователь с правом управления сетью может открыть **Группы туннелей VPS → Создать группу → Добавить из интерфейсов RouterOS** и выбрать узел применённого сегмента и действующий WG или GRE. Укажите фактическое имя интерфейса Linux, внутренние адреса обеих сторон, внешний IP IX и сети назначения. Для WG укажите публичный ключ **VPS**. Manager проверит, что он принадлежит включённому пиру, что его `allowed-address` включает адрес VPS и внешний IP назначен узлу IX. Для GRE укажите внешний IPv4 VPS. Manager сверит пару внешних адресов, выключенный FastPath и обязательную транспортную политику IPsec. Внутренний адрес VPS должен подтверждаться подсетью, адресом point-to-point или отдельным хост-маршрутом через GRE.
При сохранении и экспорте Manager читает RouterOS. Параметры ручного подключения сохраняются в группе, а существующие ключи, VRF, маршруты и интерфейсы CHR продолжают работать. Для межузловых туннелей, BGP-подключений и интерфейсов другой VRF используйте их собственную схему маршрутизации. У ручного подключения оператор указывает назначения, которые уже доступны через IX. При экспорте JSON для WG Manager подставляет публичный ключ CHR. Ручной импорт WG через внешний NAT поддерживает только адреса, назначенные самой CHR. Если публичный адрес есть лишь на вышестоящем NAT, проверка Manager отклонит его.
Фактический активный путь, состояние резервов и распределение соединений видны на VPS в **B → Группы** или в выводе `sudo ix-client bond status`. Клиент раз в секунду посылает ICMP-пробу на внутренний адрес IX через каждый туннель, в том числе в отсутствие пользовательского трафика. Разрешите ответы на эти пробы. После трёх пропущенных ответов клиент исключает путь. Если резерв работает, клиент возвращает новые соединения на основной после 30 секунд устойчивых ответов. Уже открытое соединение через упавший туннель может потребовать переподключения. Ответы на входящие прямые соединения возвращаются через тот WAN, на который пришёл запрос.
### Выход и резерв
**Интернет с этого IX** использует действующий WAN из `main`. WAN остаётся в своей таблице, для клиента на этом выходе добавляются отдельные правила и обратный маршрут. **Добавить удалённый выход** готовит оба конца межузлового WireGuard с возвратом и IPv4 SNAT на целевом IX или ExitNode. Такой выход доступен в карточке клиента как группа шлюзов. В конфигурации группы можно выбрать другой интерфейс резерва или взять параметры заранее подготовленного выхода.
@@ -1,4 +1,6 @@
import { z } from "zod"
export * from "./ix-bond-management.js"
export * from "./ix-bond.js"
const key = z.string().regex(/^[a-z][a-z0-9-]{0,23}$/)
const interfaceName = z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/)
@@ -141,6 +143,7 @@ export const ixLinuxClientRequest = z.object({
enabled: z.boolean().default(true),
kind: z.enum(["wireguard", "gre-ipsec"]),
additionalGre: z.boolean().optional(),
vpsClientId: z.uuid().optional(),
companionOf: interfaceName.optional(),
hubEndpoint: address,
peerEndpoint: address.optional(),
@@ -154,6 +157,8 @@ export const ixLinuxClientRequest = z.object({
rotate: z.boolean().optional(),
}).strict().refine(input => !input.transit || !input.exit || input.exit === input.transit.name,
{ path: ["exit"], message: "Выход клиента должен совпадать с выбранным транзитом" })
.refine(input => !input.vpsClientId || !input.companionOf,
"Новый туннель наследует VPS исходного подключения.")
.refine(input => (!input.companionOf || !input.interfaceName) &&
(!input.additionalGre || input.kind === "wireguard" && !input.interfaceName && !input.companionOf),
"Оба протокола можно создать для нового клиента. Для существующего добавьте второй протокол.")
@@ -215,6 +220,7 @@ export interface IxLinuxBinding {
}
export interface IxLinuxAccess {
hubPublicKey?: string
kind: IxLinuxBinding["kind"]
revision: number
filename: string
@@ -0,0 +1,46 @@
import { z } from "zod"
import { ixBondModeSchema, ixWireguardPublicKey } from "./ix-bond.js"
const ip = z.union([z.ipv4(), z.ipv6()])
const existing = z.object({
linuxInterface: z.string().regex(/^[a-zA-Z0-9_=-][a-zA-Z0-9_.=-]{0,14}$/),
address: ip, probe: ip, endpoint: ip,
destinations: z.array(z.union([z.cidrv4(), z.cidrv6()])).min(1).max(64),
})
export const ixExistingTransportSchema = z.discriminatedUnion("kind", [
existing.extend({ kind: z.literal("wireguard"), clientPublicKey: ixWireguardPublicKey }).strict(),
existing.extend({ kind: z.literal("gre-ipsec"), endpoint: z.ipv4(), remoteEndpoint: z.ipv4() }).strict(),
]).refine(path => path.address.includes(":") === path.probe.includes(":") && path.address !== path.probe &&
path.destinations.every(cidr => cidr.includes(":") === path.address.includes(":")), "Проверьте внутренние адреса и семейство назначений")
export type IxExistingTransport = z.infer<typeof ixExistingTransportSchema>
const memberRef = z.object({
segmentId: z.uuid(), serverId: z.number().int().positive().safe(),
interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/),
appliedRevision: z.number().int().positive().safe(), weight: z.number().int().min(1).max(100),
existing: ixExistingTransportSchema.optional(),
}).strict()
export const ixBondEditSchema = z.object({
id: z.uuid().optional(), revision: z.number().int().nonnegative().safe(),
name: z.string().trim().min(1).max(80).regex(/^[^\x00-\x1f\x7f]+$/), mode: ixBondModeSchema,
directCidrs: z.array(z.union([z.cidrv4(), z.cidrv6()])).max(64),
members: z.array(memberRef).min(2).max(16),
}).strict().refine(value => !!value.id === (value.revision > 0), "Укажите текущую ревизию группы")
export type IxBondEdit = z.infer<typeof ixBondEditSchema>
export const ixSavedBondSchema = ixBondEditSchema.safeExtend({
id: z.uuid(), revision: z.number().int().positive().safe(), clientId: z.uuid(), ownerSegmentId: z.uuid(),
})
export type IxSavedBond = z.infer<typeof ixSavedBondSchema>
export interface IxBondCandidate extends Omit<IxBondEdit["members"][number], "weight"> {
segmentName: string
clientId?: string
name: string
kind: "wireguard" | "gre-ipsec"
endpoint: string
address: string
probe: string
destinations: string[]
}
export interface IxBondCatalog { groups: IxSavedBond[]; candidates: IxBondCandidate[] }
+50
View File
@@ -0,0 +1,50 @@
import { z } from "zod"
const ip = z.union([z.ipv4(), z.ipv6()])
const cidr = z.union([z.cidrv4(), z.cidrv6()])
export const ixWireguardPublicKey = z.string().regex(/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/)
.refine(key => key !== "A".repeat(43) + "=", "Недопустимый нулевой ключ WireGuard")
export const ixBondModeSchema = z.enum(["failover", "equal", "weighted"])
const member = z.object({
interfaceName: z.string().regex(/^[a-zA-Z0-9_=-][a-zA-Z0-9_.=-]{0,14}$/),
kind: z.enum(["wireguard", "gre-ipsec"]),
address: ip,
probe: ip,
endpoint: ip,
weight: z.number().int().min(1).max(100),
// A 32-byte WireGuard key ends with two zero padding bits and one '='.
peerPublicKey: ixWireguardPublicKey.optional(),
}).strict()
export const ixBondBundleSchema = z.object({
version: z.literal(1),
id: z.string().uuid(),
revision: z.number().int().positive().safe(),
clientId: z.string().uuid(),
name: z.string().trim().min(1).max(80).regex(/^[^\x00-\x1f\x7f]+$/),
mode: ixBondModeSchema,
destinations: z.array(cidr).min(1).max(64),
directCidrs: z.array(cidr).max(64),
members: z.array(member).min(2).max(16),
}).strict().superRefine((group, ctx) => {
const problem = (message: string) => ctx.addIssue({ code: "custom", message })
const names = new Set<string>()
const hosts = new Set<string>()
const ipv6 = group.destinations[0]?.includes(":")
if (group.destinations.some(prefix => prefix.includes(":") !== ipv6)) problem("Назначения должны быть одного семейства")
for (const path of group.members) {
if (names.has(path.interfaceName)) problem("Интерфейс повторяется в группе")
names.add(path.interfaceName)
for (const address of [path.address, path.probe]) {
if (address.includes(":") !== ipv6) problem("Адрес туннеля и назначения должны быть одного семейства")
const canonical = ipv6 && z.ipv6().safeParse(address).success ? new URL("http://[" + address + "]").hostname : address
if (hosts.has(canonical)) problem("Внутренние адреса путей должны быть уникальны")
hosts.add(canonical)
}
if (path.kind === "gre-ipsec" && path.peerPublicKey) problem("Ключ WireGuard указан для GRE")
}
})
export type IxBondMode = z.infer<typeof ixBondModeSchema>
export type IxBondBundle = z.infer<typeof ixBondBundleSchema>
export type IxBondMember = z.infer<typeof member>
+14
View File
@@ -0,0 +1,14 @@
{
"version": 1,
"id": "50b82c5c-4ada-4ffd-a907-510dce60ac50",
"revision": 1,
"clientId": "6761aeb0-7b3d-45f0-9bea-c6166839490b",
"name": "vps-01",
"mode": "weighted",
"destinations": ["0.0.0.0/0"],
"directCidrs": ["203.0.113.64/27"],
"members": [
{"interfaceName": "wg-ix-a", "kind": "wireguard", "address": "10.123.1.2", "probe": "10.123.1.1", "endpoint": "192.0.2.2", "weight": 3, "peerPublicKey": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="},
{"interfaceName": "gre-ix-b", "kind": "gre-ipsec", "address": "10.123.2.2", "probe": "10.123.2.1", "endpoint": "198.51.100.2", "weight": 1}
]
}
+127 -10
View File
@@ -1,6 +1,6 @@
import { readFile } from "node:fs/promises"
import { expect, test } from "@playwright/test"
import { ixChangeSchema, ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
import { ixBondEditSchema, ixChangeSchema, ixSegmentConfigurationSchema, type IxSavedBond } from "@mmapp/contracts/internet-exchange"
const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
const observedAt = "2026-11-20T00:00:00Z"
@@ -9,6 +9,86 @@ const nodes = [
{ id: 2, name: "ix-node-02", site: "TEST-2", country: "FI", enabled: true },
]
test("IX: сборка группы VPS из двух площадок с весами и исключением WAN", async ({ page }) => {
const remote = "0b59555b-c920-4b74-b350-977309a4b84a"
const segments = [id, remote].map((segmentId, i) => ({
id: segmentId, revision: 1, appliedRevision: 1, updatedAt: observedAt,
configuration: ixSegmentConfigurationSchema.parse({ name: "site-" + (i + 1),
sites: [{ serverId: nodes[i].id, autonomousSystem: 64512, routerId: "192.0.2." + (i + 1), interfaces: i ? [] : [
{ name: "gre-local", kind: "gre-ipsec", localEndpoint: "192.0.2.1", endpoint: "198.51.100.2" },
] }] }),
}))
const candidates = segments.map((s, i) => ({ segmentId: s.id, serverId: nodes[i].id,
interfaceName: i ? "gre-vps" : "wg-vps", appliedRevision: 1, segmentName: s.configuration.name, name: "vps",
kind: i ? "gre-ipsec" : "wireguard", endpoint: "192.0.2." + (i + 1), address: "10.0." + i + ".2", probe: "10.0." + i + ".1", destinations: ["0.0.0.0/0"] }))
let groups: IxSavedBond[] = []
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const p = new URL(route.request().url()).pathname
const json = (body: unknown) => route.fulfill({ json: body })
if (p === "/api/auth/config") return json({ required: false })
if (p === "/api/ix/nodes") return json({ items: nodes })
if (p === "/api/ix/nodes/1/inventory") return json({ observedAt, routerId: "192.0.2.1", defaultRoutes: [], wireguardPorts: [],
interfaces: [{ name: "wg-console", type: "wg", running: true, disabled: false, restriction: null, addresses: ["10.8.0.1/30"] },
{ name: "gre-local", type: "gre-tunnel", running: true, disabled: false, restriction: null, addresses: ["10.9.0.1/30"] }] })
if (p === "/api/ix/segments") return json({ items: segments })
if (p === "/api/ix/segments/" + id + "/linux") return json({ items: [{ serverId: 1, kind: "wireguard", interfaceName: "wg-vps" },
{ serverId: 1, kind: "gre-ipsec", interfaceName: "gre-local" }], revision: 1 })
if (p === "/api/ix/linux-bonds") return json({ groups, candidates })
if (p === "/api/ix/segments/" + id + "/linux-bonds") {
const body = ixBondEditSchema.parse(route.request().postDataJSON())
expect(body.members.slice(0, 2).map(m => [m.segmentId, m.weight])).toEqual([[remote, 3], [id, 1]])
if (body.id) expect(body.members[2].existing).toMatchObject({ kind: "wireguard", linuxInterface: "wg0", address: "10.8.0.2",
probe: "10.8.0.1", endpoint: "192.0.2.1", destinations: ["0.0.0.0/0"] })
expect(body.directCidrs).toEqual(["192.0.2.0/24"])
groups = [{ ...body, id: remote, revision: body.revision + 1, clientId: id, ownerSegmentId: id }]
return json(groups[0])
}
return json({ items: [], revision: 1 })
})
await page.goto("/ix")
await page.getByRole("button", { name: "site-1", exact: true }).click()
await page.getByRole("button", { name: "Действия клиента wg-vps" }).click()
await page.getByRole("menuitem", { name: "Создать группу с этим туннелем" }).click()
const editor = page.getByRole("dialog", { name: "Группа туннелей VPS" })
await expect(editor.getByLabel("Имя группы")).toHaveValue("vps")
await expect(editor.getByText(/1\. vps .*wg-vps/)).toBeVisible()
await editor.getByLabel("Имя группы").fill("vps-01")
await editor.getByLabel("Режим", { exact: true }).click()
await page.getByRole("option", { name: "Параллельно, по весам" }).click()
await editor.getByLabel("Добавить туннель этого VPS").click()
await expect(page.getByRole("option", { name: /wg-vps/ })).toHaveCount(0)
await page.getByRole("option", { name: /gre-vps/ }).click()
await editor.getByRole("button", { name: "Выше" }).last().click()
await editor.getByLabel("Вес", { exact: true }).first().fill("3")
await editor.getByLabel("Прямой выход для сетей (CIDR)").fill("192.0.2.0/24")
await expect(editor.getByRole("button", { name: "Сохранить" })).toBeDisabled()
await editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" }).check()
await editor.getByRole("button", { name: "Сохранить" }).click()
await expect(page.getByText("vps-01 · Параллельно, по весам")).toBeVisible()
await expect(page.getByRole("button", { name: "Скачать для ix-client" })).toBeVisible()
await page.getByRole("button", { name: "Действия клиента wg-vps" }).click()
await page.getByRole("menuitem", { name: "Открыть группу «vps-01»" }).click()
await expect(editor.getByLabel("Имя группы")).toHaveValue("vps-01")
await expect(editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" })).toHaveCount(0)
await editor.getByRole("button", { name: "Добавить из интерфейсов RouterOS" }).click()
await editor.getByLabel("Интерфейс RouterOS").click()
await page.getByRole("option", { name: "wg-console" }).click()
await editor.getByLabel("Имя интерфейса на VPS").fill("wg0")
await editor.getByLabel("Адрес VPS внутри туннеля").fill("10.8.0.2")
await editor.getByLabel("Внешний адрес IX", { exact: true }).fill("192.0.2.1")
await editor.getByLabel("Публичный ключ WireGuard VPS").fill(Buffer.alloc(32, 23).toString("base64"))
await editor.getByRole("button", { name: "Включить в список" }).click()
await editor.getByRole("checkbox", { name: "Подтверждаю, что выбранные интерфейсы настроены на одном VPS" }).check()
await editor.getByRole("button", { name: "Сохранить" }).click()
await expect(page.getByText(/Вес 1 · wg0 .*wg-console/)).toBeVisible()
await page.getByRole("button", { name: "Действия клиента gre-local" }).click()
await page.getByRole("menuitem", { name: "Создать группу с этим туннелем" }).click()
await expect(editor.getByLabel("Интерфейс RouterOS")).toContainText("gre-local")
await expect(editor.getByLabel("Адрес IX внутри туннеля")).toContainText("10.9.0.1")
await expect(editor.getByLabel("Внешний IPv4 VPS")).toBeVisible()
})
test("IX: редактирование и применение сохранённой ревизии из WebUI без MCP", async ({ page }, testInfo) => {
const configuration = ixSegmentConfigurationSchema.parse({ name: "ix-central", sites: [
{ serverId: 1, autonomousSystem: 64512, routerId: "192.0.2.10", interfaces: [{ name: "wg-member", kind: "wireguard" }] },
@@ -24,6 +104,7 @@ test("IX: редактирование и применение сохранён
const path = new URL(request.url()).pathname
const json = (body: unknown) => route.fulfill({ json: body })
if (path === "/api/auth/config") return json({ required: false })
if (path === "/api/ix/linux-bonds") return json({ groups: [], candidates: [] })
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 }] })
@@ -146,6 +227,7 @@ test("IX: черновик удаляется после подтвержден
const path = new URL(request.url()).pathname
if (path === "/api/auth/config") return route.fulfill({ json: { required: false } })
if (path === "/api/ix/nodes") return route.fulfill({ json: { items: nodes } })
if (path === "/api/ix/linux-bonds") return route.fulfill({ json: { groups: [], candidates: [] } })
if (path === "/api/ix/segments") return route.fulfill({ json: { items: deleted ? [] : [draft] } })
if (path === `/api/ix/segments/${id}/removal-plan`) {
expect(request.postDataJSON()).toEqual({ revision: 1 })
@@ -187,6 +269,7 @@ 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[0]] })
if (path === "/api/ix/linux-bonds") return json({ groups: [], candidates: [] })
if (path === "/api/ix/segments" && req.method() === "POST") {
const change = ixChangeSchema.parse(req.postDataJSON())
expect(change.configuration.sites[0]).toMatchObject({ serverId: 1, autoRouterId: true })
@@ -228,6 +311,7 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
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
let extended = false
const clientId = "6677cc81-0ac8-48fd-902a-cecd0ce8633a"
const configFile = "[Interface]\nPrivateKey = TEST_PRIVATE_KEY\n[Peer]\nAllowedIPs = 0.0.0.0/0\n"
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
@@ -236,6 +320,7 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
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/linux-bonds") return json({ groups: [], candidates: [] })
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: [],
@@ -243,6 +328,21 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
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") {
if (req.postDataJSON().companionOf) {
expect(req.postDataJSON()).toMatchObject({ revision: 3, serverId: 1, name: "vps-01", kind: "gre-ipsec",
companionOf: "il-vps", hubEndpoint: "192.0.2.11", peerEndpoint: "123.123.123.123", prefixes: [], destinations: [] })
expect(req.postDataJSON()).not.toHaveProperty("interfaceName")
expect(req.postDataJSON()).not.toHaveProperty("exit")
const site = segment.configuration.sites[0]
segment = { ...segment, revision: 4, configuration: ixSegmentConfigurationSchema.parse({
...segment.configuration, sites: [{ ...site, interfaces: [
{ ...site.interfaces[0], linux: { ...site.interfaces[0].linux, clientId } },
{ name: "il-gre", kind: "gre-ipsec", linux: { name: "vps-01", enabled: true, destinations: [], clientId } },
] }],
}) }
extended = true
return json({ segment, interfaceName: "il-gre" })
}
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")
@@ -263,22 +363,24 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
if (path === `/api/ix/segments/${id}/linux/credential`) {
expect(req.method()).toBe("POST")
if (req.postDataJSON().interfaceName === "il-gre") {
expect(both).toBe(true)
expect(both || extended).toBe(true)
return json({ kind: "gre-ipsec", revision: 3, filename: "vps-gre.conf", template: "secret = TEST_PSK", setup: "ip tunnel add vps-gre mode gre" })
}
expect(req.postDataJSON()).toEqual({ serverId: 1, interfaceName: "il-vps" })
return json({ kind: "wireguard", revision: 3, filename: "vps.conf", template: configFile })
}
if (path === `/api/ix/segments/${id}/linux`) {
return json({ revision: segment.appliedRevision, items: segment.appliedRevision === 3 && client ? [
client, ...(both ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
return json({ revision: segment.appliedRevision, items: segment.appliedRevision >= 3 && client ? [
client, ...(both || segment.appliedRevision === 5 ? [{ name: "vps-01", kind: "gre-ipsec", serverId: 1, interfaceName: "il-gre",
policy: segment.configuration.sites[0].interfaces[1].linux }] : []),
] : [] })
}
if (path.endsWith("/plan")) return json({ revision: 2, digest, changes: [{ serverId: 1, action: "create", path: "/interface/wireguard", fields: {} }] })
if (path.endsWith("/plan")) return json({ revision: segment.revision, digest, changes: [
{ serverId: 1, action: "create", path: extended ? "/interface/gre" : "/interface/wireguard", fields: {} },
] })
if (path.endsWith("/apply")) {
expect(req.postDataJSON()).toEqual({ revision: 2, digest })
segment = { ...segment, revision: 3, appliedRevision: 3 }
expect(req.postDataJSON()).toEqual({ revision: extended ? 4 : 2, digest })
segment = { ...segment, revision: segment.revision + 1, appliedRevision: segment.revision + 1 }
return json({ segment })
}
expect(path.startsWith("/api/mcp/")).toBe(false)
@@ -334,10 +436,25 @@ for (const mode of ["WAN IX", "два протокола", "новый ExitNode"
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveCount(1)
await expect(page.getByRole("option", { name: /Через exit-arn/ })).toHaveAttribute("aria-selected", "true")
} else {
await page.getByRole("button", { name: "Действия клиента vps-01" }).click()
await page.getByRole("menuitem", { name: "Добавить другой протокол" }).click()
await editExit.click()
await page.getByLabel("Имя клиента").fill("Несохранённое имя")
const gre = protocols.getByRole("button", { name: "GRE/IPsec" })
await expect(gre).toBeEnabled()
await gre.click()
await expect(page.getByRole("heading", { name: "Добавить другой протокол" })).toBeVisible()
await expect(page.getByLabel("Имя клиента")).toHaveValue("vps-01")
await expect(page.getByLabel("Внешний адрес Linux")).toHaveValue("123.123.123.123")
await expect(protocols.getByRole("button", { name: "GRE/IPsec" })).toHaveAttribute("aria-pressed", "true")
await expect(gre).toHaveAttribute("aria-pressed", "true")
await expect(protocols.getByRole("button", { name: "WireGuard" })).toHaveAttribute("aria-pressed", "true")
await gre.click()
await expect(page.getByLabel("Имя клиента")).toHaveValue("Несохранённое имя")
await gre.click()
await page.getByRole("button", { name: "Добавить туннель", exact: true }).click()
const dialog = page.getByRole("dialog", { name: "Подтвердите сохранение" })
await expect(dialog.getByText("/interface/gre", { exact: true })).toBeVisible()
await dialog.getByRole("button", { name: "Подтвердить" }).click()
await expect(page.getByRole("button", { name: "Получить конфиг vps-01 · GRE/IPsec", exact: true })).toBeVisible()
await expect(page.getByRole("button", { name: "Получить конфиг vps-01 · WireGuard", exact: true })).toBeVisible()
expect(segment.configuration.sites[0].interfaces[0].linux?.exit).toBe("ix-wan4")
}
})