Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9f623ccda | ||
|
|
9951035448 | ||
|
|
95be5178d0 | ||
|
|
c9152bb106 | ||
|
|
ef3d7b6779 | ||
|
|
e11e67b3a1 | ||
|
|
be1cb6381a | ||
|
|
4900101b5e | ||
|
|
6f235c700a | ||
|
|
d422050a4b |
No files matched your search
@@ -252,7 +252,7 @@ function generateCombinedRouterOSConfig(
|
||||
|
||||
// ── shared components ──────────────────────────────────────────────────────────
|
||||
|
||||
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) {
|
||||
function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
|
||||
return (
|
||||
<span className={cn(
|
||||
"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0",
|
||||
@@ -261,7 +261,7 @@ function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" })
|
||||
? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20"
|
||||
: "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
|
||||
)}>
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"}
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { serverTypeSchema } from "@mmapp/contracts/servers"
|
||||
import { can } from "@/lib/auth"
|
||||
|
||||
import { z } from "zod"
|
||||
@@ -174,7 +175,7 @@ function mapBackendServer(s: BackendServer): InventoryServer {
|
||||
const ipsecInventorySchema = z.array(z.object({
|
||||
id: z.number().int().positive(), name: z.string(), host: z.string(), enabled: z.boolean(),
|
||||
country: z.string().optional().default("UN"),
|
||||
type: z.enum(["jump-host", "exit-node", "home-router"]).optional(),
|
||||
type: serverTypeSchema.optional(),
|
||||
status: z.enum(["online", "offline", "degraded"]).nullable().optional(),
|
||||
latency: z.number().nullable().optional(), asn: z.string().optional(),
|
||||
})).refine(rows => new Set(rows.map(row => row.id)).size === rows.length)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import type { IxNodeInventory, IxSegment, IxTransitRequest } from "@mmapp/contracts/internet-exchange"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
export function publicEndpoint(inventory?: IxNodeInventory) {
|
||||
if (!inventory) return ""
|
||||
const wan = new Set(inventory.defaultRoutes.filter(route => route.family === 4).map(route => route.interface))
|
||||
const addresses = new Set(inventory.interfaces.filter(iface => !iface.disabled && wan.has(iface.name))
|
||||
.flatMap(iface => iface.addresses.filter(address => !address.includes(":")).map(address => address.split("/")[0])))
|
||||
return addresses.size === 1 ? [...addresses][0] : ""
|
||||
}
|
||||
|
||||
export function transitName(segment: IxSegment, serverId: number, target: number, family: 4 | 6) {
|
||||
const used = segment.configuration.sites.find(site => site.serverId === serverId)?.groups ?? []
|
||||
const base = "via-" + target.toString(36) + "-v" + family
|
||||
let name = base
|
||||
for (let i = 2; used.some(group => group.id === name); i++) name = base + "-" + i
|
||||
return name
|
||||
}
|
||||
|
||||
function TransitEditor({ segment, nodes, backendUrl, busy, save, cancel }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean
|
||||
save: (input: IxTransitRequest) => void; cancel: () => void
|
||||
}) {
|
||||
const [serverId, setServerId] = useState(segment.configuration.sites[0].serverId)
|
||||
const [targetServerId, setTargetServerId] = useState(0)
|
||||
const [local, setLocal] = useState("")
|
||||
const [remote, setRemote] = useState("")
|
||||
const [name, setName] = useState("")
|
||||
const [probe, setProbe] = useState("")
|
||||
const [family, setFamily] = useState<4 | 6>(4)
|
||||
const origin = useIxNodeInventory(backendUrl, serverId, segment.id)
|
||||
const target = useIxNodeInventory(backendUrl, targetServerId, segment.id)
|
||||
const localEndpoint = local || publicEndpoint(origin.inventory)
|
||||
const remoteEndpoint = remote || publicEndpoint(target.inventory)
|
||||
const exitName = name || transitName(segment, serverId, targetServerId, family)
|
||||
const sourceChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
.map(node => ({ value: String(node.id), label: node.name + (node.type === "ix-node" ? " · IX" : " · ExitNode") }))
|
||||
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
if (!busy && targetServerId && localEndpoint && remoteEndpoint && exitName) {
|
||||
save({ revision: segment.revision, name: exitName, serverId, targetServerId, localEndpoint, remoteEndpoint, family, probe: probe || undefined })
|
||||
}
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4">
|
||||
{sourceChoices.length > 1 && <Field><FieldLabel htmlFor="ix-egress-source">Узел входа</FieldLabel>
|
||||
<Select items={sourceChoices} value={String(serverId)} onValueChange={value => {
|
||||
if (value) { setServerId(Number(value)); setTargetServerId(0); setLocal(""); setRemote("") }
|
||||
}}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-source"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{sourceChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>}
|
||||
<Field><FieldLabel htmlFor="ix-egress-target">Выходной узел</FieldLabel>
|
||||
<Select items={targets} value={targetServerId ? String(targetServerId) : null}
|
||||
onValueChange={value => { setTargetServerId(Number(value)); setRemote("") }}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-target"><SelectValue placeholder="Другой IX или ExitNode" /></SelectTrigger>
|
||||
<SelectContent>{targets.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<details key={serverId + ":" + targetServerId + ":" + (origin.loading || target.loading)} open={!!targetServerId && (!publicEndpoint(origin.inventory) || !publicEndpoint(target.inventory)) && !origin.loading && !target.loading}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-egress-name">Имя выхода</FieldLabel>
|
||||
<Input id="ix-egress-name" value={exitName} pattern="[a-z][a-z0-9-]{0,23}" onChange={event => setName(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-local">Внешний IPv4 узла входа</FieldLabel>
|
||||
<Input id="ix-egress-local" value={localEndpoint} required onChange={event => setLocal(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-remote">Внешний IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-egress-remote" value={remoteEndpoint} required onChange={event => setRemote(event.target.value)} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-probe">Контрольный адрес</FieldLabel>
|
||||
<Input id="ix-egress-probe" value={probe} placeholder="Адрес второго конца туннеля" onChange={event => setProbe(event.target.value)} />
|
||||
<FieldDescription>Для проверки выхода за пределами туннеля укажите доступную цель за удалённым узлом.</FieldDescription>
|
||||
</Field>
|
||||
<Field><FieldLabel htmlFor="ix-egress-family">Семейство трафика</FieldLabel>
|
||||
<Select value={String(family)} items={[{ value: "4", label: "IPv4" }, { value: "6", label: "IPv6" }]}
|
||||
onValueChange={value => { setFamily(value === "6" ? 6 : 4); setProbe("") }}>
|
||||
<SelectTrigger className="w-full" id="ix-egress-family"><SelectValue /></SelectTrigger>
|
||||
<SelectContent><SelectItem value="4">IPv4</SelectItem><SelectItem value="6">IPv6</SelectItem></SelectContent>
|
||||
</Select>
|
||||
{family === 6 && <FieldDescription>Для выхода в Интернет IPv6 нужен маршрутизируемый префикс Linux с обратным маршрутом до выходной CHR.</FieldDescription>}
|
||||
</Field>
|
||||
</div>
|
||||
</details>
|
||||
{(origin.error || target.error) && <p role="status" className="text-sm text-muted-foreground">{origin.error ?? target.error}</p>}
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button type="submit" disabled={busy || !targetServerId || !localEndpoint || !remoteEndpoint}>Сохранить</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
}
|
||||
|
||||
export function IxExits({ segment, nodes, backendUrl, busy, error, save }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; busy: boolean; error: string
|
||||
save: (input: IxTransitRequest) => Promise<boolean>
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
return <>
|
||||
<Button size="sm" className="w-fit" disabled={busy} onClick={() => setOpen(true)}>Добавить удалённый выход</Button>
|
||||
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
|
||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
||||
<SheetHeader><SheetTitle>Удалённый выход</SheetTitle>
|
||||
<SheetDescription>WireGuard, обратные маршруты и IPv4 SNAT будут подготовлены на обоих узлах.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
</SheetHeader>
|
||||
{open && <TransitEditor segment={segment} nodes={nodes} backendUrl={backendUrl} busy={busy}
|
||||
save={input => void save(input).then(success => { if (success) setOpen(false) })} cancel={() => setOpen(false)} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||
import { EllipsisIcon, PencilIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
|
||||
import type { IxLinuxBinding, IxLinuxClientRequest, IxSegment, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
|
||||
import { Frame, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { publicEndpoint, transitName } from "./ix-exits"
|
||||
import { nodeLabel, useIxNodeInventory, type IxNode } from "./ix-view"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
type FormState = {
|
||||
serverId: number
|
||||
name: string
|
||||
kind: IxLinuxClientRequest["kind"]
|
||||
hub: string
|
||||
peer: string
|
||||
key: string
|
||||
localAddress: string
|
||||
peerAddress: string
|
||||
prefixes: string
|
||||
destinations: string
|
||||
exit: string
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
const lines = (value: string) => value.split(/[,\n]/).map(line => line.trim()).filter(Boolean)
|
||||
|
||||
function groupLabel(group: IxSite["groups"][number], site: IxSite, nodes: IxNode[]) {
|
||||
const target = site.interfaces.find(binding => binding.name === group.primary.interface)?.peerServerId
|
||||
const label = target ? "Через " + nodeLabel(nodes, target) : group.primary.viaMain ? "Интернет с этого IX" : group.id
|
||||
return [label, group.backup && "с резервом"].filter(Boolean).join(" · ")
|
||||
}
|
||||
|
||||
function ClientForm({ segment, edit, nodes, backendUrl, busy, save, cancel }: {
|
||||
segment: IxSegment; edit: { site: IxSite; binding: Binding } | null; nodes: IxNode[]; backendUrl: string
|
||||
busy: boolean; save: (input: IxLinuxClientRequest) => Promise<void>; cancel: () => void
|
||||
}) {
|
||||
const binding = edit?.binding
|
||||
const [form, setForm] = useState<FormState>(() => ({
|
||||
serverId: edit?.site.serverId ?? segment.configuration.sites[0].serverId,
|
||||
name: binding?.linux?.name ?? "", kind: binding?.kind === "gre-ipsec" ? "gre-ipsec" : "wireguard",
|
||||
hub: binding?.localEndpoint ?? binding?.provisionWireguard?.hubEndpoint ?? "",
|
||||
peer: binding?.linux?.peerEndpoint ?? binding?.endpoint ?? "",
|
||||
key: binding?.provisionWireguard?.credentialId ? "" : binding?.provisionWireguard?.peerPublicKey ?? "",
|
||||
localAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.localAddress ?? "",
|
||||
peerAddress: (binding?.provisionWireguard ?? binding?.provisionGre)?.peerAddress ?? "",
|
||||
prefixes: binding?.prefixes.join("\n") ?? "", destinations: binding?.linux?.destinations.join("\n") ?? "",
|
||||
exit: binding?.linux?.exit ?? "isolated", enabled: binding?.linux?.enabled ?? true,
|
||||
}))
|
||||
const [rotate, setRotate] = useState(false)
|
||||
const origin = useIxNodeInventory(backendUrl, form.serverId, segment.id)
|
||||
const [transitLocal, setTransitLocal] = useState("")
|
||||
const [transitRemote, setTransitRemote] = useState("")
|
||||
const site = segment.configuration.sites.find(site => site.serverId === form.serverId)
|
||||
const suggested = publicEndpoint(origin.inventory)
|
||||
const targetId = form.exit.startsWith("remote:") ? Number(form.exit.slice(7)) : 0
|
||||
const target = useIxNodeInventory(backendUrl, targetId, segment.id)
|
||||
const localEndpoint = transitLocal.trim() || suggested || (form.hub.includes(":") ? "" : form.hub.trim())
|
||||
const remoteEndpoint = transitRemote.trim() || publicEndpoint(target.inventory)
|
||||
const family = form.peerAddress.includes(":") ? 6 : 4
|
||||
const patch = (fields: Partial<FormState>) => setForm(value => ({ ...value, ...fields }))
|
||||
const nodeChoices = segment.configuration.sites.map(site => ({ value: String(site.serverId), label: nodeLabel(nodes, site.serverId) }))
|
||||
const transports = [{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec (IKEv2)" }]
|
||||
const groups = site?.groups.filter(group => group.onFailure === "block" && group.gateway.includes(":") === (family === 6)) ?? []
|
||||
const local = groups.find(group => group.id === "ix-wan" + family && group.primary.viaMain)
|
||||
const targets = nodes.filter(node => node.enabled && node.id !== form.serverId && ["ix-node", "exit-node"].includes(node.type ?? ""))
|
||||
const exits = [
|
||||
{ value: "isolated", label: "Только разрешённые сети" },
|
||||
{ value: local?.id ?? "local-wan", label: local ? groupLabel(local, site!, nodes) : "Интернет с этого IX" },
|
||||
...groups.filter(group => group !== local).map(group => ({ value: group.id, label: groupLabel(group, site!, nodes) + " · " + group.id })),
|
||||
...targets.filter(node => !groups.some(group => site?.interfaces.some(link => link.name === group.primary.interface && link.peerServerId === node.id)))
|
||||
.map(node => ({ value: "remote:" + node.id, label: "Через " + node.name + (node.type === "exit-node" ? " · ExitNode" : " · IX") })),
|
||||
]
|
||||
const valid = !!form.name.trim() && !!(form.hub || suggested) && (form.kind === "wireguard" || !!form.peer) &&
|
||||
(!targetId || !!localEndpoint && !!remoteEndpoint) && exits.some(exit => exit.value === form.exit)
|
||||
const destinationsField = <Field><FieldLabel htmlFor="ix-linux-destinations">Разрешённые сети IX</FieldLabel>
|
||||
<Textarea id="ix-linux-destinations" rows={2} value={form.destinations} placeholder="По одному CIDR на строку" onChange={event => patch({ destinations: event.target.value })} />
|
||||
<FieldDescription>Перечислите префиксы для доступа через IX, например 10.2.0.0/24.</FieldDescription></Field>
|
||||
return <form className="flex min-h-0 flex-1 flex-col" onSubmit={event => {
|
||||
event.preventDefault()
|
||||
if (!valid || busy) return
|
||||
void save({
|
||||
revision: segment.revision, serverId: form.serverId, interfaceName: binding?.name, name: form.name,
|
||||
kind: form.kind, hubEndpoint: form.hub.trim() || suggested, peerEndpoint: form.peer.trim() || undefined,
|
||||
peerPublicKey: form.kind === "wireguard" ? form.key.trim() || undefined : undefined,
|
||||
localAddress: form.localAddress.trim() || undefined, peerAddress: form.peerAddress.trim() || undefined,
|
||||
prefixes: lines(form.prefixes), destinations: lines(form.destinations), exit: form.exit === "isolated" || targetId ? undefined : form.exit,
|
||||
transit: targetId ? { targetServerId: targetId, name: transitName(segment, form.serverId, targetId, family), family,
|
||||
localEndpoint, remoteEndpoint } : undefined,
|
||||
enabled: form.enabled, rotate,
|
||||
})
|
||||
}}>
|
||||
<div className="grid min-h-0 gap-4 overflow-y-auto px-4 pb-4">
|
||||
<Field><FieldLabel htmlFor="ix-linux-name">Имя клиента</FieldLabel>
|
||||
<Input id="ix-linux-name" value={form.name} placeholder="vps-01" required onChange={event => patch({ name: event.target.value })} /></Field>
|
||||
{nodeChoices.length > 1 && <Field><FieldLabel htmlFor="ix-linux-node">Узел IX</FieldLabel>
|
||||
<Select value={String(form.serverId)} items={nodeChoices} disabled={!!edit}
|
||||
onValueChange={value => value && patch({ serverId: Number(value), hub: "", exit: "isolated" })}>
|
||||
<SelectTrigger id="ix-linux-node" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{nodeChoices.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>}
|
||||
<Field><FieldLabel htmlFor="ix-linux-transport">Туннель</FieldLabel>
|
||||
<Select value={form.kind} items={transports} disabled={!!edit}
|
||||
onValueChange={value => (value === "wireguard" || value === "gre-ipsec") && patch({ kind: value })}>
|
||||
<SelectTrigger id="ix-linux-transport" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{transports.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-peer">Внешний адрес Linux</FieldLabel>
|
||||
<Input id="ix-linux-peer" value={form.peer} placeholder="123.123.123.123" required={form.kind === "gre-ipsec"} onChange={event => patch({ peer: event.target.value })} />
|
||||
<FieldDescription>{form.kind === "gre-ipsec" ? "Фиксированный IPv4 на стороне VPS для GRE/IPsec." : form.exit === "isolated"
|
||||
? "Для WireGuard это поле необязательно." : "Укажите публичный IP VPS, чтобы сохранить доступ по SSH при выходе через IX."}</FieldDescription></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-exit">Выход трафика</FieldLabel>
|
||||
<Select value={form.exit} items={exits} onValueChange={value => { if (value) { patch({ exit: value }); setTransitLocal(""); setTransitRemote("") } }}>
|
||||
<SelectTrigger id="ix-linux-exit" className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>{exits.map(item => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
{!!targetId && <FieldDescription>IX создаст туннель до {nodeLabel(nodes, targetId)} для выхода в Интернет.</FieldDescription>}
|
||||
</Field>
|
||||
{!!targetId && !publicEndpoint(target.inventory) && (target.loading ? <p role="status" className="text-sm text-muted-foreground">Читаем WAN выходного узла…</p> :
|
||||
<Field><FieldLabel htmlFor="ix-transit-target">IPv4 выходного узла</FieldLabel>
|
||||
<Input id="ix-transit-target" value={transitRemote} onChange={event => setTransitRemote(event.target.value)} />
|
||||
<FieldDescription>Укажите адрес интерфейса CHR для межузлового туннеля.</FieldDescription></Field>)}
|
||||
{!!targetId && !suggested && !origin.loading && <Field><FieldLabel htmlFor="ix-transit-source">IPv4 узла IX для транзита</FieldLabel>
|
||||
<Input id="ix-transit-source" value={localEndpoint} onChange={event => setTransitLocal(event.target.value)} /></Field>}
|
||||
{form.exit === "isolated" && destinationsField}
|
||||
<details className="grid gap-3" key={form.serverId + ":" + origin.loading}
|
||||
open={!origin.loading && !suggested && !binding?.provisionWireguard?.hubEndpoint && !binding?.localEndpoint}>
|
||||
<summary className="cursor-pointer text-sm font-medium">Параметры туннеля</summary>
|
||||
<div className="mt-3 grid gap-3">
|
||||
<Field><FieldLabel htmlFor="ix-linux-hub">Внешний адрес IX</FieldLabel>
|
||||
<Input id="ix-linux-hub" value={form.hub || suggested} onChange={event => patch({ hub: event.target.value })} />
|
||||
<FieldDescription>{origin.loading ? "Читаем адрес WAN с CHR…" : suggested ? "Адрес WAN для подключения VPS." : "Введите адрес IX, доступный с VPS."}</FieldDescription>
|
||||
</Field>
|
||||
{form.kind === "wireguard" && <Field><FieldLabel htmlFor="ix-linux-key">Публичный ключ Linux</FieldLabel>
|
||||
<Input id="ix-linux-key" value={form.key} placeholder="Создать автоматически" onChange={event => patch({ key: event.target.value })} />
|
||||
<FieldDescription>Укажите ключ только для своей пары WireGuard.</FieldDescription></Field>}
|
||||
{form.exit !== "isolated" && destinationsField}
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-local">Адрес IX в туннеле (CIDR)</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-local" value={form.localAddress} placeholder="Автоматический IPv4" onChange={event => patch({ localAddress: event.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-tunnel-peer">Адрес Linux в туннеле</FieldLabel>
|
||||
<Input id="ix-linux-tunnel-peer" value={form.peerAddress} placeholder="Автоматический IPv4" onChange={event => patch({ peerAddress: event.target.value })} /></Field>
|
||||
<Field><FieldLabel htmlFor="ix-linux-prefixes">Сети за Linux</FieldLabel>
|
||||
<Textarea id="ix-linux-prefixes" rows={2} value={form.prefixes} onChange={event => patch({ prefixes: event.target.value })} /></Field>
|
||||
</div>
|
||||
</details>
|
||||
{edit && <div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant={form.enabled ? "outline" : "secondary"} aria-pressed={!form.enabled}
|
||||
onClick={() => patch({ enabled: !form.enabled })}>{form.enabled ? "Приостановить доступ" : "Возобновить доступ"}</Button>
|
||||
{form.kind === "gre-ipsec" && <Button type="button" size="sm" variant={rotate ? "secondary" : "outline"}
|
||||
aria-pressed={rotate} onClick={() => setRotate(!rotate)}>Выпустить новый PSK</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
<SheetFooter>{form.kind === "wireguard" && !form.key && <p className="text-sm text-muted-foreground">После подтверждения можно скачать готовый файл WireGuard для Linux.</p>}
|
||||
<Button type="submit" disabled={!valid || busy}>Сохранить</Button>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>Отмена</Button></SheetFooter>
|
||||
</form>
|
||||
}
|
||||
|
||||
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect }: {
|
||||
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
|
||||
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
|
||||
view: (binding: IxLinuxBinding) => void; revoke: (binding: IxLinuxBinding) => void
|
||||
inspect: (binding: IxLinuxBinding) => void
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [edit, setEdit] = useState<{ site: IxSite; binding: Binding } | null>(null)
|
||||
const rows = useMemo(() => {
|
||||
const saved = segment.configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.linux ? [{
|
||||
serverId: site.serverId, interfaceName: binding.name, kind: binding.kind as IxLinuxBinding["kind"],
|
||||
policy: binding.linux, name: binding.linux.name, enabled: binding.linux.enabled,
|
||||
connection: applied.find(item => item.serverId === site.serverId && item.interfaceName === binding.name)?.connection,
|
||||
}] : []))
|
||||
return [...saved, ...applied.filter(binding => !saved.some(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName))]
|
||||
}, [segment, applied])
|
||||
const columns = useMemo<ColumnDef<DataGridFeatures, IxLinuxBinding>[]>(() => [
|
||||
{ id: "name", header: "Клиент", size: 170, cell: ({ row }) => <div className="grid gap-0.5">
|
||||
<span className="font-medium">{row.original.name ?? row.original.interfaceName}</span>
|
||||
<span className="text-xs text-muted-foreground">{nodeLabel(nodes, row.original.serverId)}</span>
|
||||
</div> },
|
||||
{ id: "transport", header: "Туннель", size: 105, cell: ({ row }) => row.original.kind === "wireguard" ? "WireGuard" : "GRE/IPsec" },
|
||||
{ id: "egress", header: "Выход трафика", size: 205, cell: ({ row }) => {
|
||||
const client = row.original
|
||||
const site = segment.configuration.sites.find(item => item.serverId === client.serverId)
|
||||
const binding = site?.interfaces.find(item => item.name === client.interfaceName)
|
||||
const group = site?.groups.find(item => item.id === client.policy?.exit)
|
||||
const label = site && group ? groupLabel(group, site, nodes) : client.policy ? client.policy.exit ?? "Только сети IX" : "По настройкам интерфейса"
|
||||
return readOnly || !site || !binding?.linux ? label : <Button type="button" size="sm" variant="link" className="max-w-full"
|
||||
disabled={busy} aria-label={"Доступ и выход клиента " + client.name} onClick={() => { setEdit({ site, binding }); setOpen(true) }}>
|
||||
<span className="truncate">{label}</span><PencilIcon aria-hidden />
|
||||
</Button>
|
||||
} },
|
||||
{ id: "state", header: "Состояние", size: 160, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
if (!binding.policy) return <Badge variant="secondary">Прежняя настройка</Badge>
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName)
|
||||
const site = segment.configuration.sites.find(item => item.serverId === binding.serverId)
|
||||
if (!site?.interfaces.some(item => item.name === binding.interfaceName)) return <Badge variant="warning-light">Ожидает отзыва</Badge>
|
||||
if (!live || JSON.stringify(binding.policy) !== JSON.stringify(live.policy)) return <Badge variant="warning-light">Ожидает сохранения</Badge>
|
||||
if (!binding.enabled) return <Badge variant="secondary">Приостановлен</Badge>
|
||||
return binding.connection?.state === "connected" ? <div className="grid gap-1">
|
||||
<Badge variant="success-light" className="w-fit">Подключён</Badge>
|
||||
{binding.connection.rx !== undefined && <span className="text-xs text-muted-foreground">RX {binding.connection.rx} · TX {binding.connection.tx}</span>}
|
||||
</div>
|
||||
: <Badge variant="secondary">{binding.connection?.state === "waiting" ? "Ожидает туннель" : "Нет данных"}</Badge>
|
||||
} },
|
||||
{ id: "actions", header: "Действия", size: 140, cell: ({ row }) => {
|
||||
const binding = row.original
|
||||
const site = segment.configuration.sites.find(site => site.serverId === binding.serverId)
|
||||
const saved = site?.interfaces.find(candidate => candidate.name === binding.interfaceName)
|
||||
const live = applied.find(item => item.serverId === binding.serverId && item.interfaceName === binding.interfaceName && item.enabled !== false)
|
||||
return <div className="flex flex-wrap gap-1">
|
||||
{live && <Button size="sm" variant="outline" disabled={busy} aria-label={"Получить конфиг " + (binding.name ?? binding.interfaceName)}
|
||||
onClick={() => view(live)}>Конфиг Linux</Button>}
|
||||
{binding.policy && (live || !readOnly && saved?.linux) && <DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button type="button" size="icon-sm" variant="ghost" disabled={busy} aria-label={"Действия клиента " + binding.name} />}>
|
||||
<EllipsisIcon aria-hidden />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{live && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
|
||||
{!readOnly && saved?.linux && <DropdownMenuItem variant="destructive" onClick={() => revoke(binding)}>Отозвать доступ…</DropdownMenuItem>}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>}
|
||||
</div>
|
||||
} },
|
||||
], [nodes, applied, segment.configuration.sites, readOnly, busy, view, revoke, inspect])
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns,
|
||||
getRowId: row => row.serverId + ":" + row.interfaceName })
|
||||
return <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<FrameTitle>Linux-клиенты</FrameTitle>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="icon-sm" variant="outline" aria-label="Обновить клиентов" disabled={busy || !segment.appliedRevision} onClick={refresh}><RefreshCwIcon /></Button>
|
||||
{!readOnly && <Button type="button" size="sm" disabled={busy} onClick={() => { setEdit(null); setOpen(true) }}><PlusIcon />Подключить Linux</Button>}
|
||||
</div>
|
||||
</FrameHeader>
|
||||
<FramePanel className="min-w-0 p-0">
|
||||
<DataGridShell table={table} recordCount={rows.length} isLoading={busy && !rows.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
|
||||
</FramePanel>
|
||||
<Sheet open={open} onOpenChange={value => !busy && setOpen(value)}>
|
||||
<SheetContent className="data-[side=right]:w-full data-[side=right]:sm:max-w-lg" showCloseButton={!busy}>
|
||||
<SheetHeader><SheetTitle>{edit ? "Доступ и выход клиента" : "Подключить Linux"}</SheetTitle>
|
||||
<SheetDescription>Укажите VPS и выберите, куда направлять его трафик.</SheetDescription>
|
||||
{error && <p className="text-sm text-destructive" role="alert">{error}</p>}
|
||||
</SheetHeader>
|
||||
{open && <ClientForm segment={segment} edit={edit} nodes={nodes} backendUrl={backendUrl} busy={busy}
|
||||
save={async input => { if (await save(input)) setOpen(false) }} cancel={() => setOpen(false)} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</Frame>
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
"use client"
|
||||
|
||||
import { useId, useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { PlusIcon, XIcon } from "lucide-react"
|
||||
import type { IxNodeInventory, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
type Group = IxSite["groups"][number]
|
||||
type Path = Group["primary"]
|
||||
type Peer = IxSite["neighbors"][number]
|
||||
type Choice = { value: string; label: string; disabled?: boolean }
|
||||
|
||||
function TextField({ label, value, edit, numeric, placeholder }: {
|
||||
label: string; value: string | number; edit: (value: string) => void; numeric?: boolean; placeholder?: string
|
||||
}) {
|
||||
const id = useId()
|
||||
return <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
<Input id={id} value={value} inputMode={numeric ? "numeric" : undefined} placeholder={placeholder}
|
||||
onChange={event => { if (!numeric || /^\d*$/.test(event.target.value)) edit(event.target.value) }} />
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Pick<T extends string>({ label, value, options, edit, disabled }: {
|
||||
label: string; value?: T; options: readonly { value: T; label: string; disabled?: boolean }[]; edit: (value: T) => void; disabled: boolean
|
||||
}) {
|
||||
const id = useId()
|
||||
return <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
<Select value={value ?? null} items={options} disabled={disabled}
|
||||
onValueChange={next => { if (next !== null) edit(next) }}>
|
||||
<SelectTrigger className="w-full" id={id}><SelectValue placeholder="Выберите значение" /></SelectTrigger>
|
||||
<SelectContent>{options.map(item => <SelectItem key={item.value} value={item.value} disabled={item.disabled}>{item.label}</SelectItem>)}</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Flag({ label, checked, edit, disabled }: {
|
||||
label: string; checked: boolean; edit: (value: boolean) => void; disabled: boolean
|
||||
}) {
|
||||
const id = useId()
|
||||
return <Field orientation="horizontal" className="w-fit">
|
||||
<Checkbox id={id} checked={checked} onCheckedChange={edit} disabled={disabled} />
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Lines({ label, value, edit }: { label: string; value: string[]; edit: (value: string[]) => void }) {
|
||||
const id = useId()
|
||||
return <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={id}>{label}</FieldLabel>
|
||||
<Textarea id={id} value={value.join("\n")} rows={2} placeholder="По одному префиксу на строку"
|
||||
onChange={event => edit(event.target.value.split("\n"))}
|
||||
onBlur={event => edit(event.target.value.split("\n").map(line => line.trim()).filter(Boolean))} />
|
||||
</Field>
|
||||
}
|
||||
|
||||
function Entries<T>({ title, items, edit, make, addLabel, max, readOnly, children, label, visible }: {
|
||||
title: string; items: T[]; edit: (items: T[]) => void; make: () => T
|
||||
addLabel: string; max: number; readOnly: boolean; children: (item: T, edit: (item: T) => void) => ReactNode
|
||||
label?: (item: T) => string; visible?: (item: T) => boolean
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState<number | null>(null)
|
||||
const rows = items.map((item, index) => ({ item, index })).filter(({ item }) => !visible || visible(item))
|
||||
return <section className="grid min-w-0 gap-2 border-t py-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium">{title} <span className="text-muted-foreground">· {rows.length}</span></h4>
|
||||
{!readOnly && <Button type="button" variant="outline" size="sm" disabled={items.length >= max}
|
||||
onClick={() => { setExpanded(items.length); edit([...items, make()]) }}><PlusIcon aria-hidden />{addLabel}</Button>}
|
||||
</div>
|
||||
{rows.map(({ item, index }) => <div key={index} className="min-w-0 border-s-2 ps-3">
|
||||
<Button type="button" size="sm" variant="ghost" aria-expanded={expanded === index}
|
||||
onClick={() => setExpanded(expanded === index ? null : index)}>{label?.(item) || "Запись " + (index + 1)}</Button>
|
||||
{expanded === index && <fieldset disabled={readOnly} className="grid gap-3 py-2">
|
||||
{children(item, update => edit(items.map((entry, position) => position === index ? update : entry)))}
|
||||
{!readOnly && <Button type="button" size="sm" className="w-fit" variant="ghost" aria-label={title + " — удалить запись " + (index + 1)}
|
||||
onClick={() => { setExpanded(null); edit(items.filter((_, position) => position !== index)) }}><XIcon aria-hidden />Удалить</Button>}
|
||||
</fieldset>}
|
||||
</div>)}
|
||||
</section>
|
||||
}
|
||||
|
||||
const columns = "grid min-w-0 gap-3 sm:grid-cols-2"
|
||||
const none = {value: "", label: "Нет"}
|
||||
const emptyPath = (name: string): Path => ({ interface: name, nextHop: "", probe: "" })
|
||||
const emptyWireGuard = { peerPublicKey: "", listenPort: 51820, localAddress: "", peerAddress: "" }
|
||||
const kinds = [
|
||||
{ value: "wireguard", label: "WireGuard" }, { value: "gre-ipsec", label: "GRE/IPsec" }, { value: "uplink", label: "Аплинк" },
|
||||
] as const
|
||||
|
||||
function InterfaceFields({ value, edit, peers, readOnly, segmentName, inventory }: {
|
||||
value: Binding; edit: (value: Binding) => void; peers: Choice[]; readOnly: boolean; segmentName: string
|
||||
inventory: IxNodeInventory["interfaces"]
|
||||
}) {
|
||||
const wireGuard = value.provisionWireguard
|
||||
const choices = inventory.filter(item => item.name === value.name || value.kind === "uplink" ||
|
||||
(value.kind === "wireguard" ? ["wg", "wireguard"] : ["gre", "gre-tunnel"]).includes(item.type))
|
||||
.map(item => ({ value: item.name, label: [item.name, item.addresses.join(", "), item.restriction].filter(Boolean).join(" · "),
|
||||
disabled: item.name !== value.name && (item.disabled || !!item.restriction) }))
|
||||
if (value.name && !choices.some(item => item.value === value.name)) choices.unshift({ value: value.name, label: value.name, disabled: false })
|
||||
return <>
|
||||
<div className={columns}>
|
||||
{wireGuard || !inventory.length ? <TextField label="Имя интерфейса" value={value.name} edit={name => edit({ ...value, name })} />
|
||||
: <Pick label="Интерфейс CHR" value={value.name || undefined} options={choices} disabled={readOnly}
|
||||
edit={name => edit({ ...value, name })} />}
|
||||
<Pick label="Тип подключения" value={value.kind} options={kinds} disabled={readOnly}
|
||||
edit={kind => edit({ ...value, kind, ...(kind !== "wireguard" && {provisionWireguard: undefined}), ...(kind !== "uplink" && {natIpv4: undefined}) })} />
|
||||
<Pick label="Удалённый узел" value={value.peerServerId ? String(value.peerServerId) : ""} options={[{ value: "", label: "Внешний сервер" }, ...peers]} disabled={readOnly}
|
||||
edit={id => edit({ ...value, peerServerId: id ? Number(id) : undefined })} />
|
||||
<TextField label="Локальный внешний адрес" value={value.localEndpoint ?? ""} edit={address => edit({ ...value, localEndpoint: address || undefined })} />
|
||||
<TextField label="Удалённый внешний адрес" value={value.endpoint ?? ""} edit={address => edit({ ...value, endpoint: address || undefined })} />
|
||||
</div>
|
||||
<Lines label="Префиксы подключения" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
|
||||
{value.kind === "gre-ipsec" && <p className="text-sm text-muted-foreground">
|
||||
Создайте выделенный туннель в разделе <Link className="underline" href="/gre">GRE-туннели</Link>.
|
||||
Укажите комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>, включите IPsec и отключите FastPath.
|
||||
IX проверит обязательную транспортную политику GRE между указанными IPv4-адресами.
|
||||
</p>}
|
||||
{(value.kind === "uplink" || (value.kind === "wireguard" && !wireGuard)) && <p className="text-sm text-muted-foreground">
|
||||
Для подключения существующего интерфейса выделите его под этот сегмент и задайте комментарий <code>IX:{segmentName || "<имя сегмента>"}</code>.
|
||||
</p>}
|
||||
{value.kind === "uplink" && <Flag label="NAT IPv4" checked={!!value.natIpv4} disabled={readOnly} edit={natIpv4 => edit({ ...value, natIpv4 })} />}
|
||||
{value.kind === "wireguard" && <Flag label="Создать интерфейс и пир WireGuard на узле IX" checked={!!wireGuard} disabled={readOnly}
|
||||
edit={enabled => edit({ ...value, provisionWireguard: enabled ? { ...emptyWireGuard } : undefined })} />}
|
||||
{wireGuard && <div className={columns}>
|
||||
<TextField label="Публичный ключ пира" value={wireGuard.peerPublicKey} edit={peerPublicKey => edit({ ...value, provisionWireguard: { ...wireGuard, peerPublicKey } })} />
|
||||
<TextField label="Порт WireGuard на IX" numeric value={wireGuard.listenPort || ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, listenPort: Number(port) } })} />
|
||||
<TextField label="Локальный адрес туннеля (CIDR)" value={wireGuard.localAddress} edit={localAddress => edit({ ...value, provisionWireguard: { ...wireGuard, localAddress } })} />
|
||||
<TextField label="Адрес пира в туннеле" value={wireGuard.peerAddress} edit={peerAddress => edit({ ...value, provisionWireguard: { ...wireGuard, peerAddress } })} />
|
||||
<TextField label="Внешний адрес IX для шаблона Linux" value={wireGuard.hubEndpoint ?? ""} edit={address => edit({ ...value, provisionWireguard: { ...wireGuard, hubEndpoint: address || undefined } })} />
|
||||
<TextField label="Порт удалённого WireGuard" numeric value={wireGuard.endpointPort ?? ""} edit={port => edit({ ...value, provisionWireguard: { ...wireGuard, endpointPort: port ? Number(port) : undefined } })} />
|
||||
</div>}
|
||||
</>
|
||||
}
|
||||
|
||||
function PathFields({ title, value, edit, interfaces, inventory, readOnly }: {
|
||||
title: string; value: Path; edit: (value: Path) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]; readOnly: boolean
|
||||
}) {
|
||||
const choices = value.viaMain ? inventory.filter(item => !interfaces.some(choice => choice.value === item.name) && !item.disabled)
|
||||
.map(item => ({ value: item.name, label: item.name })) : [...interfaces]
|
||||
if (value.interface && !choices.some(item => item.value === value.interface)) choices.unshift({ value: value.interface, label: value.interface })
|
||||
return <fieldset className="grid min-w-0 gap-3 rounded-md border p-3 sm:grid-cols-3">
|
||||
<legend className="px-1 text-sm font-medium">{title}</legend>
|
||||
<div className="sm:col-span-3"><Flag label="WAN из таблицы main" checked={!!value.viaMain} disabled={readOnly}
|
||||
edit={viaMain => edit({ ...emptyPath(""), viaMain })} /></div>
|
||||
<Pick label="Интерфейс пути" value={value.interface || undefined} options={choices} edit={name => edit({ ...value, interface: name })} disabled={readOnly} />
|
||||
<TextField label="Адрес следующего шлюза" value={value.nextHop} edit={nextHop => edit({ ...value, nextHop })} />
|
||||
<TextField label="Контрольный адрес" value={value.probe} edit={probe => edit({ ...value, probe })} />
|
||||
</fieldset>
|
||||
}
|
||||
|
||||
function GroupFields({ value, edit, interfaces, inventory, alternatives, readOnly }: {
|
||||
value: Group; edit: (value: Group) => void; interfaces: Choice[]; inventory: IxNodeInventory["interfaces"]
|
||||
alternatives: Group[]; readOnly: boolean
|
||||
}) {
|
||||
const selectedBackup = alternatives.find(other => other.primary.interface === value.backup?.interface &&
|
||||
other.primary.nextHop === value.backup?.nextHop && other.primary.probe === value.backup?.probe)
|
||||
return <>
|
||||
<Pick label="Резервный выход" value={value.backup ? selectedBackup?.id ?? ":manual" : ""} disabled={readOnly}
|
||||
options={[none, ...alternatives.map(other => ({ value: other.id, label: other.id })), { value: ":manual", label: "Указать другой шлюз" }]}
|
||||
edit={id => edit({ ...value, backup: id === ":manual" ? emptyPath(interfaces.find(item => item.value !== value.primary.interface)?.value ?? "")
|
||||
: alternatives.find(other => other.id === id)?.primary })} />
|
||||
<div className={columns}>
|
||||
<TextField label="Имя группы шлюзов" value={value.id} edit={id => edit({ ...value, id })} />
|
||||
<TextField label="Служебный адрес шлюза" value={value.gateway} edit={gateway => edit({ ...value, gateway })} />
|
||||
<Pick label="Если оба пути недоступны" value={value.onFailure} disabled={readOnly} options={[
|
||||
{value: "block", label: "Отбрасывать трафик"}, {value: "segment-exit", label: "Использовать выход сегмента"},
|
||||
]} edit={onFailure => edit({ ...value, onFailure })} />
|
||||
</div>
|
||||
<PathFields title="Основной путь" value={value.primary} interfaces={interfaces} inventory={inventory} readOnly={readOnly} edit={primary => edit({ ...value, primary })} />
|
||||
{value.backup && <PathFields title="Резервный путь" value={value.backup} interfaces={interfaces} inventory={inventory}
|
||||
readOnly={readOnly} edit={backup => edit({ ...value, backup })} />}
|
||||
</>
|
||||
}
|
||||
|
||||
function PeerFields({ value, edit, interfaces, groups, readOnly }: {
|
||||
value: Peer; edit: (value: Peer) => void; interfaces: Choice[]; groups: Choice[]; readOnly: boolean
|
||||
}) {
|
||||
const publicFeed = value.type === "public-feed"
|
||||
return <>
|
||||
<div className={columns}>
|
||||
<TextField label="Имя BGP-соседа" value={value.id} edit={id => edit({ ...value, id })} />
|
||||
<Pick label="Тип BGP-соседа" value={value.type} disabled={readOnly} options={[
|
||||
{value: "member", label: "Участник IX"}, {value: "exchange", label: "Вторая площадка"}, {value: "public-feed", label: "Публичный фид"},
|
||||
]} edit={type => edit({ ...value, type, ...(type === "public-feed" ? { group: undefined, exportPrefixes: [] } : { rules: [] }) })} />
|
||||
<TextField label="Адрес BGP-соседа" value={value.address} edit={address => edit({ ...value, address })} />
|
||||
<TextField label="Локальный адрес BGP" value={value.localAddress} edit={localAddress => edit({ ...value, localAddress })} />
|
||||
<TextField label="ASN соседа" numeric value={value.remoteAs || ""} edit={asn => edit({ ...value, remoteAs: Number(asn) })} />
|
||||
<Pick label="Интерфейс BGP" value={value.binding} options={interfaces} disabled={readOnly} edit={binding => edit({ ...value, binding })} />
|
||||
<Pick label="Лимит префиксов" value={String(value.limit)} options={[10, 100, 1000, 10000].map(limit => ({value: String(limit), label: String(limit)}))}
|
||||
disabled={readOnly} edit={limit => edit({ ...value, limit: Number(limit) as Peer["limit"] })} />
|
||||
{!publicFeed && <Pick label="Группа шлюзов для импорта" value={value.group} options={groups} disabled={readOnly} edit={group => edit({ ...value, group })} />}
|
||||
</div>
|
||||
<Lines label="Префиксы импорта" value={value.prefixes} edit={prefixes => edit({ ...value, prefixes })} />
|
||||
{publicFeed
|
||||
? <Entries title="Правила по BGP community" items={value.rules} edit={rules => edit({ ...value, rules })}
|
||||
make={() => ({ community: "", group: groups[0]?.value ?? "" })} max={100} addLabel="Добавить правило" readOnly={readOnly}>
|
||||
{(rule, update) => <div className={columns}>
|
||||
<TextField label="BGP community" value={rule.community} placeholder="65000:10" edit={community => update({ ...rule, community })} />
|
||||
<Pick label="Группа шлюзов правила" value={rule.group} options={groups} edit={group => update({ ...rule, group })} disabled={readOnly} />
|
||||
</div>}
|
||||
</Entries>
|
||||
: <Lines label="Префиксы экспорта" value={value.exportPrefixes} edit={exportPrefixes => edit({ ...value, exportPrefixes })} />}
|
||||
</>
|
||||
}
|
||||
|
||||
export function IxSiteEditor({ site, edit, peers, readOnly, segmentName, inventory }: {
|
||||
site: IxSite; edit: (fields: Partial<IxSite>) => void; peers: Choice[]; readOnly: boolean; segmentName: string
|
||||
inventory: IxNodeInventory["interfaces"]
|
||||
}) {
|
||||
const interfaces = site.interfaces.filter(item => item.name).map(item => ({ value: item.name, label: item.name }))
|
||||
const groups = site.groups.filter(item => item.id).map(item => ({ value: item.id, label: item.id }))
|
||||
return <div className="grid min-w-0 gap-2">
|
||||
<Entries<Binding> title="Интерфейсы маршрутизации" label={item => item.name} visible={item => !item.linux && !item.provisionTransit} items={site.interfaces} edit={interfaces => edit({ interfaces })}
|
||||
make={() => ({ name: "", kind: "wireguard", prefixes: [] })} max={80} addLabel="Добавить интерфейс" readOnly={readOnly}>
|
||||
{(value, update) => <InterfaceFields value={value} edit={update} peers={peers} readOnly={readOnly} segmentName={segmentName} inventory={inventory} />}
|
||||
</Entries>
|
||||
<Entries<Group> title="Выходы и резерв" label={item => item.id} items={site.groups} edit={groups => edit({ groups })}
|
||||
make={() => ({ id: "", gateway: "", primary: emptyPath(interfaces[0]?.value ?? ""), onFailure: "block" })}
|
||||
max={24} addLabel="Добавить группу шлюзов" readOnly={readOnly}>
|
||||
{(value, update) => <GroupFields value={value} edit={update} interfaces={interfaces} inventory={inventory}
|
||||
alternatives={site.groups.filter(group => group.id !== value.id && group.primary.interface !== value.primary.interface &&
|
||||
group.gateway.includes(":") === value.gateway.includes(":"))} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<Entries title="Статические маршруты" label={item => item.prefix} items={site.routes} edit={routes => edit({ routes })}
|
||||
make={() => ({ prefix: "", group: groups[0]?.value ?? "" })} max={250} addLabel="Добавить маршрут" readOnly={readOnly}>
|
||||
{(route, update) => <div className={columns}>
|
||||
<TextField label="Префикс маршрута" value={route.prefix} edit={prefix => update({ ...route, prefix })} />
|
||||
<Pick label="Группа шлюзов маршрута" value={route.group} options={groups} edit={group => update({ ...route, group })} disabled={readOnly} />
|
||||
</div>}
|
||||
</Entries>
|
||||
<Entries<Peer> title="BGP-соседи" label={item => item.id} items={site.neighbors} edit={neighbors => edit({ neighbors })} max={16} addLabel="Добавить BGP-соседа" readOnly={readOnly}
|
||||
make={() => ({ id: "", type: "member", address: "", localAddress: "", remoteAs: 0,
|
||||
binding: interfaces[0]?.value ?? "", group: groups[0]?.value, prefixes: [], exportPrefixes: [], rules: [], limit: 1000 })}>
|
||||
{(value, update) => <PeerFields value={value} edit={update} interfaces={interfaces} groups={groups} readOnly={readOnly} />}
|
||||
</Entries>
|
||||
<details className="rounded-lg border">
|
||||
<summary className="cursor-pointer px-3 py-2 text-sm font-medium">Выходы по умолчанию и маршруты отбрасывания</summary>
|
||||
<fieldset disabled={readOnly} className="grid gap-3 border-t p-3">
|
||||
{[0, 1].map(index => <Pick key={index} label={"Группа выхода " + (index + 1)} value={site.exits[index] ?? ""}
|
||||
options={[none, ...groups.filter(group => group.value !== site.exits[1 - index])]} disabled={readOnly}
|
||||
edit={id => { const exits = [...site.exits]; exits[index] = id; edit({ exits: exits.filter(Boolean) }) }} />)}
|
||||
<Lines label="Префиксы отбрасывания" value={site.discardNetworks} edit={discardNetworks => edit({ discardNetworks })} />
|
||||
</fieldset>
|
||||
</details>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { type ColumnDef, useTable } from "@tanstack/react-table"
|
||||
import { FileTextIcon, PlusIcon, XIcon } from "lucide-react"
|
||||
import type { IxConfiguration, IxNodeInventory, IxSegment, IxSite, IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
|
||||
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { IxSiteEditor } from "./ix-site-editor"
|
||||
|
||||
export type IxNode = { id: number; name: string; site: string; country: string; enabled: boolean; type?: string }
|
||||
type Route = IxSiteObservation["routes"][number]
|
||||
|
||||
export const nodeLabel = (nodes: readonly IxNode[], id: number) => nodes.find(node => node.id === id)?.name || `Узел ${id}`
|
||||
export const newSite = (): IxSite => ({
|
||||
serverId: 0, autonomousSystem: 64512, routerId: "", autoRouterId: true,
|
||||
interfaces: [], groups: [], exits: [], routes: [], neighbors: [], discardNetworks: [],
|
||||
})
|
||||
|
||||
export function SegmentStatus({ segment }: { segment: IxSegment }) {
|
||||
return segment.revision === segment.appliedRevision
|
||||
? <Badge variant="success-light">Применена</Badge>
|
||||
: <Badge variant="warning-light">{segment.appliedRevision ? "Есть черновик" : "Черновик"}</Badge>
|
||||
}
|
||||
|
||||
export function SegmentGrid({ rows, nodes, loading, open, empty }: {
|
||||
rows: IxSegment[]; nodes: IxNode[]; loading: boolean; open: (segment: IxSegment) => void; empty: React.ReactNode
|
||||
}) {
|
||||
const columns = useMemo<ColumnDef<DataGridFeatures, IxSegment>[]>(() => [
|
||||
{ id: "name", header: "Сегмент", size: 210, cell: ({ row }) => (
|
||||
<Button type="button" variant="link" size="sm" className="max-w-full justify-start" onClick={() => open(row.original)}>
|
||||
<span className="truncate">{row.original.configuration.name}</span>
|
||||
</Button>
|
||||
) },
|
||||
{ id: "sites", header: "Площадки", size: 230, cell: ({ row }) => row.original.configuration.sites.map(site => nodeLabel(nodes, site.serverId)).join(", ") },
|
||||
{ id: "clients", header: "Linux-клиенты", size: 125, cell: ({ row }) =>
|
||||
<span className="tabular-nums">{row.original.configuration.sites.reduce((total, site) => total + site.interfaces.filter(item => item.linux).length, 0)}</span> },
|
||||
{ id: "state", header: "Состояние", size: 140, cell: ({ row }) => <SegmentStatus segment={row.original} /> },
|
||||
], [nodes, open])
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: rows, columns, getRowId: row => row.id })
|
||||
return <DataGridShell table={table} recordCount={rows.length} isLoading={loading} loadingMode="skeleton" emptyMessage={empty} />
|
||||
}
|
||||
|
||||
export function useIxNodeInventory(backendUrl: string, serverId: number, segmentId?: string) {
|
||||
const path = serverId > 0 ? `/api/ix/nodes/${serverId}/inventory${segmentId ? "?segmentId=" + segmentId : ""}` : null
|
||||
const [result, setResult] = useState<{ path: string; inventory?: IxNodeInventory; error?: string }>()
|
||||
const [refresh, setRefresh] = useState(0)
|
||||
useEffect(() => {
|
||||
if (!path) return
|
||||
const controller = new AbortController()
|
||||
void requestJson<IxNodeInventory>(backendUrl, path, { signal: controller.signal }).then(inventory => {
|
||||
if (!Array.isArray(inventory?.interfaces) || !Array.isArray(inventory.defaultRoutes)) throw new Error("Неполный каталог интерфейсов")
|
||||
if (!controller.signal.aborted) setResult({ path, inventory })
|
||||
}).catch(() => {
|
||||
if (!controller.signal.aborted) setResult({ path, error: "Не удалось прочитать интерфейсы CHR" })
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [backendUrl, path, refresh])
|
||||
return { ...(result?.path === path ? result : undefined), loading: path !== null && result?.path !== path,
|
||||
reload: () => { setResult(undefined); setRefresh(value => value + 1) } }
|
||||
}
|
||||
|
||||
function IxInventoryFields({ site, segmentId, backendUrl, fieldId, peers, readOnly, segmentName, edit }: {
|
||||
site: IxSite; segmentId?: string; backendUrl: string; fieldId: string; peers: { value: string; label: string }[]
|
||||
readOnly: boolean; segmentName: string; edit: (fields: Partial<IxSite>) => void
|
||||
}) {
|
||||
const { inventory, error, loading, reload } = useIxNodeInventory(backendUrl, site.serverId, segmentId)
|
||||
const suggested = site.routerId || (site.autoRouterId ? inventory?.routerId ?? "" : "")
|
||||
return <>
|
||||
<Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-router"}>Router ID</FieldLabel>
|
||||
<Input id={fieldId + "-router"} value={suggested} placeholder="Подбирается автоматически" readOnly={readOnly}
|
||||
onChange={event => edit({ routerId: event.target.value, autoRouterId: !event.target.value })} />
|
||||
<FieldDescription>{suggested ? site.autoRouterId ? "Назначен автоматически" : "Задан вручную" :
|
||||
loading ? "Проверяем занятые идентификаторы…" : "Свободный ID будет выбран при сохранении."}</FieldDescription>
|
||||
</Field>
|
||||
<div className="grid min-w-0 gap-3 sm:col-span-2 lg:col-span-3">
|
||||
{site.serverId > 0 && <div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-sm text-muted-foreground" role="status">
|
||||
{loading ? "Читаем интерфейсы CHR…" : error ?? `Интерфейсы CHR · ${inventory?.interfaces?.length ?? 0}`}
|
||||
</span>
|
||||
<Button type="button" size="sm" variant="outline" disabled={loading} onClick={reload}>Обновить интерфейсы</Button>
|
||||
</div>}
|
||||
<IxSiteEditor site={site} segmentName={segmentName} readOnly={readOnly} edit={edit} peers={peers}
|
||||
inventory={inventory?.interfaces ?? []} />
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
|
||||
export function ConfigurationFields({ configuration, nodes, peers, readOnly, change, backendUrl, segmentId, section }: {
|
||||
section: "configuration" | "routes"
|
||||
configuration: IxConfiguration; nodes: IxNode[]; peers: IxNode[]; readOnly: boolean; change: (value: IxConfiguration) => void
|
||||
backendUrl: string; segmentId?: string
|
||||
}) {
|
||||
function updateSite(index: number, fields: Partial<IxSite>) {
|
||||
change({ ...configuration, sites: configuration.sites.map((site, position) => position === index ? { ...site, ...fields } : site) })
|
||||
}
|
||||
const canAddSite = configuration.sites.length < 2 && nodes.filter(node => node.enabled).length > configuration.sites.length
|
||||
|
||||
return <div className="grid min-w-0 gap-3">
|
||||
{section === "configuration" && <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Сегмент</FrameTitle></FrameHeader>
|
||||
<FramePanel>
|
||||
<Field className="max-w-md">
|
||||
<FieldLabel htmlFor="ix-name">Имя сегмента</FieldLabel>
|
||||
<Input id="ix-name" placeholder="ix-central" value={configuration.name} readOnly={readOnly}
|
||||
onChange={event => change({ ...configuration, name: event.target.value })} />
|
||||
{!readOnly && <FieldDescription>Латинские строчные буквы, цифры и дефисы.</FieldDescription>}
|
||||
</Field>
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
{configuration.sites.map((site, index) => {
|
||||
const fieldId = `ix-site-${index}`
|
||||
const choices = nodes.filter(node => node.id === site.serverId || (node.enabled && !configuration.sites.some((other, i) => i !== index && other.serverId === node.id)))
|
||||
return <Frame key={fieldId} spacing="sm">
|
||||
<FrameHeader className="flex-row items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<FrameTitle>{section === "configuration" ? "Площадка " + (index + 1) : nodeLabel(nodes, site.serverId)}</FrameTitle>
|
||||
</div>
|
||||
{section === "configuration" && !readOnly && configuration.sites.length > 1 && <Button type="button" size="icon-sm" variant="ghost"
|
||||
aria-label={`Убрать площадку ${index + 1}`}
|
||||
onClick={() => change({ ...configuration, sites: configuration.sites.filter((_, position) => position !== index) })}>
|
||||
<XIcon aria-hidden />
|
||||
</Button>}
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid gap-4">
|
||||
<div className="grid min-w-0 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{section === "configuration" && <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId}>Узел IX</FieldLabel>
|
||||
<Select
|
||||
value={site.serverId ? String(site.serverId) : null}
|
||||
items={choices.map(node => ({ value: String(node.id), label: node.name }))}
|
||||
disabled={readOnly}
|
||||
onValueChange={value => { if (value && Number(value) !== site.serverId) updateSite(index, { ...newSite(), serverId: Number(value) }) }}
|
||||
>
|
||||
<SelectTrigger id={fieldId} className="w-full"><SelectValue placeholder="Выберите узел" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{choices.map(node => <SelectItem key={node.id} value={String(node.id)} disabled={!node.enabled}>{node.name}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>}
|
||||
{section === "routes" && <Field className="min-w-0">
|
||||
<FieldLabel htmlFor={fieldId + "-asn"}>Локальный ASN</FieldLabel>
|
||||
<Input id={fieldId + "-asn"} inputMode="numeric" value={site.autonomousSystem || ""} readOnly={readOnly}
|
||||
onChange={event => { if (/^\d*$/.test(event.target.value)) updateSite(index, { autonomousSystem: Number(event.target.value) }) }} />
|
||||
</Field>}
|
||||
{section !== "configuration" && <IxInventoryFields site={site} segmentId={segmentId} backendUrl={backendUrl} fieldId={fieldId}
|
||||
readOnly={readOnly} segmentName={configuration.name} edit={fields => updateSite(index, fields)}
|
||||
peers={peers.filter(node => node.id !== site.serverId && (node.enabled || site.interfaces.some(binding => binding.peerServerId === node.id)))
|
||||
.map(node => ({ value: String(node.id), label: node.name }))} />}
|
||||
</div>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
})}
|
||||
{section === "configuration" && !readOnly && canAddSite && <Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => change({ ...configuration, sites: [...configuration.sites, newSite()] })}>
|
||||
<PlusIcon aria-hidden />Добавить площадку
|
||||
</Button>}
|
||||
</div>
|
||||
}
|
||||
|
||||
const routeColumns: ColumnDef<DataGridFeatures, Route>[] = [
|
||||
{ id: "prefix", header: "Префикс", size: 160, cell: ({ row }) => <span className="font-mono">{row.original.prefix}</span> },
|
||||
{ id: "gateway", header: "Шлюз", size: 140, cell: ({ row }) => row.original.gateway || "—" },
|
||||
{ id: "immediate", header: "Фактический next hop", size: 200, cell: ({ row }) => row.original.immediateGateway ?? "—" },
|
||||
{ id: "active", header: "Состояние", size: 112, cell: ({ row }) => row.original.active
|
||||
? <Badge variant="success-light">Активен</Badge>
|
||||
: <Badge variant="secondary">Неактивен</Badge> },
|
||||
]
|
||||
|
||||
export function RouteGrid({ observation, nodes }: { observation: IxSiteObservation; nodes: IxNode[] }) {
|
||||
const table = useTable({ features: dataGridFeatures, manualPagination: true, data: observation.routes, columns: routeColumns })
|
||||
return <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<FrameTitle className="wrap-anywhere">{nodeLabel(nodes, observation.serverId)}</FrameTitle>
|
||||
<FrameDescription>{new Date(observation.observedAt).toLocaleString("ru-RU")}</FrameDescription>
|
||||
</div>
|
||||
{observation.available ? <Badge variant="info-light">
|
||||
BGP {observation.neighbors.filter(peer => peer.established).length} из {observation.neighbors.length}
|
||||
</Badge> : <Badge variant="warning-light">Состояние недоступно</Badge>}
|
||||
</FrameHeader>
|
||||
{observation.available && <FramePanel className="min-w-0 p-0">
|
||||
<div className="overflow-x-auto">
|
||||
<DataGridShell table={table} recordCount={observation.routes.length}
|
||||
emptyMessage={<EmptyState icon={<FileTextIcon />} title="Маршруты не найдены" className="py-8" />} />
|
||||
</div>
|
||||
</FramePanel>}
|
||||
</Frame>
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { ArrowLeftIcon, CircleAlertIcon, NetworkIcon, PlusIcon, RefreshCwIcon, Trash2Icon } from "lucide-react"
|
||||
import { ixSegmentConfigurationSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxLinuxClientRequest, type IxLinuxPath, type IxTransitRequest, type IxWebPlan, type IxSegment, type IxSiteObservation } from "@mmapp/contracts/internet-exchange"
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
|
||||
import { Frame, FrameDescription, FrameHeader, FramePanel, FrameTitle } from "@/components/reui/frame"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { ServerRailLayout, ServerRailMobileButton } from "@/components/server-rail-layout"
|
||||
import { ALL_SERVERS_ID } from "@/components/server-tile-rail"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { can, ensureAuthConfig } from "@/lib/auth"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, SegmentStatus, type IxNode } from "./ix-view"
|
||||
import { IxLinuxClients } from "./ix-linux-clients"
|
||||
import { IxExits } from "./ix-exits"
|
||||
|
||||
type Tab = "configuration" | "routes" | "linux"
|
||||
|
||||
const title = "Точки обмена трафиком"
|
||||
const describe = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить операцию IX"
|
||||
const json = (value: unknown) => JSON.stringify(value, null, 2)
|
||||
const post = (value: unknown) => ({ method: "POST", body: JSON.stringify(value) })
|
||||
|
||||
function download(name: string, content: string) {
|
||||
const url = URL.createObjectURL(new Blob([content], { type: "text/plain;charset=utf-8" }))
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = name
|
||||
link.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
|
||||
const actionLabels = { create: "Создать", update: "Обновить", delete: "Удалить" } as const
|
||||
|
||||
function RouterOsChanges({ changes, nodes }: { changes: IxWebPlan["changes"]; nodes: IxNode[] }) {
|
||||
if (!changes.length) return null
|
||||
return <ul className="max-h-56 min-w-0 divide-y overflow-auto rounded-md border">
|
||||
{changes.map((operation, index) => <li key={index} className="min-w-0 p-2.5 text-sm">
|
||||
<details>
|
||||
<summary className="cursor-pointer wrap-anywhere">{actionLabels[operation.action]} · {nodeLabel(nodes, operation.serverId)} · <code>{operation.path}</code>
|
||||
{operation.target && <> · <code>{operation.target}</code></>}
|
||||
</summary>
|
||||
<dl className="grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 py-2 text-xs">
|
||||
{operation.placeBefore && <><dt className="text-muted-foreground">Перед объектом</dt><dd className="font-mono">{operation.placeBefore}</dd></>}
|
||||
{Object.entries(operation.fields).map(([key, value]) => <div key={key} className="contents">
|
||||
<dt className="max-w-32 wrap-anywhere text-muted-foreground">{key}</dt>
|
||||
<dd className="wrap-anywhere font-mono">{value}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
</details>
|
||||
</li>)}
|
||||
</ul>
|
||||
}
|
||||
|
||||
export default function IxPage() {
|
||||
const { backendUrl, mode, prefsHydrated } = useDataSource()
|
||||
const [segments, setSegments] = useState<IxSegment[]>([])
|
||||
const [nodes, setNodes] = useState<IxNode[]>([])
|
||||
const [peers, setPeers] = useState<IxNode[]>([])
|
||||
const [selected, setSelected] = useState<IxSegment | null>(null)
|
||||
const [draft, setDraft] = useState<IxConfiguration | null>(null)
|
||||
const [advanced, setAdvanced] = useState<string | null>(null)
|
||||
const [filter, setFilter] = useState("")
|
||||
const [activeNode, setActiveNode] = useState(ALL_SERVERS_ID)
|
||||
const [observations, setObservations] = useState<IxSiteObservation[] | null>(null)
|
||||
const [linuxBindings, setLinuxBindings] = useState<IxLinuxBinding[]>([])
|
||||
const [linux, setLinux] = useState<(IxLinuxAccess & IxLinuxBinding) | null>(null)
|
||||
const [linuxPath, setLinuxPath] = useState<(IxLinuxPath & Pick<IxLinuxBinding, "name" | "interfaceName">) | null>(null)
|
||||
const [review, setReview] = useState("")
|
||||
const [reviewError, setReviewError] = useState("")
|
||||
const [plan, setPlan] = useState<IxWebPlan | null>(null)
|
||||
const [removalPlan, setRemovalPlan] = useState<IxWebPlan | null>(null)
|
||||
const [tab, setTab] = useState<Tab>("configuration")
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const [notice, setNotice] = useState("")
|
||||
const [write, setWrite] = useState(false)
|
||||
const heading = useRef<HTMLHeadingElement>(null)
|
||||
const focusAfterNavigation = useRef(false)
|
||||
const inDetail = draft !== null
|
||||
|
||||
async function load(signal?: AbortSignal) {
|
||||
if (signal?.aborted) return
|
||||
setWrite(can("mm:network:write"))
|
||||
const [segmentsResult, nodesResult] = await Promise.all([
|
||||
requestJson<{ items: IxSegment[] }>(backendUrl, "/api/ix/segments?limit=100", { signal }),
|
||||
requestJson<{ items: IxNode[]; peers?: IxNode[] }>(backendUrl, "/api/ix/nodes", { signal }),
|
||||
])
|
||||
if (signal?.aborted) return
|
||||
setSegments(segmentsResult.items)
|
||||
setNodes(nodesResult.items)
|
||||
|
||||
setPeers(nodesResult.peers ?? nodesResult.items)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!prefsHydrated || mode !== "live") return
|
||||
const controller = new AbortController()
|
||||
void ensureAuthConfig().then(() => {
|
||||
if (controller.signal.aborted) return
|
||||
setLoading(true)
|
||||
setError("")
|
||||
return load(controller.signal)
|
||||
})
|
||||
.catch(error => { if (!controller.signal.aborted) setError(describe(error)) })
|
||||
.finally(() => { if (!controller.signal.aborted) setLoading(false) })
|
||||
return () => controller.abort()
|
||||
// Reload when the project data source changes.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [backendUrl, mode, prefsHydrated])
|
||||
|
||||
useEffect(() => {
|
||||
if (focusAfterNavigation.current) {
|
||||
focusAfterNavigation.current = false
|
||||
heading.current?.focus()
|
||||
}
|
||||
}, [inDetail])
|
||||
|
||||
const rows = segments.filter(segment => (activeNode === ALL_SERVERS_ID ||
|
||||
segment.configuration.sites.some(site => String(site.serverId) === activeNode)) &&
|
||||
segment.configuration.name.includes(filter.trim().toLowerCase()))
|
||||
const enabledNodes = nodes.filter(node => node.enabled && (activeNode === ALL_SERVERS_ID || String(node.id) === activeNode))
|
||||
const live = prefsHydrated && mode === "live"
|
||||
const canCreate = live && write && !loading && enabledNodes.length > 0
|
||||
const savedConfiguration = selected ? json(selected.configuration) : null
|
||||
const dirty = (advanced ?? json(draft)) !== savedConfiguration
|
||||
const canPlan = live && write && selected !== null && selected.appliedRevision !== selected.revision && !dirty
|
||||
|
||||
function invalidateReview() {
|
||||
setPlan(null)
|
||||
setReview("")
|
||||
setReviewError("")
|
||||
setRemovalPlan(null)
|
||||
setNotice("")
|
||||
}
|
||||
|
||||
function open(segment: IxSegment | null, defaultTab: Tab = segment ? "linux" : "configuration") {
|
||||
focusAfterNavigation.current = !inDetail
|
||||
setSelected(segment)
|
||||
setDraft(segment?.configuration ?? { name: "", sites: [{ ...newSite(), serverId: enabledNodes.length === 1 ? enabledNodes[0].id : 0 }] })
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setLinuxBindings([])
|
||||
setTab(defaultTab)
|
||||
setError("")
|
||||
invalidateReview()
|
||||
if (defaultTab === "linux" && segment?.appliedRevision) void perform(() => loadLinuxBindings(segment))
|
||||
}
|
||||
|
||||
function close() {
|
||||
focusAfterNavigation.current = true
|
||||
setDraft(null)
|
||||
setRemovalPlan(null)
|
||||
setError("")
|
||||
setNotice("")
|
||||
}
|
||||
|
||||
function change(): IxChange {
|
||||
const configuration = ixSegmentConfigurationSchema.parse(advanced === null && draft
|
||||
? { ...draft, sites: draft.sites.map(site => ({ ...site, routerId: site.routerId || (site.autoRouterId ? "0.0.0.0" : "") })) }
|
||||
: JSON.parse(advanced ?? "null"))
|
||||
return { ...(selected ? { id: selected.id } : {}), revision: selected?.revision ?? 0, configuration }
|
||||
}
|
||||
|
||||
async function perform(work: () => Promise<void>) {
|
||||
setBusy(true)
|
||||
setError("")
|
||||
setNotice("")
|
||||
try { await work(); return true } catch (error) { setError(describe(error)); return false }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (selected && !dirty) {
|
||||
await reviewSegment(selected, selected.configuration.name)
|
||||
return
|
||||
}
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl, "/api/ix/segments", post(change()))
|
||||
await reviewSegment(segment, segment.configuration.name)
|
||||
}
|
||||
|
||||
async function prepare(segment: IxSegment, resume = false) {
|
||||
setPlan(null)
|
||||
setReviewError("")
|
||||
try {
|
||||
setPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + segment.id + "/plan", post({
|
||||
revision: segment.revision, ...(resume && { resume }),
|
||||
})))
|
||||
} catch (error) {
|
||||
setReviewError(describe(error))
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareRemoval() {
|
||||
if (!selected) return
|
||||
setRemovalPlan(await requestJson<IxWebPlan>(backendUrl, "/api/ix/segments/" + selected.id + "/removal-plan", post({ revision: selected.revision })))
|
||||
}
|
||||
|
||||
async function removeSegment() {
|
||||
if (!selected || !removalPlan) return
|
||||
setRemovalPlan(null)
|
||||
await requestJson<void>(backendUrl, "/api/ix/segments/" + selected.id, {
|
||||
method: "DELETE", body: JSON.stringify({ revision: removalPlan.revision, digest: removalPlan.digest }),
|
||||
})
|
||||
setSegments(current => current.filter(segment => segment.id !== selected.id))
|
||||
close()
|
||||
setNotice("Сегмент " + selected.configuration.name + " удалён")
|
||||
}
|
||||
|
||||
async function apply() {
|
||||
if (!selected || !plan || !canPlan) return
|
||||
setPlan(null)
|
||||
try {
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
|
||||
"/api/ix/segments/" + selected.id + "/apply", post({ revision: plan.revision, digest: plan.digest, ...(plan.resume && { resume: true }) }))
|
||||
setSelected(segment)
|
||||
setDraft(segment.configuration)
|
||||
setAdvanced(null)
|
||||
setObservations(null)
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setLinuxBindings([])
|
||||
setSegments(current => current.map(item => item.id === segment.id ? segment : item))
|
||||
setReview("")
|
||||
setReviewError("")
|
||||
setNotice("Конфигурация IX применена")
|
||||
if (tab === "linux" || selected.appliedRevision === null) {
|
||||
setTab("linux")
|
||||
await loadLinuxBindings(segment).catch(error => setError(describe(error)))
|
||||
} else if (tab === "routes") {
|
||||
await observe(segment).catch(error => setError(describe(error)))
|
||||
}
|
||||
} catch (error) {
|
||||
setReviewError(describe(error))
|
||||
}
|
||||
}
|
||||
|
||||
async function observe(segment = selected) {
|
||||
if (!segment?.appliedRevision) return
|
||||
const { sites } = await requestJson<{ sites: IxSiteObservation[] }>(backendUrl, `/api/ix/segments/${segment.id}/status`)
|
||||
setObservations(sites)
|
||||
}
|
||||
|
||||
async function loadLinuxBindings(segment = selected) {
|
||||
if (!segment) return
|
||||
setLinux(null)
|
||||
const { items } = await requestJson<{ items: IxLinuxBinding[] }>(backendUrl, `/api/ix/segments/${segment.id}/linux`)
|
||||
setLinuxBindings(items)
|
||||
}
|
||||
|
||||
async function exportLinux(binding: IxLinuxBinding) {
|
||||
if (!selected) return
|
||||
setLinux(null)
|
||||
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
|
||||
if (binding.managedWireguard && write) {
|
||||
const access = await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
|
||||
download(access.filename, access.template)
|
||||
setNotice("Конфигурация WireGuard скачана")
|
||||
return
|
||||
}
|
||||
const access = binding.policy && binding.kind === "gre-ipsec" && write
|
||||
? await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`,
|
||||
post({ serverId: binding.serverId, interfaceName: binding.interfaceName }))
|
||||
: await requestJson<IxLinuxAccess>(backendUrl, `/api/ix/segments/${selected.id}/linux?${query}`)
|
||||
setLinux({ ...binding, ...access })
|
||||
}
|
||||
|
||||
async function inspectLinux(binding: IxLinuxBinding) {
|
||||
if (!selected) return
|
||||
setLinuxPath(null)
|
||||
const query = new URLSearchParams({ serverId: String(binding.serverId), interfaceName: binding.interfaceName })
|
||||
const path = await requestJson<IxLinuxPath>(backendUrl, `/api/ix/segments/${selected.id}/linux/path?${query}`)
|
||||
setLinuxPath({ name: binding.name, interfaceName: binding.interfaceName, ...path })
|
||||
}
|
||||
|
||||
async function stageClient(input: IxLinuxClientRequest | IxLinuxBinding) {
|
||||
if (!selected || dirty || !write) return
|
||||
const path = `/api/ix/segments/${selected.id}`
|
||||
const result = "revision" in input
|
||||
? await requestJson<{ segment: IxSegment; interfaceName: string }>(backendUrl, path + "/linux", post(input))
|
||||
: await requestJson<{ segment: IxSegment }>(backendUrl, path + "/linux/revoke",
|
||||
post({ revision: selected.revision, serverId: input.serverId, interfaceName: input.interfaceName }))
|
||||
await reviewSegment(result.segment, "revision" in input ? "Доступ клиента " + input.name : "Отзыв доступа " + (input.name ?? input.interfaceName))
|
||||
}
|
||||
|
||||
async function stageTransit(input: IxTransitRequest) {
|
||||
if (!selected || dirty || !write) return
|
||||
const { segment } = await requestJson<{ segment: IxSegment }>(backendUrl,
|
||||
`/api/ix/segments/${selected.id}/transit`, post(input))
|
||||
await reviewSegment(segment, "Выход через " + nodeLabel(peers, input.targetServerId))
|
||||
}
|
||||
|
||||
async function reviewSegment(segment: IxSegment, title: string) {
|
||||
setSelected(segment)
|
||||
setDraft(segment.configuration)
|
||||
setAdvanced(null)
|
||||
setSegments(current => current.some(item => item.id === segment.id)
|
||||
? current.map(item => item.id === segment.id ? segment : item) : [segment, ...current])
|
||||
setLinux(null)
|
||||
setLinuxPath(null)
|
||||
setReview(title)
|
||||
await prepare(segment)
|
||||
}
|
||||
|
||||
function closeReview() {
|
||||
if (busy) return
|
||||
setReview("")
|
||||
setPlan(null)
|
||||
setReviewError("")
|
||||
setNotice("Изменения сохранены в черновике. Нажмите «Сохранить», чтобы вернуться к подтверждению.")
|
||||
}
|
||||
|
||||
function showTab(next: Tab) {
|
||||
if (next === tab || busy) return
|
||||
if (advanced !== null) {
|
||||
try { setDraft(change().configuration); setAdvanced(null) } catch (error) { setError(describe(error)); return }
|
||||
}
|
||||
setError("")
|
||||
setTab(next)
|
||||
if (next === "routes" && observations === null && selected?.appliedRevision) void perform(observe)
|
||||
if (next === "linux" && selected?.appliedRevision) void perform(loadLinuxBindings)
|
||||
}
|
||||
|
||||
const settingsProps = draft && {
|
||||
configuration: draft, nodes, peers, backendUrl, segmentId: selected?.id, readOnly: !live || !write || busy,
|
||||
change: (value: IxConfiguration) => { setDraft(value); invalidateReview() },
|
||||
}
|
||||
|
||||
const listEmpty = error ? "Не удалось загрузить список" :
|
||||
filter.trim() ? "Сегменты не найдены" : !live ? "Подключите backend" : "Нет сегментов IX"
|
||||
const listDescription = error ? "Повторите загрузку списка." : filter.trim() ? "Попробуйте другое имя сегмента." :
|
||||
!live ? "Откройте раздел в режиме «Живые»." : enabledNodes.length ? undefined : "Сначала добавьте сервер типа IX Node."
|
||||
|
||||
return <ServerRailLayout items={nodes.map(node => ({ ...node, id: String(node.id), type: "ix-node", selectable: node.enabled }))}
|
||||
selectedId={activeNode} allCount={nodes.length} loading={loading} showCount={false} preserveSelection onSelect={id => {
|
||||
if (busy || id === activeNode) return
|
||||
setActiveNode(id)
|
||||
setFilter("")
|
||||
const forNode = segments.filter(segment => segment.configuration.sites.some(site => String(site.serverId) === id))
|
||||
if (forNode.length === 1) open(forNode[0], "linux")
|
||||
else close()
|
||||
}}
|
||||
header={<PageHeader crumbs={inDetail ? [{ label: "Сегменты IX" }, { label: selected?.configuration.name ?? "Новый сегмент" }] : [{ label: title }]}
|
||||
actions={<ServerRailMobileButton />} />}>
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto">
|
||||
<div className="flex w-full min-w-0 flex-col gap-4 p-4 md:gap-5 md:p-6" aria-busy={busy}>
|
||||
{inDetail && <Button type="button" variant="ghost" size="sm" className="w-fit" disabled={busy} onClick={close}>
|
||||
<ArrowLeftIcon aria-hidden />Все сегменты
|
||||
</Button>}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 ref={heading} tabIndex={-1} className="text-xl font-semibold tracking-tight wrap-anywhere md:text-2xl">
|
||||
{inDetail ? selected?.configuration.name ?? "Новый сегмент" : title}
|
||||
</h1>
|
||||
{inDetail && selected && <SegmentStatus segment={selected} />}
|
||||
</div>
|
||||
{inDetail ? (selected && <p className="mt-1 text-sm text-muted-foreground">
|
||||
Ревизия {selected.revision}{selected.appliedRevision && selected.appliedRevision !== selected.revision ? ` · Применена ревизия ${selected.appliedRevision}` : ""}
|
||||
</p>) : <p className="mt-1 text-sm text-muted-foreground">Сегменты IX, площадки и маршрутизация</p>}
|
||||
</div>
|
||||
{inDetail && live && write && <div className="flex flex-wrap items-center gap-2">
|
||||
{(dirty || canPlan) && <Button type="button" size="sm" disabled={busy} onClick={() => void perform(save)}>Сохранить</Button>}
|
||||
{selected && <AlertDialog open={removalPlan !== null}
|
||||
onOpenChange={open => { if (open) void perform(prepareRemoval); else setRemovalPlan(null) }}>
|
||||
<AlertDialogTrigger render={<Button type="button" variant="outline" size="sm" disabled={busy} />}>
|
||||
<Trash2Icon aria-hidden />Удалить сегмент
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="wrap-anywhere">Удалить {selected.configuration.name}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{selected.appliedRevision
|
||||
? "Этот сегмент перестанет передавать трафик. Управляемая конфигурация будет удалена с узлов IX."
|
||||
: "Черновик будет удалён из списка сегментов. Конфигурация роутеров останется прежней."}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{removalPlan && <RouterOsChanges changes={removalPlan.changes} nodes={nodes} />}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" disabled={busy} onClick={() => void perform(removeSegment)}>Удалить</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>}
|
||||
</div>}
|
||||
{!inDetail && <div className="flex flex-wrap items-center gap-2">
|
||||
<Button type="button" size="icon-sm" variant="outline" disabled={busy || loading || !live} aria-label="Обновить список"
|
||||
onClick={() => void perform(() => load())}><RefreshCwIcon aria-hidden /></Button>
|
||||
{canCreate && <Button type="button" size="sm" onClick={() => open(null)} disabled={busy}><PlusIcon aria-hidden />Добавить сегмент</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
{error && <Alert variant="destructive"><CircleAlertIcon aria-hidden /><AlertTitle>Ошибка IX</AlertTitle><AlertDescription className="wrap-anywhere">{error}</AlertDescription></Alert>}
|
||||
{notice && <p role="status" className="text-sm text-muted-foreground">{notice}</p>}
|
||||
|
||||
{!draft ? <Frame spacing="sm" className="min-w-0">
|
||||
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
|
||||
<div><FrameTitle>Сегменты</FrameTitle><FrameDescription>{live && !loading ? `Найдено: ${rows.length}` : ""}</FrameDescription></div>
|
||||
<Input type="search" aria-label="Поиск сегментов" placeholder="Найти сегмент" className="w-full sm:w-56"
|
||||
value={filter} onChange={event => setFilter(event.target.value)} />
|
||||
</FrameHeader>
|
||||
<FramePanel className="min-w-0 p-0">
|
||||
<div className="overflow-x-auto">
|
||||
<SegmentGrid rows={rows} nodes={nodes} loading={!prefsHydrated || (live && loading)} open={open} empty={
|
||||
<EmptyState icon={<NetworkIcon aria-hidden />} title={listEmpty} description={listDescription}
|
||||
action={live && !filter.trim() && !error && enabledNodes.length === 0 ? <Button render={<Link href="/servers" />} nativeButton={false} size="sm" variant="outline">Открыть серверы</Button> : undefined} />
|
||||
} />
|
||||
</div>
|
||||
</FramePanel>
|
||||
</Frame> : <Tabs value={tab} onValueChange={value => showTab(value as Tab)} className="min-w-0 gap-3">
|
||||
<div className="min-w-0 overflow-x-auto border-b pb-1">
|
||||
<TabsList variant="line" aria-label="Разделы сегмента">
|
||||
{selected && <>
|
||||
<TabsTrigger value="linux">Linux-клиенты</TabsTrigger>
|
||||
<TabsTrigger value="routes">Маршрутизация</TabsTrigger>
|
||||
</>}
|
||||
<TabsTrigger value="configuration">Настройки IX</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<TabsContent value="configuration" className="grid min-w-0 gap-3">
|
||||
{advanced === null ? settingsProps && <ConfigurationFields {...settingsProps} section="configuration" /> : <Frame spacing="sm">
|
||||
<FrameHeader><FrameTitle>Конфигурация JSON</FrameTitle><FrameDescription>Интерфейсы, группы шлюзов, маршруты и BGP-политики.</FrameDescription></FrameHeader>
|
||||
<FramePanel>
|
||||
<Textarea aria-label="Конфигурация JSON" spellCheck={false} readOnly={!live || !write || busy} rows={14}
|
||||
className="font-mono" value={advanced} onChange={event => { setAdvanced(event.target.value); invalidateReview() }} />
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{advanced === null ? <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setAdvanced(json(draft))}>
|
||||
{write ? "Редактировать JSON" : "Показать JSON"}
|
||||
</Button> : <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
|
||||
setDraft(change().configuration)
|
||||
setAdvanced(null)
|
||||
})}>К форме</Button>}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="routes" className="grid min-w-0 gap-3">
|
||||
{selected && !dirty && live && write && <IxExits segment={selected} nodes={peers} backendUrl={backendUrl} busy={busy}
|
||||
error={error} save={input => perform(() => stageTransit(input))} />}
|
||||
{settingsProps && <ConfigurationFields {...settingsProps} section="routes" />}
|
||||
{!!selected?.appliedRevision && <>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void perform(observe)}>
|
||||
<RefreshCwIcon aria-hidden />Обновить состояние
|
||||
</Button>
|
||||
</div>
|
||||
{busy && observations === null && <Skeleton className="h-28 w-full" role="status" aria-label="Загрузка маршрутов" />}
|
||||
{observations?.map(site => <RouteGrid key={site.serverId} observation={site} nodes={nodes} />)}
|
||||
</>}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="linux" className="grid min-w-0 gap-3">
|
||||
{selected ? <IxLinuxClients key={selected.id} segment={selected} nodes={peers} backendUrl={backendUrl}
|
||||
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
|
||||
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
|
||||
refresh={() => void perform(loadLinuxBindings)} view={binding => void perform(() => exportLinux(binding))}
|
||||
inspect={binding => void perform(() => inspectLinux(binding))} />
|
||||
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
|
||||
{linuxPath && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Маршруты клиента · {linuxPath.name ?? linuxPath.interfaceName}</FrameTitle>
|
||||
<FrameDescription>{linuxPath.policy ?? "Только сети IX"} · {new Date(linuxPath.observedAt).toLocaleString("ru-RU")}</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid gap-2 text-sm">
|
||||
<p className="text-muted-foreground">Чтение FIB CHR. Доставку пакетов проверяют с Linux-клиента.</p>
|
||||
{linuxPath.routes.length ? <ul className="grid gap-2">{linuxPath.routes.map((route, index) => <li key={index}>
|
||||
<code>{route.prefix}</code> · {route.immediateGateway || route.gateway || "—"} · {route.active ? "активен" : "неактивен"}
|
||||
</li>)}</ul> : <p>Подходящих маршрутов сейчас нет.</p>}
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
{linux && <Frame spacing="sm">
|
||||
<FrameHeader>
|
||||
<FrameTitle>Конфигурация Linux · {linux.interfaceName}</FrameTitle>
|
||||
<FrameDescription>Ревизия {linux.revision} · {nodeLabel(nodes, linux.serverId)}</FrameDescription>
|
||||
</FrameHeader>
|
||||
<FramePanel className="grid min-w-0 gap-3">
|
||||
<p className="text-sm text-muted-foreground">{linux.kind === "wireguard"
|
||||
? linux.managedWireguard ? "Готовый файл с ключом доступен пользователю с правом управления сетью."
|
||||
: "Подставьте приватный ключ Linux. После установки проверьте, куда направляются трафик и соединение управления."
|
||||
: linux.policy && write ? "Подключите файл к strongSwan. Храните конфиг с PSK с правами доступа только для root."
|
||||
: "Для подключения нужен индивидуальный PSK, выданный оператором."}</p>
|
||||
{(!linux.policy || linux.kind === "wireguard") && <pre className="max-h-64 min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.template}</pre>}
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit" onClick={() => download(linux.filename, linux.template)}>
|
||||
Скачать {linux.managedWireguard ? "шаблон" : linux.filename}
|
||||
</Button>
|
||||
{linux.setup && <>
|
||||
<pre className="min-w-0 overflow-auto rounded-md border p-3 text-xs">{linux.setup}</pre>
|
||||
<Button type="button" variant="outline" size="sm" className="w-fit"
|
||||
onClick={() => download(linux.filename.replace(/\.conf$/, "-setup.sh"), "#!/bin/sh\nset -eu\n" + linux.setup + "\n")}>Скачать команды настройки</Button>
|
||||
</>}
|
||||
{linux.bgp && <p className="wrap-anywhere text-sm text-muted-foreground">
|
||||
BGP · ASN Linux {linux.bgp.localAs} · ASN IX {linux.bgp.remoteAs} · сосед {linux.bgp.neighbor}
|
||||
{linux.bgp.advertisedPrefixes.length > 0 && <> · анонсы Linux {linux.bgp.advertisedPrefixes.join(", ")}</>}
|
||||
</p>}
|
||||
</FramePanel>
|
||||
</Frame>}
|
||||
</TabsContent>
|
||||
|
||||
</Tabs>}
|
||||
<Dialog open={!!review} onOpenChange={open => { if (!open) closeReview() }}>
|
||||
<DialogContent showCloseButton={!busy} className="max-h-[85dvh] overflow-y-auto sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Подтвердите сохранение</DialogTitle>
|
||||
<DialogDescription>{review} · ревизия {selected?.revision}. После подтверждения изменения вступят в силу на узлах IX.</DialogDescription>
|
||||
</DialogHeader>
|
||||
{reviewError ? <Alert variant="destructive"><AlertTitle>Не удалось подтвердить состояние IX</AlertTitle>
|
||||
<AlertDescription>{reviewError}</AlertDescription></Alert>
|
||||
: plan ? <>
|
||||
<p className="text-sm font-medium">{plan.changes.length ? "Операций RouterOS: " + plan.changes.length : "RouterOS уже настроена. Будет отмечена применённая ревизия."}</p>
|
||||
<RouterOsChanges changes={plan.changes} nodes={peers} />
|
||||
</> : <p role="status" className="text-sm text-muted-foreground">{busy ? "Проверяем конфигурацию на узлах…" : "Обновите сравнение перед сохранением."}</p>}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={closeReview}>Отмена</Button>
|
||||
{reviewError && selected && <Button type="button" variant="outline" disabled={busy}
|
||||
onClick={() => void perform(() => prepare(selected, true))}>Сверить и продолжить</Button>}
|
||||
{plan ? <Button type="button" disabled={busy || !canPlan} onClick={() => void perform(apply)}>Подтвердить</Button>
|
||||
: reviewError && selected && <Button type="button" disabled={busy} onClick={() => void perform(() => prepare(selected))}>Повторить проверку</Button>}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
</ServerRailLayout>
|
||||
}
|
||||
@@ -66,8 +66,10 @@ import {
|
||||
hopHasRate,
|
||||
matchNetflowForGreEdge,
|
||||
matchNetflowForWan,
|
||||
type GreNetflowHop,
|
||||
type MatchedNetflowHop,
|
||||
} from "@/lib/map-netflow-hops"
|
||||
import { useMapGreTraffic } from "@/hooks/use-map-gre-traffic"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { CountryFlagSvg } from "@/components/network-map/country-flag-svg"
|
||||
@@ -243,6 +245,7 @@ const TYPE_STYLE: Record<ServerType, { label: string; fill: string; r: number }>
|
||||
"jump-host": { label: "JH", fill: "var(--chart-1)", r: 34 },
|
||||
// EN — крайние edge-узлы, менее акцентные.
|
||||
"exit-node": { label: "EN", fill: "var(--chart-3)", r: 30 },
|
||||
"ix-node": { label: "IX", fill: "var(--chart-4)", r: 34 },
|
||||
}
|
||||
|
||||
const WAN_COLORS = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"]
|
||||
@@ -257,6 +260,7 @@ const TYPE_LABELS: Record<ServerType, string> = {
|
||||
"jump-host": "JumpHost",
|
||||
"exit-node": "Exit Node",
|
||||
"home-router": "Home Router",
|
||||
"ix-node": "IX Node",
|
||||
}
|
||||
|
||||
const MOCK_MAP_SERVICES: FlowMapService[] = [
|
||||
@@ -597,19 +601,21 @@ function NetflowRateBadge({
|
||||
mx,
|
||||
my,
|
||||
hop,
|
||||
liveInterface,
|
||||
onOpen,
|
||||
}: {
|
||||
mx: number
|
||||
my: number
|
||||
hop: MatchedNetflowHop
|
||||
hop: Pick<MatchedNetflowHop, "bps" | "bpsFwd" | "bpsRev">
|
||||
liveInterface?: string
|
||||
onOpen?: (e: React.SyntheticEvent<SVGElement>) => void
|
||||
}) {
|
||||
const showDir = hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
const showDir = !!liveInterface || hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
const bw = showDir ? 86 : 72
|
||||
const bh = showDir ? 32 : 20
|
||||
const bh = liveInterface ? 41 : showDir ? 32 : 20
|
||||
return (
|
||||
<g
|
||||
role={onOpen?"button":undefined} aria-label={onOpen?"Поток NetFlow между узлами":undefined} tabIndex={onOpen?0:undefined} className="network-map-focusable"
|
||||
role={onOpen?"button":undefined} aria-label={onOpen ? liveInterface ? "Текущий трафик GRE " + liveInterface : "Поток NetFlow между узлами" : undefined} tabIndex={onOpen?0:undefined} className="network-map-focusable"
|
||||
onKeyDown={e=>{if(onOpen&&(e.key==="Enter"||e.key===" ")){e.preventDefault();e.stopPropagation();onOpen(e)}}}
|
||||
transform={`translate(${mx},${my})`}
|
||||
style={{ cursor: onOpen ? "pointer" : "default" }}
|
||||
@@ -617,7 +623,7 @@ function NetflowRateBadge({
|
||||
onClick={(e) => { e.stopPropagation(); onOpen?.(e) }}
|
||||
>
|
||||
<title>
|
||||
Поток NetFlow между узлами за интервал карты, без overlay/mesh.
|
||||
{liveInterface ? "Текущий RX/TX интерфейса " + liveInterface : "Поток NetFlow между узлами за интервал карты, без overlay/mesh."}
|
||||
</title>
|
||||
<rect className="network-map-focus-ring" x={-bw / 2 - 4} y={-bh / 2 - 4} width={bw + 8} height={bh + 8} rx="9" fill="none" stroke="var(--ring)" strokeWidth="2" />
|
||||
<rect
|
||||
@@ -630,14 +636,15 @@ function NetflowRateBadge({
|
||||
stroke="var(--status-online)"
|
||||
strokeWidth="1.15"
|
||||
/>
|
||||
<text textAnchor="middle" y={showDir ? "-4" : "4"} fontFamily="ui-monospace,monospace">
|
||||
<text textAnchor="middle" y={liveInterface ? "-8" : showDir ? "-4" : "4"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online-fg)" fontSize="8" fontWeight="700">{formatNetflowRate(hop)}</tspan>
|
||||
</text>
|
||||
{showDir && (
|
||||
<text textAnchor="middle" y="10" fontFamily="ui-monospace,monospace">
|
||||
<text textAnchor="middle" y={liveInterface ? "4" : "10"} fontFamily="ui-monospace,monospace">
|
||||
<tspan fill="var(--status-online)" fontSize="6.5" fontWeight="600">{formatNetflowDir(hop)}</tspan>
|
||||
</text>
|
||||
)}
|
||||
{liveInterface && <text textAnchor="middle" y="14" fill="var(--muted-foreground)" fontSize="6.5">Live GRE</text>}
|
||||
</g>
|
||||
)
|
||||
}
|
||||
@@ -1153,6 +1160,17 @@ function NetworkMapContent() {
|
||||
const [mapServers, setMapServers] = useState<Server[]>([])
|
||||
const [sessionCounts,setSessionCounts]=useState<Record<string,number|null>>({})
|
||||
const [mapGreTunnels, setMapGreTunnels] = useState<GreTunnel[]>([])
|
||||
const [showIx, setShowIx] = useState(true)
|
||||
const [ixLinks, setIxLinks] = useState<Array<{ from: number; to: number; segment: string }>>([])
|
||||
const hasIxNodes = mapServers.some(server => server.type === "ix-node")
|
||||
useEffect(() => {
|
||||
if (!useLiveData || !hasIxNodes) { setIxLinks([]); return }
|
||||
const controller = new AbortController()
|
||||
void apiFetch<{ links: Array<{ from: number; to: number; segment: string }> }>("/api/ix/topology", { signal: controller.signal })
|
||||
.then(result => { if (!controller.signal.aborted) setIxLinks(result.links) })
|
||||
.catch(() => { if (!controller.signal.aborted) setIxLinks([]) })
|
||||
return () => controller.abort()
|
||||
}, [apiFetch, useLiveData, hasIxNodes])
|
||||
const [speedProbes, setSpeedProbes] = useState<GreSpeedProbeSnapshot[]>([])
|
||||
const [mapHops, setMapHops] = useState<FlowMapHop[]>([])
|
||||
const [mapServices, setMapServices] = useState<FlowMapService[]>([])
|
||||
@@ -1617,15 +1635,28 @@ function NetworkMapContent() {
|
||||
}, [greEdges])
|
||||
|
||||
const netflowByGreKey = useMemo(() => {
|
||||
const m = new Map<string, MatchedNetflowHop>()
|
||||
const m = new Map<string, GreNetflowHop>()
|
||||
if (!showNetflow) return m
|
||||
for (const e of greEdges) {
|
||||
const hop = matchNetflowForGreEdge(e, mapHops)
|
||||
if (hopHasRate(hop)) m.set(greEdgeKey(e), hop)
|
||||
if (hop && hopHasRate(hop)) m.set(greEdgeKey(e), hop)
|
||||
}
|
||||
return m
|
||||
}, [greEdges, mapHops, showNetflow])
|
||||
|
||||
const greTrafficTargets = useMemo(() => {
|
||||
if (!useLiveData || !showNetflow || (!flowReadAt && !flowError)) return []
|
||||
return greEdges.flatMap(edge => {
|
||||
const edgeId = greEdgeKey(edge)
|
||||
const owner = edge.fromServer.id === edge.tunnel.serverId ? edge.fromServer : edge.toServer
|
||||
return edge.tunnel.enabled && edge.tunnel.status !== "down" && owner.status !== "offline" &&
|
||||
edge.tunnel.name && !netflowByGreKey.get(edgeId)?.exactInterface
|
||||
? [{ edgeId, serverId: owner.id, iface: edge.tunnel.name }]
|
||||
: []
|
||||
})
|
||||
}, [useLiveData, showNetflow, flowReadAt, flowError, greEdges, netflowByGreKey])
|
||||
const getGreLiveRate = useMapGreTraffic(backendUrl, greTrafficTargets)
|
||||
|
||||
const netflowByWanKey = useMemo(() => {
|
||||
const m = new Map<string, MatchedNetflowHop>()
|
||||
if (!showNetflow) return m
|
||||
@@ -2170,7 +2201,7 @@ function NetworkMapContent() {
|
||||
<PopoverContent align="start" aria-label="Слои карты" className="gap-0.5">
|
||||
{([
|
||||
{ key: "showPingBadges", label: "Ping-значки", val: showPingBadges, set: setShowPingBadges, hint: "P" },
|
||||
{ key: "showNetflow", label: "NetFlow", val: showNetflow, set: setShowNetflow, hint: "" },
|
||||
{ key: "showNetflow", label: "Трафик на линиях", val: showNetflow, set: setShowNetflow, hint: "" },
|
||||
{ key: "showServices", label: "Назначения", val: showServices, set: setShowServices, hint: "" },
|
||||
{ key: "showAnimDots", label: "Анимация трафика", val: showAnimDots, set: setShowAnimDots, hint: "" },
|
||||
{ key: "showMinimap", label: "Минимап", val: showMinimap, set: setShowMinimap, hint: "M" },
|
||||
@@ -2260,6 +2291,10 @@ function NetworkMapContent() {
|
||||
{/* ── Canvas ── */}
|
||||
<div ref={canvasRef} className={cn("flex-1 min-h-0 min-w-0 relative overflow-hidden bg-background select-none", (selected || selectedGreEdge || selectedService) && "hidden lg:block")}>
|
||||
<NetworkMapLegend />
|
||||
{ixLinks.length > 0 && <button type="button" aria-pressed={showIx} onClick={() => setShowIx(value => !value)}
|
||||
className="absolute right-3 top-3 z-20 rounded-md border bg-popover px-3 py-2 text-xs font-medium">
|
||||
Связи IX
|
||||
</button>}
|
||||
<p id="network-map-help" className="sr-only">Стрелки перемещают карту, плюс и минус меняют масштаб, F вписывает объекты. Tab выбирает объект, Enter открывает детали.</p>
|
||||
<svg
|
||||
ref={svgRef} role="group" aria-label="Интерактивная карта сети" tabIndex={0} aria-describedby="network-map-help"
|
||||
@@ -2318,7 +2353,8 @@ function NetworkMapContent() {
|
||||
tBadge,
|
||||
normalPx,
|
||||
)
|
||||
const flowHop = netflowByGreKey.get(edgeId)
|
||||
const liveRate = getGreLiveRate(edgeId)
|
||||
const flowHop = liveRate ?? netflowByGreKey.get(edgeId)
|
||||
const flowPos = edgeBadgePosition(
|
||||
e.from.x,
|
||||
e.from.y,
|
||||
@@ -2347,7 +2383,7 @@ function NetworkMapContent() {
|
||||
strokeWidth={
|
||||
highlightedPath && greMatchesPath(e, highlightedPath)
|
||||
? 3.4
|
||||
: hopHasRate(flowHop) ? 2.6 : 1.5
|
||||
: flowHop && flowHop.bps > 0 ? 2.6 : 1.5
|
||||
}
|
||||
strokeDasharray={e.tunnel.ipsec ? "7 4" : "none"}
|
||||
opacity={ts.opacity}
|
||||
@@ -2383,11 +2419,12 @@ function NetworkMapContent() {
|
||||
outerSummary={greOuterSummaryLine(e.tunnel, fromN, toN, greResolvedMap)}
|
||||
/>
|
||||
)}
|
||||
{showNetflow && hopHasRate(flowHop) && (
|
||||
{showNetflow && flowHop && (
|
||||
<NetflowRateBadge
|
||||
mx={flowPos.mx}
|
||||
my={flowPos.my}
|
||||
hop={flowHop}
|
||||
liveInterface={liveRate ? e.tunnel.name : undefined}
|
||||
onOpen={openGreDetail}
|
||||
/>
|
||||
)}
|
||||
@@ -2395,6 +2432,16 @@ function NetworkMapContent() {
|
||||
)
|
||||
})}
|
||||
|
||||
{showIx && [...new Map(ixLinks.map(link => {
|
||||
const key = [Math.min(link.from, link.to), Math.max(link.from, link.to), link.segment].join(":")
|
||||
return [key, link] as const
|
||||
})).entries()].map(([key, link]) => {
|
||||
const from = nodePosById[String(link.from)], to = nodePosById[String(link.to)]
|
||||
return from && to && <line key={key} x1={from.x} y1={from.y} x2={to.x} y2={to.y}
|
||||
stroke="var(--chart-4)" strokeWidth={2} strokeDasharray="8 4">
|
||||
<title>IX-сегмент {link.segment} · настроенная связь</title>
|
||||
</line>
|
||||
})}
|
||||
{/* ── Home Router → WAN satellite connectors ── */}
|
||||
{homeRouters.flatMap(router => {
|
||||
const rNode = nodes.find(n => n.id === router.id)
|
||||
@@ -2854,7 +2901,10 @@ function NetworkMapContent() {
|
||||
{(() => {
|
||||
const edge = selectedGreEdge
|
||||
const t = edge.tunnel
|
||||
const tunnelOwner = edge.fromServer.id === t.serverId ? edge.fromServer : edge.toServer
|
||||
const selectedEdgeId = greEdgeKey(edge)
|
||||
const liveRate = getGreLiveRate(selectedEdgeId)
|
||||
const greFlow = liveRate ?? netflowByGreKey.get(selectedEdgeId)
|
||||
const localWanName = ifaceNameForGreOuterIp(edge.fromServer, t.localAddress, greResolvedMap)
|
||||
const remoteWanName = ifaceNameForGreOuterIp(edge.toServer, t.remoteAddress, greResolvedMap)
|
||||
const baseProbe = greTunnelProbe(t,!useLiveData)
|
||||
@@ -2918,15 +2968,11 @@ function NetworkMapContent() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Поток (NetFlow)</span>
|
||||
<span className="text-xs text-muted-foreground">{liveRate ? "Текущий RX/TX GRE" : "Поток (NetFlow)"}</span>
|
||||
<span className="text-xs font-mono font-semibold text-emerald-400">
|
||||
{(() => {
|
||||
const hop = netflowByGreKey.get(selectedEdgeId)
|
||||
if (!hopHasRate(hop)) return "—"
|
||||
return hop.bpsFwd > 0 && hop.bpsRev > 0
|
||||
? formatNetflowDir(hop)
|
||||
: formatNetflowRate(hop)
|
||||
})()}
|
||||
{greFlow ? liveRate || greFlow.bpsFwd > 0 && greFlow.bpsRev > 0
|
||||
? formatNetflowDir(greFlow)
|
||||
: formatNetflowRate(greFlow) : "—"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground pt-2 leading-snug">
|
||||
@@ -2934,7 +2980,7 @@ function NetworkMapContent() {
|
||||
? "Ping и/или TX/RX — с последнего прогона speed-пробы; проба сопоставляется с этим GRE по WAN и интерфейсам. "
|
||||
: useLiveData?"Измерения GRE неизвестны: нет подходящей пробы. ":"Измерения демонстрационные. "}
|
||||
{spGr?"Проба "+spGr.id+" · время Ping: "+(spGr.lastPingAt?new Date(spGr.lastPingAt).toLocaleString("ru-RU"):"неизвестно")+" · время TX/RX неизвестно. ":""}
|
||||
Поток по данным NetFlow за {mapWindowSec / 60} мин, без overlay/mesh.
|
||||
{liveRate ? "Текущий трафик по счётчикам интерфейса RouterOS." : `Поток по данным NetFlow за ${mapWindowSec / 60} мин, без overlay/mesh.`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2946,7 +2992,7 @@ function NetworkMapContent() {
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">На узле</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{edge.fromServer.name}</span>
|
||||
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">{tunnelOwner.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 border-b border-border/50">
|
||||
<span className="text-xs text-muted-foreground">Пир (каталог)</span>
|
||||
@@ -3388,11 +3434,12 @@ function NetworkMapContent() {
|
||||
fromServer && toServer ? speedProbeByTunnelId.get(tunnelPanelKey) : undefined
|
||||
const merged = mergeGreMetricsWithSpeedProbe(spGre, baseProbe)
|
||||
const pc = pingColor(merged.pingMs)
|
||||
const greFlow = netflowByGreKey.get(tunnelPanelKey)
|
||||
const liveRate = getGreLiveRate(tunnelPanelKey)
|
||||
const greFlow = liveRate ?? netflowByGreKey.get(tunnelPanelKey)
|
||||
const showMetrics =
|
||||
merged.pingMs != null ||
|
||||
(merged.dlMbps != null && merged.ulMbps != null) ||
|
||||
hopHasRate(greFlow)
|
||||
!!greFlow
|
||||
return (
|
||||
<div key={tunnelPanelKey} className="rounded-md border border-border/60 px-3 py-2 bg-muted/20">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
@@ -3432,9 +3479,9 @@ function NetworkMapContent() {
|
||||
↓{merged.dlMbps} ↑{merged.ulMbps}
|
||||
</span>
|
||||
)}
|
||||
{hopHasRate(greFlow) && (
|
||||
{greFlow && (
|
||||
<span className="text-[9px] ml-1.5 text-emerald-400">
|
||||
{formatNetflowRate(greFlow)}
|
||||
{formatNetflowRate(greFlow)}{liveRate ? " · Live GRE" : ""}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -35,7 +35,7 @@ interface BackendServer {
|
||||
id: number
|
||||
name: string
|
||||
host: string
|
||||
type?: "jump-host" | "exit-node" | "home-router"
|
||||
type?: import("@mmapp/contracts/servers").ServerType
|
||||
site: string
|
||||
country: string
|
||||
asn: string
|
||||
@@ -329,11 +329,11 @@ function RouteSheet({
|
||||
)
|
||||
}
|
||||
|
||||
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) {
|
||||
function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
|
||||
return (
|
||||
<Badge size="xs" className="shrink-0 text-foreground"
|
||||
variant={type === "home-router" ? "success-light" : type === "jump-host" ? "primary-light" : "info-light"}>
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"}
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
+27
-12
@@ -38,6 +38,8 @@ import { cn } from "@/lib/utils"
|
||||
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||
import { DataPageCard } from "@/components/data-page-card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import { Field, FieldTitle } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||
@@ -591,6 +593,7 @@ function ServersPageContent() {
|
||||
"jump-host": serverList.filter(s => s.type === "jump-host").length,
|
||||
"exit-node": serverList.filter(s => s.type === "exit-node").length,
|
||||
"home-router":serverList.filter(s => s.type === "home-router").length,
|
||||
"ix-node": serverList.filter(s => s.type === "ix-node").length,
|
||||
online: serverList.filter(s => s.status === "online").length,
|
||||
}), [serverList])
|
||||
|
||||
@@ -599,6 +602,7 @@ function ServersPageContent() {
|
||||
{ value: "jump-host", label: "JumpHost" },
|
||||
{ value: "exit-node", label: "Exit Node" },
|
||||
{ value: "home-router", label: "Home Router" },
|
||||
{ value: "ix-node", label: "IX Node" },
|
||||
]
|
||||
|
||||
const isHomeRouter = form.type === "home-router"
|
||||
@@ -770,18 +774,29 @@ function ServersPageContent() {
|
||||
value={form.name} onChange={e => set("name", e.target.value)} />
|
||||
</FormField>
|
||||
|
||||
<FormField label="Тип узла" required>
|
||||
<SegmentedControl
|
||||
className="max-w-full flex-wrap"
|
||||
value={form.type}
|
||||
onChange={v => set("type", v)}
|
||||
options={[
|
||||
{ value: "home-router", label: "Home Router" },
|
||||
{ value: "jump-host", label: "JumpHost" },
|
||||
{ value: "exit-node", label: "Exit Node" },
|
||||
]}
|
||||
/>
|
||||
</FormField>
|
||||
<Field>
|
||||
<FieldTitle id="server-node-type-label">Тип узла <span aria-hidden className="text-destructive">*</span></FieldTitle>
|
||||
<ButtonGroup aria-labelledby="server-node-type-label" className="max-w-full">
|
||||
{([
|
||||
["home-router", "Home Router"],
|
||||
["jump-host", "JumpHost"],
|
||||
["exit-node", "Exit Node"],
|
||||
["ix-node", "IX Node"],
|
||||
] as const).map(([value, label]) => (
|
||||
<Button
|
||||
key={value}
|
||||
type="button"
|
||||
variant={form.type === value ? "default" : "outline"}
|
||||
size="sm"
|
||||
aria-pressed={form.type === value}
|
||||
className="h-auto min-h-7 min-w-0 flex-auto shrink whitespace-normal py-1"
|
||||
onClick={() => set("type", value)}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
</Field>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormField label="Площадка" required hint="MSK, SPB, FRA…">
|
||||
|
||||
@@ -235,7 +235,7 @@ function probeGroupActionKey(srvId: string, group: { name: string; target: strin
|
||||
|
||||
// ── shared components ──────────────────────────────────────────────────────────
|
||||
|
||||
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) {
|
||||
function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
|
||||
return (
|
||||
<span className={cn(
|
||||
"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0",
|
||||
@@ -245,7 +245,7 @@ function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" })
|
||||
? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20"
|
||||
: "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
|
||||
)}>
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"}
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -666,7 +666,7 @@ interface BackendServer {
|
||||
id: number
|
||||
name: string
|
||||
host: string
|
||||
type: "jump-host" | "exit-node" | "home-router"
|
||||
type: import("@mmapp/contracts/servers").ServerType
|
||||
site: string
|
||||
country: string
|
||||
enabled: boolean
|
||||
@@ -843,7 +843,7 @@ const INIT_RESOURCES: ServerResource[] = mockServers.map(s => {
|
||||
|
||||
// ── ResourcesTab ──────────────────────────────────────────────────────────────
|
||||
|
||||
type ResTypeFilter = "all" | "jump-host" | "exit-node" | "home-router"
|
||||
type ResTypeFilter = "all" | import("@mmapp/contracts/servers").ServerType
|
||||
|
||||
function ResourceWarnings({ rows }: { rows: UptimeResourceRow[] }) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
@@ -941,6 +941,7 @@ function ResourcesTab({ resources, serversList, liveApi }: { resources: ServerRe
|
||||
{ value: "jump-host", label: "JumpHost" },
|
||||
{ value: "exit-node", label: "Exit Node" },
|
||||
{ value: "home-router", label: "Home Router" },
|
||||
{ value: "ix-node", label: "IX Node" },
|
||||
]
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE public.servers DROP CONSTRAINT servers_type_check;
|
||||
ALTER TABLE public.servers ADD CONSTRAINT servers_type_check
|
||||
CHECK (type IN ('jump-host', 'exit-node', 'home-router', 'ix-node'));
|
||||
|
||||
CREATE TABLE public.ix_segments (
|
||||
id uuid PRIMARY KEY,
|
||||
name text NOT NULL UNIQUE,
|
||||
revision integer NOT NULL CHECK (revision > 0),
|
||||
configuration jsonb NOT NULL CHECK (jsonb_typeof(configuration) = 'object'),
|
||||
applied_revision integer CHECK (applied_revision > 0 AND applied_revision <= revision),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE public.ix_segment_devices (
|
||||
segment_id uuid NOT NULL REFERENCES public.ix_segments(id) ON DELETE CASCADE,
|
||||
server_id bigint NOT NULL REFERENCES public.servers(id) ON DELETE RESTRICT,
|
||||
PRIMARY KEY (segment_id, server_id)
|
||||
);
|
||||
CREATE INDEX ix_segment_devices_server_idx ON public.ix_segment_devices(server_id);
|
||||
|
||||
CREATE TABLE public.ix_segment_revisions (
|
||||
segment_id uuid NOT NULL REFERENCES public.ix_segments(id) ON DELETE CASCADE,
|
||||
revision integer NOT NULL CHECK (revision > 0),
|
||||
configuration jsonb NOT NULL CHECK (jsonb_typeof(configuration) = 'object'),
|
||||
actor_id text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (segment_id, revision)
|
||||
);
|
||||
|
||||
INSERT INTO public.schema_migrations (id) VALUES ('0058_internet_exchange') ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,97 @@
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE public.server_poll_storage_usage
|
||||
DROP CONSTRAINT server_poll_storage_usage_check2,
|
||||
DROP CONSTRAINT server_poll_storage_usage_admissions_check,
|
||||
DROP CONSTRAINT server_poll_storage_rows_charge,
|
||||
DROP CONSTRAINT server_poll_storage_bytes_charge,
|
||||
ADD CONSTRAINT server_poll_storage_usage_admissions_check CHECK (admissions >= 0),
|
||||
ADD CONSTRAINT server_poll_storage_rows_charge CHECK (reserved_rows = admissions * 4019 + compacted_admissions * 2),
|
||||
ADD CONSTRAINT server_poll_storage_bytes_charge CHECK (reserved_bytes = admissions * 8421376 + compacted_admissions * 32768 + archive_bytes);
|
||||
|
||||
CREATE OR REPLACE FUNCTION server_poll_storage_admission_guard() RETURNS trigger LANGUAGE plpgsql SET TimeZone='UTC' SET search_path=pg_catalog,public AS $$
|
||||
DECLARE retention integer; charged integer; r public.server_poll_archives%ROWTYPE;
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(hashtextextended('server-poll-storage-v1',0));
|
||||
IF TG_OP='DELETE' THEN
|
||||
IF NOT public.server_poll_storage_gc_allowed(OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_executions WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_intents WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_acks WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_receipts WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_quarantines WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id) THEN RAISE EXCEPTION 'poll lifetime or children prevent admission deletion'; END IF;
|
||||
UPDATE public.server_poll_storage_usage SET admissions=admissions-CASE WHEN OLD.storage_state='full' THEN 1 ELSE 0 END,
|
||||
compacted_admissions=compacted_admissions-CASE WHEN OLD.storage_state='compacted' THEN 1 ELSE 0 END,
|
||||
archive_bytes=archive_bytes-COALESCE(OLD.archive_bytes,0),
|
||||
reserved_rows=reserved_rows-CASE WHEN OLD.storage_state='full' THEN 4019 ELSE 2 END,
|
||||
reserved_bytes=reserved_bytes-CASE WHEN OLD.storage_state='full' THEN 8421376 ELSE 32768+OLD.archive_bytes END
|
||||
WHERE scope IN('global','owner:'||OLD.owner_id);
|
||||
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll quota refund mismatch'; END IF; RETURN OLD;
|
||||
END IF;
|
||||
IF TG_OP='UPDATE' THEN
|
||||
IF OLD.storage_state='compacted' AND NEW.storage_state='compacted'
|
||||
AND current_setting('mm.poll_retire_receipt',true)=OLD.receipt_id::text
|
||||
AND (to_jsonb(OLD)-'archive_bytes')=(to_jsonb(NEW)-'archive_bytes') THEN
|
||||
SELECT * INTO r FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id AND version=2;
|
||||
IF NOT FOUND OR r.ciphertext_bytes<>NEW.archive_bytes OR NEW.archive_bytes>OLD.archive_bytes
|
||||
OR r.execution_id<>OLD.execution_id OR r.connection_id<>OLD.connection_id OR r.owner_id<>OLD.owner_id
|
||||
THEN RAISE EXCEPTION 'retired poll charge source mismatch'; END IF;
|
||||
UPDATE public.server_poll_storage_usage
|
||||
SET archive_bytes=archive_bytes-OLD.archive_bytes+NEW.archive_bytes,
|
||||
reserved_bytes=reserved_bytes-OLD.archive_bytes+NEW.archive_bytes
|
||||
WHERE scope IN ('global','owner:'||OLD.owner_id) AND compacted_admissions>=1 AND archive_bytes>=OLD.archive_bytes;
|
||||
GET DIAGNOSTICS charged=ROW_COUNT;
|
||||
IF charged<>2 THEN RAISE EXCEPTION 'retired poll charge adjustment mismatch'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
-- This durable one-shot marker is written and ACKed in its OWN transaction
|
||||
-- before archive construction. A committed/unknown claim never resets and
|
||||
-- the worker never retries destructive work against an already claimed full
|
||||
-- source. Claim time is maintenance metadata, not renewed execution activity.
|
||||
IF OLD.storage_state='full' AND NEW.storage_state='full' AND OLD.compaction_claim IS NULL AND OLD.compaction_claimed_at IS NULL AND OLD.compaction_claim_xid IS NULL
|
||||
AND NEW.compaction_claim IS NOT NULL AND NEW.compaction_claim_xid IS NULL
|
||||
AND(to_jsonb(OLD)-ARRAY['compaction_claim','compaction_claimed_at','compaction_claim_xid'])=(to_jsonb(NEW)-ARRAY['compaction_claim','compaction_claimed_at','compaction_claim_xid'])
|
||||
AND public.server_poll_storage_compact_allowed(OLD.receipt_id)
|
||||
THEN NEW.compaction_claimed_at:=clock_timestamp(); NEW.compaction_claim_xid:=pg_current_xact_id(); RETURN NEW; END IF;
|
||||
IF(to_jsonb(OLD)-ARRAY['claim_token','claim_attempted_at','used_rows','used_bytes','storage_state','compact_at','archive_bytes','original_activity_at']) IS DISTINCT FROM
|
||||
(to_jsonb(NEW)-ARRAY['claim_token','claim_attempted_at','used_rows','used_bytes','storage_state','compact_at','archive_bytes','original_activity_at']) THEN RAISE EXCEPTION 'poll admission identity is immutable'; END IF;
|
||||
IF OLD.storage_state<>'full' THEN RAISE EXCEPTION 'compacted poll identity cannot reopen or change'; END IF;
|
||||
IF NEW.storage_state='compacted' THEN
|
||||
SELECT * INTO r FROM public.server_poll_archives WHERE receipt_id=OLD.receipt_id AND compaction_xid=pg_current_xact_id();
|
||||
IF NOT FOUND OR NEW.used_rows<>OLD.used_rows OR NEW.used_bytes<>OLD.used_bytes OR NEW.claim_token IS DISTINCT FROM OLD.claim_token
|
||||
OR NEW.claim_attempted_at IS DISTINCT FROM OLD.claim_attempted_at OR NEW.archive_bytes<>r.ciphertext_bytes OR NEW.original_activity_at<>r.original_activity_at
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_executions WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_intents WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_acks WHERE receipt_id=OLD.receipt_id)
|
||||
OR EXISTS(SELECT 1 FROM public.server_poll_receipts WHERE receipt_id=OLD.receipt_id) OR EXISTS(SELECT 1 FROM public.server_poll_quarantines WHERE receipt_id=OLD.receipt_id)
|
||||
THEN RAISE EXCEPTION 'poll compaction requires the complete current-transaction archive'; END IF;
|
||||
NEW.compact_at:=r.created_at;
|
||||
UPDATE public.server_poll_storage_usage SET admissions=admissions-1,compacted_admissions=compacted_admissions+1,
|
||||
archive_bytes=archive_bytes+r.ciphertext_bytes,reserved_rows=reserved_rows-4019+2,reserved_bytes=reserved_bytes-8421376+32768+r.ciphertext_bytes
|
||||
WHERE scope IN('global','owner:'||OLD.owner_id) AND admissions>=1;
|
||||
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll compaction charge mismatch'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF NEW.compact_at IS NOT NULL OR NEW.archive_bytes IS NOT NULL OR NEW.original_activity_at IS NOT NULL THEN RAISE EXCEPTION 'full poll cannot carry archive metadata'; END IF;
|
||||
IF OLD.claim_token IS NOT NULL AND NEW.claim_token IS NULL AND OLD.claim_attempted_at IS NULL AND NEW.claim_attempted_at IS NOT NULL
|
||||
AND NEW.used_rows=OLD.used_rows AND NEW.used_bytes=OLD.used_bytes AND OLD.authority_expires_at>clock_timestamp()
|
||||
THEN NEW.claim_attempted_at:=clock_timestamp(); RETURN NEW; END IF;
|
||||
IF OLD.claim_token IS NOT DISTINCT FROM NEW.claim_token AND OLD.claim_attempted_at IS NOT DISTINCT FROM NEW.claim_attempted_at
|
||||
AND NEW.used_rows=OLD.used_rows+1 AND NEW.used_bytes>OLD.used_bytes THEN RETURN NEW; END IF;
|
||||
RAISE EXCEPTION 'poll admission cannot refresh, reopen or refund itself';
|
||||
END IF;
|
||||
IF NEW.storage_state<>'full' OR NEW.compact_at IS NOT NULL OR NEW.archive_bytes IS NOT NULL OR NEW.original_activity_at IS NOT NULL
|
||||
OR NEW.compaction_claim IS NOT NULL OR NEW.compaction_claimed_at IS NOT NULL OR NEW.compaction_claim_xid IS NOT NULL
|
||||
OR NOT public.server_poll_storage_accounting_valid() THEN RAISE EXCEPTION 'new poll requires full reservation and exact ledger'; END IF;
|
||||
SELECT requests_retention_days INTO retention FROM public.mcp_settings WHERE id=1;
|
||||
IF retention IS NULL OR retention NOT BETWEEN 1 AND 365 OR NEW.authority_issued_at>clock_timestamp() OR NEW.authority_expires_at<=clock_timestamp()
|
||||
OR NEW.claim_token IS NULL OR NEW.claim_attempted_at IS NOT NULL OR NEW.used_rows<>0 OR NEW.used_bytes<>0 THEN RAISE EXCEPTION 'new poll admission needs original live authority'; END IF;
|
||||
IF EXISTS(SELECT 1 FROM public.server_poll_storage_admissions WHERE receipt_id=NEW.receipt_id OR(identity_kind=NEW.identity_kind AND execution_id=NEW.execution_id)) THEN RAISE EXCEPTION 'poll identity already spent'; END IF;
|
||||
NEW.created_at:=clock_timestamp(); NEW.retention_days:=retention; NEW.safety_ms:=60000;
|
||||
NEW.gc_not_before:=NEW.authority_expires_at+make_interval(days=>retention)+interval '60 seconds';
|
||||
INSERT INTO public.server_poll_storage_usage(scope) VALUES('owner:'||NEW.owner_id) ON CONFLICT DO NOTHING;
|
||||
UPDATE public.server_poll_storage_usage SET admissions=admissions+1,reserved_rows=reserved_rows+4019,reserved_bytes=reserved_bytes+8421376 WHERE scope IN('global','owner:'||NEW.owner_id);
|
||||
GET DIAGNOSTICS charged=ROW_COUNT; IF charged<>2 THEN RAISE EXCEPTION 'poll admission counters unavailable'; END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
INSERT INTO public.schema_migrations (id) VALUES ('0059_server_poll_journal_limits') ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
COMMIT;
|
||||
+134
-1
@@ -464,6 +464,55 @@
|
||||
],
|
||||
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/nodes",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Служебная проекция для выбора площадок в интерфейсе. В MCP доступ к серверам определяется областью подключения."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/nodes/:serverId/inventory",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.inventory"],
|
||||
"reason": "Общее чтение интерфейсов, шлюзов и кандидата Router ID. MCP проверяет серверную область, а контекст редактируемого сегмента используется в WebUI."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.list"],
|
||||
"reason": "Общий сервис списка сегментов. MCP ограничивает выборку областью серверов и возвращает метаданные ревизий."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/linux",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Шаблон подключения Linux оператор получает в интерфейсе для локальной настройки клиента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/linux/path",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.linux-path"],
|
||||
"reason": "Общее чтение маршрутов Linux-клиента из применённой ревизии. MCP проверяет доступ к узлу клиента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/segments/:id/status",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.read"],
|
||||
"reason": "Общий опрос маршрутов и BGP-сессий применённой ревизии. MCP проверяет доступ ко всем узлам сегмента."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/ix/topology",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Проекция применённых связей для сетевой карты. MCP читает конфигурацию и состояние отдельных сегментов."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
"path": "/api/logs",
|
||||
@@ -1071,7 +1120,7 @@
|
||||
"operations": [
|
||||
"traffic.live.read"
|
||||
],
|
||||
"reason": "Общий readTrafficLiveSample; MCP возвращает ограниченную серию до трёх срезов вместо бесконечного SSE. Полнота суммы, направление RX/TX, отзыв доступа и смена источника проверяются перед каждым новым native-запросом."
|
||||
"reason": "Общий readTrafficLiveSample для разового чтения интерфейса, SSE и ограниченной MCP-серии. Источник проверяется перед каждым новым native-запросом."
|
||||
},
|
||||
{
|
||||
"method": "GET",
|
||||
@@ -1562,6 +1611,76 @@
|
||||
],
|
||||
"reason": "Общий REST/MCP executor существующего сертификата: оба selector и все роли, явный private/CA intent, human MCP plan, actor/key no-replay, exact owned file/read/cleanup, encrypted owner-only artifact/TTL; синтетическая SQL/HTTP/portal и browser приёмка. Native CHR отдельно."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/preview",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Локальный предпросмотр объектов из компилятора. План MCP дополнительно фиксирует состояние площадок и требует подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/plan",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.configure"],
|
||||
"reason": "Предпросмотр сохранённой ревизии для оператора. MCP строит отдельный план через общий сервис IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/apply",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.configure"],
|
||||
"reason": "Пользователь WebUI подтверждает просмотренную ревизию. MCP применяет свой подтверждённый план через общий исполнитель IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI сохраняет одной ревизией клиента Linux и выбранный транзит. Записи на RouterOS идут после подтверждения изменений."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux/credential",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI выдаёт действующий PSK или ключ WireGuard оператору с правом изменения сети и записью в журнале. Для WireGuard MCP возвращает защищённую ссылку через network.wireguard.export."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/linux/revoke",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "WebUI сохраняет черновик отзыва клиента. Удаление конфигурации RouterOS выполняется отдельным подтверждённым планом."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/removal-plan",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.delete"],
|
||||
"reason": "Предпросмотр управляемых объектов перед явным подтверждением удаления сегмента."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments/:id/transit",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Мастер WebUI собирает черновик связи и выхода по инвентарю двух узлов. Применение к обоим маршрутизаторам требует отдельного подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "DELETE",
|
||||
"path": "/api/ix/segments/:id",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.delete"],
|
||||
"reason": "Общий исполнитель удаления проверяет ревизию и очищает управляемые объекты IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/ix/segments",
|
||||
"status": "excluded",
|
||||
"operations": [],
|
||||
"reason": "Сохранение черновика из интерфейса. Для изменения конфигурации через MCP используется план с подтверждением."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/mcp/connections",
|
||||
@@ -1632,6 +1751,20 @@
|
||||
"operations": ["network.bridge-vlan.configure"],
|
||||
"reason": "Подготовка связанного плана bridge/VLAN через тот же MCP-инструмент; выполнение требует человеческого подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/mcp/ix/plan",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.configure"],
|
||||
"reason": "Интерфейс владельца вызывает тот же инструмент MCP подготовки плана IX. Применение проходит отдельно после подтверждения."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/mcp/ix/restore",
|
||||
"status": "mediated",
|
||||
"operations": ["network.ix.restore"],
|
||||
"reason": "Интерфейс владельца вызывает тот же инструмент MCP подготовки восстановления сохранённой ревизии IX."
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/api/mcp/management-channels",
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { isIPv4 } from "node:net"
|
||||
import { homedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
const targets = process.env.MMAPP_IX_CHR_HOSTS?.split(",").map(value => value.trim()) ?? []
|
||||
if (targets.length !== 2 || new Set(targets).size !== 2 || !targets.every(isIPv4)) {
|
||||
throw new Error("MMAPP_IX_CHR_HOSTS must identify two distinct, isolated CHR IPv4 addresses")
|
||||
}
|
||||
export const hosts = [targets[0], targets[1]] as const
|
||||
const key = join(homedir(), ".ssh", "chr_claude")
|
||||
const known = process.env.MMAPP_IX_TEST_KNOWN_HOSTS ?? join(homedir(), ".ssh", "known_hosts")
|
||||
|
||||
export const quote = (value: string) => '"' + value.replace(/[\\"$]/g, "\\$&").replace(/\n/g, "\\n") + '"'
|
||||
export const sshOptions = ["-F", process.platform === "win32" ? "NUL" : "/dev/null", "-i", key,
|
||||
"-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "UserKnownHostsFile=" + known,
|
||||
"-o", "ConnectTimeout=12", "-o", "LogLevel=ERROR"]
|
||||
|
||||
export function cli(side: number, expression: string, stage?: string) {
|
||||
const args = [...sshOptions, "claude@" + hosts[side],
|
||||
`:onerror err in={ ${expression.replace(/\r?\n\s*/g, " ")}; :put "IX_OK" } do={ :put ("IX_ERROR:" . $err) }`]
|
||||
const run = () => execFileSync("ssh", args, { encoding: "utf8", timeout: 35000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }).trim()
|
||||
let stdout: string
|
||||
try {
|
||||
for (let attempt = 0;; attempt++) {
|
||||
try { stdout = run(); break } catch (error) {
|
||||
// Retry only when the command could not have reached the router.
|
||||
const failure = error as { status?: number; stderr?: string; stdout?: string }
|
||||
if (attempt >= 2 || failure.status !== 255 || failure.stdout || !/^ssh: connect to host .* port 22: Connection timed out\s*$/i.test(failure.stderr ?? "")) throw error
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (stage) throw Error(`CHR ${side + 1}: SSH failed during ${stage}`)
|
||||
throw error
|
||||
}
|
||||
if (!stdout.split(/\r?\n/).includes("IX_OK") || stdout.includes("IX_ERROR") || /syntax error|expected end|expected closing/.test(stdout)) {
|
||||
const diagnostic = stdout.replace(/[a-f0-9]{36,}/gi, "[redacted]").slice(0, 420)
|
||||
throw Error(`CHR ${side + 1} rejected ${stage ?? expression.slice(0, 360)} · ${diagnostic}`)
|
||||
}
|
||||
return stdout.replace(/\r?\n?IX_OK$/, "").trim()
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomBytes, randomUUID, X509Certificate } from "node:crypto"
|
||||
import { mkdtemp } from "node:fs/promises"
|
||||
import { createServer, isIPv4 } from "node:net"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { getCACertificates, setDefaultCACertificates } from "node:tls"
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
|
||||
import EmbeddedPostgres from "embedded-postgres"
|
||||
import { SignJWT } from "jose"
|
||||
import { ixNamespace } from "../../src/services/internet-exchange-plan.js"
|
||||
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
|
||||
|
||||
assert.deepEqual(process.argv.slice(2), ["--owned-test-pair"])
|
||||
for (const name of Object.keys(process.env)) {
|
||||
if (/^(DATABASE_|MCP_|AUTH_|PG|MMAPP_)/.test(name)) delete process.env[name]
|
||||
}
|
||||
process.env.DOTENV_CONFIG_PATH = join(tmpdir(), "mmapp-ix-no-env-" + randomUUID())
|
||||
|
||||
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 12)
|
||||
const segment = short + "-gre", gre = short + "-gre", pin = (side: number) => "10.245.0." + (1 + side)
|
||||
const psk = randomBytes(32).toString("hex"), password = randomBytes(24).toString("hex")
|
||||
const roots = getCACertificates("default")
|
||||
const certificates: string[] = []
|
||||
const entered = new Map<number, string>()
|
||||
const result: Record<string, unknown> = {}
|
||||
let appliedNamespace: string | undefined
|
||||
const ipsecPaths = ["/ip/ipsec/policy", "/ip/ipsec/identity", "/ip/ipsec/peer", "/ip/ipsec/proposal", "/ip/ipsec/profile"]
|
||||
const ixPaths = ["/ip/route", "/ip/address", "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge"]
|
||||
const sides = [0, 1]
|
||||
|
||||
function baseline(side: number) {
|
||||
return cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
|
||||
:put [/ip/service/print as-value proplist=disabled,port,certificate,address where name=www-ssl and dynamic=no];
|
||||
:put [:len [/interface/gre/find]]; :put [:len [/ip/vrf/find]];
|
||||
:put [:len [/ip/ipsec/peer/find]]; :put [:len [/ip/ipsec/installed-sa/find]];
|
||||
:put [:len [/ip/firewall/filter/find]]; :put [:len [/ipv6/firewall/filter/find]];
|
||||
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
|
||||
}
|
||||
|
||||
async function port() {
|
||||
const socket = createServer()
|
||||
await new Promise<void>((ok, fail) => socket.listen(0, "127.0.0.1", ok).on("error", fail))
|
||||
const value = (socket.address() as { port: number }).port
|
||||
await new Promise<void>((ok, fail) => socket.close(error => error ? fail(error) : ok()))
|
||||
return value
|
||||
}
|
||||
|
||||
async function until<T>(label: string, check: () => T | Promise<T>, timeout = 45000) {
|
||||
const end = Date.now() + timeout
|
||||
do {
|
||||
const value = await check()
|
||||
if (value) return value
|
||||
await delay(900)
|
||||
} while (Date.now() < end)
|
||||
throw Error(label + " timed out")
|
||||
}
|
||||
|
||||
function prepareGre(side: number) {
|
||||
const local = hosts[side], remote = hosts[1 - side]
|
||||
const p = quote(short)
|
||||
cli(side, `:put "profile"; /ip/ipsec/profile/add name=${p} enc-algorithm=aes-256 hash-algorithm=sha256 dh-group=modp2048;
|
||||
:put "proposal"; /ip/ipsec/proposal/add name=${p} enc-algorithms=aes-256-cbc auth-algorithms=sha256 pfs-group=modp2048;
|
||||
:put "peer"; /ip/ipsec/peer/add name=${p} address=${remote}/32 local-address=${local} profile=${p} exchange-mode=ike2 passive=${side ? "yes" : "no"};
|
||||
:put "identity"; /ip/ipsec/identity/add peer=${p} auth-method=pre-shared-key secret=${quote(psk)} comment=${p};
|
||||
:put "policy"; /ip/ipsec/policy/add peer=${p} src-address=${local}/32 dst-address=${remote}/32 protocol=gre action=encrypt level=require tunnel=no proposal=${p} comment=${p};
|
||||
:put "GRE"; /interface/gre/add name=${quote(gre)} local-address=${local} remote-address=${remote} allow-fast-path=no comment=${quote("IX:" + segment)};
|
||||
/ip/address/add address=${pin(side)}/30 interface=${quote(gre)} comment=${quote(ns + ":lab:gre")}`, "isolated IKEv2/GRE setup")
|
||||
}
|
||||
|
||||
async function openRest(side: number) {
|
||||
const sessions = cli(side, ':put [/user/active/print as-value proplist=address where name=claude and via=ssh]')
|
||||
const sources = [...new Set([...sessions.matchAll(/address=([\d.]+)/g)].map(match => match[1]))]
|
||||
assert(sources.length === 1 && isIPv4(sources[0]), "Cannot pin HTTPS to a single observed management address")
|
||||
const source = sources[0] + "/32", host = hosts[side], ca = short + "-ca", leaf = short + "-tls"
|
||||
cli(side, `/certificate/add name=${quote(ca)} common-name=${quote(ca)} key-usage=key-cert-sign,crl-sign days-valid=1;
|
||||
/certificate/sign [find where name=${quote(ca)}];
|
||||
/certificate/add name=${quote(leaf)} common-name=${quote(host)} subject-alt-name=IP:${host} key-usage=tls-server days-valid=1;
|
||||
/certificate/sign [find where name=${quote(leaf)}] ca=${quote(ca)};
|
||||
/certificate/export-certificate [find where name=${quote(ca)}] file-name=${quote(ca)}`)
|
||||
const certificate = cli(side, `:put [/file/get [find where name=${quote(ca + ".crt")}] contents]`)
|
||||
assert.equal(new X509Certificate(certificate).ca, true)
|
||||
certificates.push(certificate)
|
||||
setDefaultCACertificates([...roots, ...certificates])
|
||||
cli(side, `/ip/firewall/filter/add chain=input action=drop protocol=tcp dst-port=443 dst-address=${host}/32 src-address=!${source} comment=${quote(ns + ":lab:tls")};
|
||||
/user/group/add name=${quote(short)} policy=read,write,api,rest-api;
|
||||
/user/add name=${quote(short)} address=${source} group=${quote(short)} password=${quote(password)};
|
||||
/ip/service/set [find where name=www-ssl and dynamic=no] address=${source} certificate=${quote(leaf)} disabled=no`, "restricted HTTPS REST setup")
|
||||
let lastError = ""
|
||||
await until("router REST on verified HTTPS", async () => {
|
||||
const response = await fetch(`https://${host}/rest/system/resource`, {
|
||||
headers: { authorization: "Basic " + Buffer.from(short + ":" + password).toString("base64") }, signal: AbortSignal.timeout(5000),
|
||||
}).catch(error => { lastError = String(error.cause ?? error); return undefined })
|
||||
if (!response) return false
|
||||
assert.equal(response.status, 200, "REST test user was refused")
|
||||
assert.equal((await response.json()).version, "7.24.5 (stable)")
|
||||
return true
|
||||
}, 18000).catch(error => { throw Error(`CHR ${side + 1}: ${error.message} · ${lastError}`) })
|
||||
}
|
||||
|
||||
function clean(side: number, before: string) {
|
||||
const own = `where comment~${quote(appliedNamespace ? `^(${ns}|${appliedNamespace}):` : "^" + ns + ":")}`
|
||||
const checks = ixPaths.map(path => `[:len [${path}/find ${own}]]`)
|
||||
cli(side, `/ip/service/set [find where name=www-ssl and dynamic=no] disabled=yes address="" certificate=none;
|
||||
/user/remove [/user/find where name=${quote(short)}]; /user/group/remove [/user/group/find where name=${quote(short)}];
|
||||
/file/remove [/file/find where name=${quote(short + "-ca.crt")}];
|
||||
/certificate/remove [/certificate/find where name=${quote(short + "-tls")}];
|
||||
/certificate/remove [/certificate/find where name=${quote(short + "-ca")}];
|
||||
${ixPaths.map(path => `${path}/remove [${path}/find ${own}]`).join("; ")};
|
||||
/interface/gre/remove [/interface/gre/find where name=${quote(gre)} and comment=${quote("IX:" + segment)}];
|
||||
${ipsecPaths.map((path, i) => `${path}/remove [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]`).join("; ")}`)
|
||||
checks.push(...ipsecPaths.map((path, i) => `[:len [${path}/find where ${i < 2 ? "comment" : "name"}=${quote(short)}]]`),
|
||||
`[:len [/user/find where name=${quote(short)}]]`, `[:len [/user/group/find where name=${quote(short)}]]`,
|
||||
`[:len [/certificate/find where name~${quote("^" + short + "-(ca|tls)$")}]]`, `[:len [/file/find where name=${quote(short + "-ca.crt")}]]`)
|
||||
assert.equal(cli(side, ":put (" + checks.join("+") + ")"), "0")
|
||||
assert.equal(baseline(side), before)
|
||||
}
|
||||
|
||||
async function useManager() {
|
||||
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-mcp-"))
|
||||
process.chdir(root)
|
||||
const pgPort = await port(), httpPort = await port()
|
||||
const origin = `http://127.0.0.1:${httpPort}`, endpoint = new URL("/mcp", origin)
|
||||
const pgPassword = randomBytes(24).toString("hex"), jwtSecret = randomBytes(32).toString("hex")
|
||||
Object.assign(process.env, { DATABASE_URL: `postgresql://ixlab:${pgPassword}@127.0.0.1:${pgPort}/postgres`,
|
||||
NODE_ENV: "test", AUTH_REQUIRED: "true", AUTH_JWT_SECRET: jwtSecret, AUTH_ISSUER: origin,
|
||||
AUTH_PORTAL_URL: origin, MCP_STATE_DIR: join(root, "state"), MCP_PUBLIC_URL: endpoint.href, MCP_UI_URL: origin, CORS_ORIGIN: origin })
|
||||
const pg = new EmbeddedPostgres({ databaseDir: join(root, "db"), user: "ixlab", password: pgPassword, port: pgPort,
|
||||
persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], postgresFlags: ["-h", "127.0.0.1"],
|
||||
onLog: () => {}, onError: () => {} })
|
||||
await pg.initialise()
|
||||
await pg.start()
|
||||
const { pool, closePool } = await import("../../src/db/index.js")
|
||||
const { applySqlMigrations } = await import("../../src/db/migrate.js")
|
||||
const { buildApp } = await import("../../src/index.js")
|
||||
const { updateMcpSettings } = await import("../../src/modules/mcp/store.js")
|
||||
let app: Awaited<ReturnType<typeof buildApp>> | undefined
|
||||
const client = new Client({ name: "owned-ix-gre", version: "1.0.0" })
|
||||
try {
|
||||
await applySqlMigrations(pool)
|
||||
const serverIds: number[] = []
|
||||
for (const [side, host] of hosts.entries()) {
|
||||
const { rows } = await pool.query(`INSERT INTO servers(name,host,port,username,password,use_ssl,verify_ssl,enabled,type)
|
||||
VALUES($1,$2,443,$3,$4,true,true,true,'ix-node') RETURNING id`, [`ix-chr-${side + 1}`, host, short, password])
|
||||
serverIds.push(Number(rows[0].id))
|
||||
}
|
||||
const permissions = ["mm:network:read", "mm:network:write", "mm:mcp:admin", "mm:mcp:approve"]
|
||||
const actor = { id: "ix-fixture", email: "[email protected]", name: "IX fixture", apps: ["mm"], permissions,
|
||||
expiresAt: Date.now() + 1800000, issuedAt: Date.now() }
|
||||
await updateMcpSettings({ enabled: true }, actor)
|
||||
app = await buildApp({ startScheduler: false, logger: false })
|
||||
await app.listen({ port: httpPort, host: "127.0.0.1" })
|
||||
const jwt = await new SignJWT({ sub: actor.id, apps: actor.apps, permissions }).setProtectedHeader({ alg: "HS256" })
|
||||
.setIssuer(origin).setIssuedAt().setExpirationTime("15m").sign(new TextEncoder().encode(jwtSecret))
|
||||
async function rest(path: string, data?: object) {
|
||||
const response = await fetch(origin + "/api" + path, { method: data ? "POST" : "GET",
|
||||
headers: { authorization: "Bearer " + jwt, "content-type": "application/json" },
|
||||
...(data ? { body: JSON.stringify(data) } : {}), signal: AbortSignal.timeout(15000) })
|
||||
const body = await response.json()
|
||||
assert(response.ok, `${path}: ${response.status} ${JSON.stringify(body).slice(0, 600)}`)
|
||||
return body
|
||||
}
|
||||
const configuration = { name: segment, sites: serverIds.map((serverId, side) => ({
|
||||
serverId, routerId: pin(side), autonomousSystem: 64512 + side,
|
||||
interfaces: [{ name: gre, kind: "gre-ipsec", localEndpoint: hosts[side], endpoint: hosts[1 - side], peerServerId: serverIds[1 - side] }],
|
||||
})) }
|
||||
const draft = await rest("/ix/segments", { revision: 0, configuration })
|
||||
const segmentId: string = draft.segment.id
|
||||
assert.match(segmentId, /^[0-9a-f-]{36}$/)
|
||||
appliedNamespace = ixNamespace(segmentId)
|
||||
assert.equal(draft.segment.revision, 1)
|
||||
assert.equal(draft.segment.appliedRevision, null)
|
||||
result.managerRestDraft = true
|
||||
const { token } = await rest("/mcp/connections", { name: "Owned IX approval", mode: "approval", permissions: ["mm:network:read", "mm:network:write"],
|
||||
limits: { mutationsPerHour: 40, callsPerMinute: 120 },
|
||||
expiresAt: new Date(Date.now() + 600000).toISOString(), scope: { serverIds, allowGlobal: false,
|
||||
operationIds: ["network.ix.configure", "network.ix.read", "changes.apply", "operations.read"] } })
|
||||
await client.connect(new StreamableHTTPClientTransport(endpoint, {
|
||||
requestInit: { headers: { authorization: "Bearer " + token } },
|
||||
}), { timeout: 10000 })
|
||||
async function call(name: string, args: object, expectedError = false) {
|
||||
const reply = await client.callTool({ name, arguments: args }, undefined, { timeout: 120000 })
|
||||
assert.equal(Boolean(reply.isError), expectedError, name + " " + JSON.stringify(reply.structuredContent ?? reply.content).slice(0, 1200))
|
||||
return (reply.structuredContent as { result: any })?.result
|
||||
}
|
||||
const plan = await call("mm_ix_change_plan", { change: { id: segmentId, revision: 1, configuration } })
|
||||
assert.equal(plan.state, "awaiting-approval")
|
||||
const apply = { planId: plan.planId, idempotencyKey: randomUUID() }
|
||||
await call("mm_change_apply", apply, true)
|
||||
await rest("/mcp/plans/" + plan.planId + "/decision", { approve: true })
|
||||
const op = await call("mm_change_apply", apply)
|
||||
const terminal = await until("MCP terminal operation", async () => {
|
||||
const value = await call("mm_operation_get", { operationId: op.id })
|
||||
return !["pending", "running"].includes(value.state) && value
|
||||
}, 90000)
|
||||
assert.equal(terminal.state, "applied", JSON.stringify({ state: terminal.state, error: terminal.error_code }))
|
||||
assert.equal(terminal.verification, "passed")
|
||||
assert.equal((await call("mm_change_apply", apply)).id, op.id)
|
||||
const verified = await call("mm_ix_segment_get", { id: segmentId })
|
||||
assert.equal(verified.segment.appliedRevision, 2)
|
||||
const status = await rest("/ix/segments/" + segmentId + "/status")
|
||||
assert.deepEqual(status.sites.map(({ serverId, available }: { serverId: number; available: boolean }) => [serverId, available]),
|
||||
serverIds.map(serverId => [serverId, true]))
|
||||
result.mcpAppliedAndVerified = true
|
||||
result.routerRestSites = status.sites.length
|
||||
} finally {
|
||||
await client.close()
|
||||
await app?.close()
|
||||
await closePool()
|
||||
await pg.stop()
|
||||
}
|
||||
}
|
||||
|
||||
function packets(side: number) {
|
||||
assert(appliedNamespace)
|
||||
return Number(cli(side, `:put [/ping address=${pin(1 - side)} src-address=${pin(side)} vrf=${appliedNamespace} count=3 interval=250ms]`).split(/\r?\n/).at(-1))
|
||||
}
|
||||
|
||||
let failure: unknown
|
||||
try {
|
||||
const original = sides.map(baseline)
|
||||
for (const value of original) {
|
||||
const [version, board, ...expected] = value.split(/\r?\n/)
|
||||
assert.equal(version, "7.24.5 (stable)")
|
||||
assert.match(board, /^CHR/)
|
||||
const [https, ...inventory] = expected
|
||||
assert.match(https, /(?:^|;)certificate=none;disabled=true;port=443$/)
|
||||
assert.deepEqual(inventory, ["0", "1", "0", "0", "0", "0", "1"])
|
||||
}
|
||||
for (const side of sides) {
|
||||
entered.set(side, original[side])
|
||||
prepareGre(side)
|
||||
}
|
||||
for (const side of sides) await openRest(side)
|
||||
console.log("Both RouterOS REST endpoints authenticated with temporary trusted HTTPS certificates")
|
||||
await useManager()
|
||||
console.log("MCP applied the reviewed configuration to both routers")
|
||||
await until("encrypted GRE forwarding", () => packets(0) === 3 && packets(1) === 3)
|
||||
const sas = sides.map(side => Number(cli(side, ":put [:len [/ip/ipsec/installed-sa/find where state=mature]]")))
|
||||
assert(sas.every(count => count === 2))
|
||||
result.greReplies = [3, 3]
|
||||
result.matureIpsecSAs = sas
|
||||
// Turn off both matching policies during the plaintext negative test.
|
||||
for (const side of sides) cli(side, `/ip/ipsec/policy/disable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
|
||||
for (const side of sides) assert.equal(packets(side), 0)
|
||||
result.plaintextGreBlocked = true
|
||||
for (const side of sides) cli(side, `/ip/ipsec/policy/enable [/ip/ipsec/policy/find where comment=${quote(short)}]`)
|
||||
await until("GRE recovery with required IPsec", () => packets(0) === 3 && packets(1) === 3)
|
||||
result.greRecovered = true
|
||||
} catch (error) {
|
||||
failure = error
|
||||
}
|
||||
setDefaultCACertificates(roots)
|
||||
let testStandRestored = true
|
||||
for (const [side, original] of entered) {
|
||||
try { clean(side, original) } catch (error) {
|
||||
console.error(`Cleanup unconfirmed on CHR ${side + 1} · ${ns} ${appliedNamespace ?? ""}`)
|
||||
testStandRestored = false
|
||||
failure ??= error
|
||||
}
|
||||
}
|
||||
console.log(JSON.stringify({ ...result, testStandRestored }))
|
||||
if (failure) throw failure
|
||||
@@ -0,0 +1,198 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomInt, randomUUID } from "node:crypto"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { ixSegmentConfigurationSchema } from "@mmapp/contracts/internet-exchange"
|
||||
import { compileIxConfiguration, ixDiscardInterface, ixNamespace } from "../../src/services/internet-exchange-plan.js"
|
||||
import { cli, hosts, quote } from "./ix-chr-ssh.mjs"
|
||||
|
||||
assert.equal(process.argv[2], "--owned-test-pair")
|
||||
assert(process.argv.length === 3 || (process.argv.length === 4 && process.argv[3] === "--ipv6"))
|
||||
const ipv6 = process.argv[3] === "--ipv6"
|
||||
const id = randomUUID(), ns = ixNamespace(id), short = ns.slice(0, 10)
|
||||
const discard = ixDiscardInterface(id)
|
||||
const marker = ns + ":lab", primary = short + "-p", backup = short + "-b"
|
||||
const port = randomInt(45000, 55000)
|
||||
const net = "10.247." + randomInt(32, 224)
|
||||
const [aP, bP, aB, bB] = ipv6 ? ["fd00:247:1::1", "fd00:247:1::2", "fd00:247:2::1", "fd00:247:2::2"] : [1, 2, 5, 6].map(n => net + "." + n)
|
||||
const [target, pProbe, bProbe, trafficSource] = ipv6 ? ["2001:db8:3::200", "2001:db8:3::201", "2001:db8:3::202", "2001:db8:3::203"] : ["192.0.2.200", "192.0.2.201", "192.0.2.202", "192.0.2.203"]
|
||||
const afi = ipv6 ? "ipv6" : "ip", length = ipv6 ? "/128" : "/32", gateway = ipv6 ? "fd00:198:18::101" : "198.18.0.101"
|
||||
const addressPath = "/" + afi + "/address", routePath = "/" + afi + "/route", filterPath = "/" + afi + "/firewall/filter", listPath = "/" + afi + "/firewall/address-list"
|
||||
const advertise: Record<string, string> = ipv6 ? { advertise: "no" } : {}
|
||||
const community = "65000:120"
|
||||
const entered = new Set<number>()
|
||||
const results: Record<string, unknown> = {}
|
||||
const pending: string[][] = [[], []]
|
||||
|
||||
const fields = (values: Record<string, string>) => Object.entries(values).map(([name, value]) => name === "blackhole" && value === "yes" ? name : name + "=" + quote(value)).join(" ")
|
||||
function add(side: number, path: string, values: Record<string, string>, beforeMain = false) {
|
||||
pending[side].push(path + " add " + fields(values) + (beforeMain ? " place-before=[/ip/vrf/find where name=main]" : ""))
|
||||
}
|
||||
function flush(side: number) {
|
||||
while (pending[side].length) {
|
||||
const commands = pending[side].splice(0, 10)
|
||||
cli(side, commands.map((command, index) => `:put "IX_STAGE_${index}"; ${command}`).join("; "))
|
||||
}
|
||||
}
|
||||
function owned(side: number, path: string, values: Record<string, string>, tag: string) {
|
||||
add(side, path, { ...values, comment: marker + ":" + tag })
|
||||
}
|
||||
function preflight(side: number) {
|
||||
const data = cli(side, `:put [/system resource get version]; :put [/system resource get board-name];
|
||||
:put ([:len [/ip/vrf/find]]=1 && [:len [/interface/wireguard/find]]=0 && [:len [/routing/bgp/connection/find]]=0 && [:len [/ip/firewall/filter/find]]=0 && [:len [/ipv6/firewall/filter/find]]=0);
|
||||
:put [:len [/ip/address/find where address~${quote("^" + hosts[side] + "/")}]]`)
|
||||
const [version, board, empty, address] = data.split(/\r?\n/)
|
||||
assert.equal(version, "7.24.5 (stable)")
|
||||
assert.match(board, /^CHR/)
|
||||
assert.equal(empty, "true", "Stand changed, refusing a modified baseline")
|
||||
assert.equal(address, "1", "Expected test WAN address missing")
|
||||
}
|
||||
|
||||
const config = ixSegmentConfigurationSchema.parse({
|
||||
name: "ix-acceptance",
|
||||
sites: [
|
||||
{ serverId: 501, autonomousSystem: 64512, routerId: net + ".5",
|
||||
interfaces: [{ name: primary, kind: "wireguard", peerServerId: 502 }, { name: backup, kind: "wireguard", peerServerId: 502 }],
|
||||
groups: [{ id: "far", gateway, primary: { interface: primary, nextHop: bP, probe: pProbe },
|
||||
backup: { interface: backup, nextHop: bB, probe: bProbe } }],
|
||||
neighbors: [{ id: "feed", type: "public-feed", address: bB, localAddress: aB, remoteAs: 64513, binding: backup, rules: [{ community, group: "far" }] }],
|
||||
},
|
||||
{ serverId: 502, autonomousSystem: 64513, routerId: net + ".6",
|
||||
interfaces: [{ name: primary, kind: "wireguard", peerServerId: 501 }, { name: backup, kind: "wireguard", peerServerId: 501 }] },
|
||||
],
|
||||
})
|
||||
const compiled = compileIxConfiguration(id, config)
|
||||
const deferred = new Set([routePath, "/routing/bgp/instance", "/routing/filter/rule", "/routing/bgp/connection"])
|
||||
const cleanupPaths = [...deferred].reverse().concat(listPath,
|
||||
"/interface/wireguard/peers", addressPath, "/ip/firewall/filter", "/ipv6/firewall/filter", "/ip/vrf", "/interface/bridge", "/interface/wireguard")
|
||||
|
||||
function clean(side: number) {
|
||||
const where = `where comment~${quote("^" + ns + ":")}`
|
||||
cli(side, cleanupPaths.map(path => `${path} remove [${path}/find ${where}]`).join("; "))
|
||||
assert.equal(cli(side, `:put (${cleanupPaths.map(path => `[:len [${path}/find ${where}]]`).join("+")})`), "0")
|
||||
preflight(side)
|
||||
}
|
||||
|
||||
function observe() {
|
||||
return cli(0, `:put [/routing/route/print as-value where dst-address=${quote(target + length)} and routing-table=${quote(ns)}]`)
|
||||
}
|
||||
async function until(label: string, check: () => boolean, timeout = 75000) {
|
||||
const start = Date.now()
|
||||
while (!check()) {
|
||||
if (Date.now() - start > timeout) throw new Error(label + " timeout: " + observe())
|
||||
await delay(900)
|
||||
}
|
||||
return Date.now() - start
|
||||
}
|
||||
function hasPath(name: string) {
|
||||
const fields = observe().split(";")
|
||||
return fields.includes("bgp=true") && fields.includes("active=true") && fields.some(field => field.startsWith("immediate-gw=") && field.endsWith("%" + name))
|
||||
}
|
||||
function establishedSession() {
|
||||
const session = cli(0, `:put [/routing/bgp/session/print as-value where name~${quote(ns + "-feed")}]`).split(";")
|
||||
assert.ok(session.includes("established=true"))
|
||||
assert.ok(session.includes("prefix-count=1"))
|
||||
const started = session.find(field => field.startsWith("last-started="))
|
||||
assert.ok(started)
|
||||
return started
|
||||
}
|
||||
function packetProbe(destination: string, source?: string, side = 0, routingTable = ns) {
|
||||
return Number(cli(side, `:put [/ping address=${destination} vrf=${routingTable} count=3 interval=250ms${source ? " src-address=" + source : ""}]`).split(/\r?\n/).at(-1))
|
||||
}
|
||||
|
||||
async function run() {
|
||||
preflight(0); preflight(1)
|
||||
for (let side = 0; side < 2; side++) {
|
||||
entered.add(side)
|
||||
for (const [index, name] of [primary, backup].entries()) owned(side, "/interface/wireguard", { name, "listen-port": String(port + index), vrf: "main" }, "wg" + index)
|
||||
for (const object of compiled.filter(object => object.serverId === 501 + side && !deferred.has(object.path))) {
|
||||
add(side, object.path, object.fields, object.path === "/ip/vrf")
|
||||
if (object.path === "/ip/vrf") {
|
||||
flush(side)
|
||||
await until("VRF interface", () => cli(side, `:put [:len [/interface/find where name=${quote(ns)}]]`) === "1", 9000)
|
||||
}
|
||||
}
|
||||
for (const [index, name] of [primary, backup].entries()) {
|
||||
owned(side, "/ip/firewall/filter", { chain: "input", action: "accept", protocol: "udp", "src-address": hosts[1 - side] + "/32", "dst-port": String(port + index) }, "allow-wg" + index)
|
||||
const inner = (side ? [bP, bB] : [aP, aB])[index]
|
||||
owned(side, addressPath, { address: inner + (ipv6 ? "/64" : "/30"), interface: name, ...advertise }, "address" + index)
|
||||
}
|
||||
flush(side)
|
||||
}
|
||||
for (const [index, name] of [primary, backup].entries()) {
|
||||
const keys = [0, 1].map(side => cli(side, `:put [/interface/wireguard/get [/interface/wireguard/find where name=${quote(name)}] public-key]`))
|
||||
keys.forEach(value => assert.match(value, /^[A-Za-z0-9+/]{43}=$/))
|
||||
for (const side of [0, 1]) owned(side, "/interface/wireguard/peers", { interface: name, "public-key": keys[1 - side], "endpoint-address": hosts[1 - side],
|
||||
"endpoint-port": String(port + index), "allowed-address": (side
|
||||
? [index ? aB : aP, trafficSource]
|
||||
: [index ? bB : bP, target, index ? bProbe : pProbe]).map(address => address + length).join(","),
|
||||
"persistent-keepalive": "5" }, "peer" + index)
|
||||
}
|
||||
for (const [index, address] of [target, pProbe, bProbe].entries()) {
|
||||
owned(1, addressPath, { address: address + length, interface: discard, ...advertise }, "destination" + index)
|
||||
}
|
||||
owned(0, addressPath, { address: trafficSource + length, interface: discard, ...advertise }, "source")
|
||||
// Keep the same source and return path across both forward paths.
|
||||
owned(1, routePath, { "dst-address": trafficSource + length, "routing-table": ns,
|
||||
gateway: aB + "%" + backup + "@" + ns, "target-scope": "10" }, "return")
|
||||
const control = { chain: "input", "in-interface": ns, protocol: "tcp", "src-address": aB + length, action: "accept" }
|
||||
const beforeDeny = " place-before=[" + filterPath + "/find where comment=" + quote(ns + ":deny-input-" + (ipv6 ? "6" : "4")) + "]"
|
||||
cli(1, [fields({ ...control, "dst-port": "179", comment: marker + ":bgp-accept" }),
|
||||
fields({ ...control, "src-port": "179", "connection-state": "established", comment: marker + ":bgp-reply" })]
|
||||
.map(rule => filterPath + " add " + rule + beforeDeny).join("; "))
|
||||
owned(1, listPath, { list: short + "-net", address: target + length }, "network")
|
||||
owned(1, "/routing/bgp/instance", { name: ns, as: "64513", "router-id": net + ".6", vrf: ns, "routing-table": ns }, "instance")
|
||||
owned(1, "/routing/filter/rule", { chain: short + "-out", rule: `if (dst == ${target}${length}) { set bgp-communities ${community}; accept; } reject;` }, "export")
|
||||
owned(1, "/routing/bgp/connection", { name: short + "-export", instance: ns, afi, "local.role": "ebgp", "local.address": bB,
|
||||
"remote.address": aB + length, "remote.as": "64512", vrf: ns, "routing-table": ns, "output.network": short + "-net", "output.filter-chain": short + "-out" }, "connection")
|
||||
for (const object of compiled.filter(object => object.serverId === 501 && deferred.has(object.path))) add(0, object.path, object.fields)
|
||||
flush(1); flush(0)
|
||||
await until("primary WireGuard transport", () => packetProbe(bP, aP) === 3, 40000)
|
||||
await until("backup WireGuard transport", () => packetProbe(bB, aB) === 3, 40000)
|
||||
await until("BGP primary route", () => hasPath(primary))
|
||||
const session = establishedSession()
|
||||
results.bgpEstablished = true
|
||||
results.primaryRoute = observe()
|
||||
results.primaryReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.primaryReplies, 3)
|
||||
assert.equal(cli(0, `:put [:len [/routing/route/find where dst-address=${quote(target + length)} and routing-table=main]]`), "0", "BGP prefix must not leak to main")
|
||||
results.mainIsolated = true
|
||||
|
||||
// Drop only A's test UDP flow on the remote end. Interfaces remain enabled,
|
||||
// so this exercises probe-driven failover rather than administrative down.
|
||||
cli(1, "/ip/firewall/filter add " + fields({ chain: "input", action: "drop", protocol: "udp", "src-address": hosts[0] + "/32",
|
||||
"dst-port": String(port), comment: marker + ":cut" }) + " place-before=[/ip/firewall/filter/find where comment=" + quote(marker + ":allow-wg0") + "]")
|
||||
results.failoverMs = await until("primary underlay loss", () => hasPath(backup))
|
||||
results.backupRoute = observe()
|
||||
results.backupReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.backupReplies, 3)
|
||||
assert.equal(establishedSession(), session)
|
||||
cli(1, "/ip/firewall/filter remove [/ip/firewall/filter/find where comment=" + quote(marker + ":cut") + "]")
|
||||
results.failbackMs = await until("primary recovery", () => hasPath(primary))
|
||||
results.recoveredReplies = packetProbe(target, trafficSource)
|
||||
assert.equal(results.recoveredReplies, 3)
|
||||
assert.equal(establishedSession(), session)
|
||||
results.bgpSessionKept = true
|
||||
}
|
||||
|
||||
let failure: unknown
|
||||
try { await run() } catch (error) {
|
||||
failure = error
|
||||
for (const side of entered) try {
|
||||
console.error(`Test CHR ${side + 1} · ${cli(side, `:put [/routing/bgp/session/print as-value];
|
||||
:put [/interface/wireguard/peers/print as-value proplist=interface,rx,tx,last-handshake,current-endpoint-address where comment~${quote("^" + ns + ":")}];
|
||||
${filterPath}/print stats where comment~${quote("^" + ns + ":")};
|
||||
:put [${addressPath}/print as-value proplist=address,interface,invalid where comment~${quote("^" + ns + ":")}];
|
||||
:put [/routing/route/print as-value where routing-table=${quote(ns)}]; :put [/routing/nexthop/print as-value where address~${quote(gateway)}]`).slice(0, 8500)}`)
|
||||
} catch { /* Preserve the original failure and continue cleanup. */ }
|
||||
}
|
||||
for (const side of entered) {
|
||||
try { clean(side) } catch (error) {
|
||||
console.error(`Cleanup unconfirmed on test CHR ${side + 1} for ${ns}: ${error}`)
|
||||
failure ??= error
|
||||
}
|
||||
}
|
||||
if (failure) {
|
||||
console.error(JSON.stringify(results))
|
||||
throw failure
|
||||
}
|
||||
console.log(JSON.stringify({ ...results, testStandRestored: true }))
|
||||
@@ -0,0 +1,386 @@
|
||||
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 { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
|
||||
import EmbeddedPostgres from "embedded-postgres"
|
||||
|
||||
const dir = await mkdtemp(join(tmpdir(), "mm-ix-web-"))
|
||||
const socket = createServer()
|
||||
await new Promise<void>(resolve => socket.listen(0, "127.0.0.1", resolve))
|
||||
const pgPort = (socket.address() as { port: number }).port
|
||||
await new Promise<void>(resolve => socket.close(() => resolve()))
|
||||
const password = randomBytes(24).toString("hex")
|
||||
const pg = new EmbeddedPostgres({ databaseDir: join(dir, "pg"), user: "ixlab", password,
|
||||
port: pgPort, persistent: false, initdbFlags: ["--encoding=UTF8", "--no-locale"], onLog() {} })
|
||||
Object.assign(process.env, {
|
||||
NODE_ENV: "test", DATABASE_URL: `postgres://ixlab:${password}@127.0.0.1:${pgPort}/postgres`,
|
||||
MCP_STATE_DIR: join(dir, "state"), AUTH_REQUIRED: "true", AUTH_JWT_SECRET: randomBytes(32).toString("hex"),
|
||||
DATABASE_PATH: join(dir, "no-legacy.sqlite"),
|
||||
})
|
||||
await pg.initialise()
|
||||
await pg.start()
|
||||
const rows: Record<string, Record<string, string>[]> = {
|
||||
"/ip/vrf": [{ ".id": "*1", name: "main", interfaces: "all", builtin: "true" }],
|
||||
"/interface": [{ ".id": "*A0", name: "gre-client", type: "gre", comment: "IX:ix-web-fixture" }],
|
||||
"/interface/gre": [{ ".id": "*A0", name: "gre-client", "local-address": "192.0.2.20", "remote-address": "192.0.2.21", "allow-fast-path": "false" }],
|
||||
"/ip/ipsec/policy": [{ ".id": "*A1", "src-address": "192.0.2.20/32", "dst-address": "192.0.2.21/32",
|
||||
protocol: "gre", action: "encrypt", level: "require", tunnel: "false", disabled: "false" }],
|
||||
}
|
||||
let writes = 0
|
||||
let deletes = 0
|
||||
let failPutAt = -1
|
||||
let failDeleteAt = -1
|
||||
const router = createServer(async (request, response) => {
|
||||
try {
|
||||
const path = new URL(request.url!, "http://127.0.0.1").pathname.replace(/^\/rest/, "")
|
||||
let result: unknown
|
||||
if (request.method === "GET") result = rows[path] ?? []
|
||||
else if (request.method === "PUT") {
|
||||
if (writes === failPutAt) throw Error("Synthetic RouterOS apply failure")
|
||||
let raw = ""
|
||||
for await (const chunk of request) raw += chunk
|
||||
const { "place-before": place, ...fields } = JSON.parse(raw)
|
||||
const row = { ...fields, ...(path === "/interface/wireguard" && { "public-key": "B".repeat(43) + "=" }),
|
||||
".id": "*" + (++writes + 1).toString(16).toUpperCase() }
|
||||
const list = rows[path] ??= []
|
||||
const index = list.findIndex(entry => entry[".id"] === place)
|
||||
list.splice(index < 0 ? list.length : index, 0, row)
|
||||
if (path === "/ip/vrf" || path === "/interface/wireguard" || path === "/interface/bridge") {
|
||||
rows["/interface"].push({ ".id": row[".id"], name: row.name,
|
||||
type: path === "/interface/wireguard" ? "wg" : path.split("/").at(-1)!, comment: row.comment })
|
||||
}
|
||||
result = row
|
||||
} else if (request.method === "DELETE") {
|
||||
if (deletes === failDeleteAt) throw Error("Synthetic RouterOS deletion failure")
|
||||
const parent = path.slice(0, path.lastIndexOf("/"))
|
||||
const id = decodeURIComponent(path.slice(path.lastIndexOf("/") + 1))
|
||||
const index = (rows[parent] ?? []).findIndex(row => row[".id"] === id)
|
||||
assert(index >= 0)
|
||||
const [deleted] = rows[parent].splice(index, 1)
|
||||
rows["/interface"] = rows["/interface"].filter(row => row.name !== deleted.name || row[".id"] !== id)
|
||||
deletes++
|
||||
response.statusCode = 204
|
||||
response.end()
|
||||
return
|
||||
} else throw Error("Unexpected native verb: " + request.method)
|
||||
response.setHeader("content-type", "application/json")
|
||||
response.end(JSON.stringify(result))
|
||||
} catch (error) {
|
||||
response.statusCode = 500
|
||||
response.end(JSON.stringify({ error: String(error) }))
|
||||
}
|
||||
})
|
||||
const { initDatabase } = await import("../../src/db/bootstrap.js")
|
||||
const { pool } = await import("../../src/db/index.js")
|
||||
let app: Awaited<ReturnType<typeof import("../../src/index.js").buildApp>> | undefined
|
||||
let mcp: Client | undefined
|
||||
try {
|
||||
await initDatabase()
|
||||
assert.equal((await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled, false)
|
||||
await new Promise<void>(resolve => router.listen(0, "127.0.0.1", resolve))
|
||||
const port = (router.address() as { port: number }).port
|
||||
const { rows: [server] } = await pool.query(`INSERT INTO servers
|
||||
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
|
||||
VALUES('owned-ix','127.0.0.1',$1,true,'ix-node','synthetic','synthetic',false,true) RETURNING id`, [port])
|
||||
const { buildApp } = await import("../../src/index.js")
|
||||
const { env } = await import("../../src/config.js")
|
||||
app = await buildApp({ logger: false, startScheduler: false })
|
||||
const origin = await app.listen({ host: "127.0.0.1", port: 0 })
|
||||
const token = (owner: string, permission: string) => app!.jwt.sign({ iss: env.authIssuer, sub: owner,
|
||||
apps: ["mm"], permissions: [permission], iat: Math.floor(Date.now() / 1000) - 1, exp: Math.floor(Date.now() / 1000) + 600 })
|
||||
const writer = token("ix-web-owner", "mm:network:write")
|
||||
const reader = token("ix-web-reader", "mm:network:read")
|
||||
const otherWriter = token("ix-web-other-owner", "mm:network:write")
|
||||
async function post(path: string, payload: object, status: number, jwt = writer, method = "POST") {
|
||||
const reply = await fetch(origin + "/api/ix/segments" + path, { method,
|
||||
headers: { "content-type": "application/json", ...(jwt ? { authorization: "Bearer " + jwt } : {}) },
|
||||
body: JSON.stringify(payload), signal: AbortSignal.timeout(30_000) })
|
||||
const data = reply.status === 204 ? undefined : await reply.json()
|
||||
assert.equal(reply.status, status, JSON.stringify(data))
|
||||
return data
|
||||
}
|
||||
const configuration = { name: "ix-web-fixture", sites: [{ serverId: Number(server.id),
|
||||
autonomousSystem: 64512, routerId: "192.0.2.5", interfaces: [{ name: "wg-ix-web", kind: "wireguard",
|
||||
prefixes: ["2001:db8:12::/48"], provisionWireguard: { peerPublicKey: "A".repeat(43) + "=",
|
||||
listenPort: 51820, localAddress: "10.20.30.1/30", peerAddress: "10.20.30.2", hubEndpoint: "192.0.2.20" } },
|
||||
{ name: "gre-client", kind: "gre-ipsec", localEndpoint: "192.0.2.20", endpoint: "192.0.2.21" }] }] }
|
||||
const { segment } = await post("", { revision: 0, configuration }, 200)
|
||||
assert.equal(segment.revision, 1)
|
||||
assert.equal(segment.appliedRevision, null)
|
||||
const path = "/" + segment.id
|
||||
const linux = async (name?: string, status = 200) => {
|
||||
const query = name ? "?" + new URLSearchParams({ serverId: String(server.id), interfaceName: name }) : ""
|
||||
const response = await fetch(origin + "/api/ix/segments" + path + "/linux" + query, { headers: { authorization: "Bearer " + reader } })
|
||||
const body = await response.json()
|
||||
assert.equal(response.status, status, JSON.stringify(body))
|
||||
return body
|
||||
}
|
||||
assert.deepEqual(await linux(), { revision: null, items: [] })
|
||||
const { digest, changes } = await post(path + "/plan", { revision: 1 }, 200)
|
||||
assert(changes.some((step: { path: string }) => step.path === "/interface/wireguard/peers"))
|
||||
await post(path + "/apply", { revision: 1, digest }, 401, "")
|
||||
await post(path + "/apply", { revision: 1, digest }, 403, reader)
|
||||
await post(path + "/apply", { revision: 1, digest }, 409, otherWriter)
|
||||
await post(path + "/apply", { revision: 1, digest: "0".repeat(64) }, 409)
|
||||
rows["/interface"].push({ ".id": "*F0", name: "test-drift", type: "ether" })
|
||||
await post(path + "/apply", { revision: 1, digest }, 409)
|
||||
assert.equal(writes, 0)
|
||||
const fresh = await post(path + "/plan", { revision: 1 }, 200)
|
||||
await post(path + "/plan", { revision: 1, resume: true }, 409)
|
||||
const protectionId = randomUUID()
|
||||
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES ($1,$2,'ix-web-owner')",
|
||||
[protectionId, { kind: "server", id: String(server.id), protection: "deny" }])
|
||||
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
|
||||
assert.equal(writes, 0)
|
||||
await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protectionId])
|
||||
failPutAt = 1
|
||||
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 503)
|
||||
assert.equal(writes, 1)
|
||||
await post(path + "/plan", { revision: 1 }, 409)
|
||||
failPutAt = -1
|
||||
const resume = await post(path + "/plan", { revision: 1, resume: true }, 200)
|
||||
assert.equal(resume.changes.length, changes.length - 1)
|
||||
const applied = await post(path + "/apply", { revision: 1, digest: resume.digest, resume: true }, 200)
|
||||
assert.equal(applied.segment.appliedRevision, 2)
|
||||
assert.equal(applied.result.configurationVerified, true)
|
||||
assert.equal(applied.result.forwardingVerified, false)
|
||||
const resultWrites = writes
|
||||
assert.equal(resultWrites, changes.length)
|
||||
const clients = await linux()
|
||||
assert.equal(clients.revision, 2)
|
||||
assert.deepEqual(clients.items.map((item: { kind: string }) => item.kind), ["wireguard", "gre-ipsec"])
|
||||
const wg = await linux("wg-ix-web")
|
||||
assert.match(wg.template, /Endpoint = 192\.0\.2\.20:51820/)
|
||||
assert.match(wg.template, /Table = off/)
|
||||
assert(!wg.template.includes("A".repeat(43)))
|
||||
await post(path + "/linux/credential", { serverId: Number(server.id), interfaceName: "wg-ix-web" }, 404)
|
||||
const gre = await linux("gre-client")
|
||||
assert.match(gre.template, /local_ts = 192\.0\.2\.21\/32\[47\]/)
|
||||
assert.match(gre.template, /remote_ts = 192\.0\.2\.20\/32\[47\]/)
|
||||
assert.match(gre.template, /mode = transport/)
|
||||
assert.match(gre.setup, /mode gre local 192\.0\.2\.21 remote 192\.0\.2\.20/)
|
||||
rows["/ip/ipsec/policy"][0].disabled = "true"
|
||||
await linux("gre-client", 409)
|
||||
rows["/ip/ipsec/policy"][0].disabled = "false"
|
||||
rows["/interface/wireguard/peers"][0].disabled = "true"
|
||||
await linux("wg-ix-web", 409)
|
||||
delete rows["/interface/wireguard/peers"][0].disabled
|
||||
await post(path + "/apply", { revision: 1, digest: fresh.digest }, 409)
|
||||
assert.equal(writes, resultWrites)
|
||||
|
||||
const next = await post("", { id: segment.id, revision: 2, configuration: { ...configuration,
|
||||
sites: [{ ...configuration.sites[0], discardNetworks: ["2001:db8:ff::/48"] }] } }, 200)
|
||||
assert.equal(next.segment.appliedRevision, 2)
|
||||
assert.equal((await linux("wg-ix-web")).revision, 2)
|
||||
const members = rows["/interface/list/member"]
|
||||
members.push({ ".id": "*FE", list: rows["/interface/list"][0].name, interface: "test-drift" })
|
||||
const foreign = await post(path + "/plan", { revision: 3 }, 409)
|
||||
assert.match(foreign.error, /посторонний интерфейс/)
|
||||
members.pop()
|
||||
const nextPlan = await post(path + "/plan", { revision: 3 }, 200)
|
||||
await post(path + "/apply", { revision: 3, digest: nextPlan.digest }, 200)
|
||||
assert(rows["/ipv6/route"].some(row => row["dst-address"] === "2001:db8:ff::/48"))
|
||||
const { rows: [audit] } = await pool.query(`SELECT count(*)::int AS n FROM mcp_audit
|
||||
WHERE actor_id='ix-web-owner' AND action='configuration.acknowledged' AND connection_id IS NULL`)
|
||||
assert.equal(audit.n, writes)
|
||||
const { rows: [connections] } = await pool.query("SELECT count(*)::int AS n FROM mcp_connections")
|
||||
assert.equal(connections.n, 0)
|
||||
|
||||
const draftConfig = { ...configuration, name: "ix-web-draft" }
|
||||
const draft = (await post("", { revision: 0, configuration: draftConfig }, 200)).segment
|
||||
const draftPath = "/" + draft.id
|
||||
const draftRemoval = await post(draftPath + "/removal-plan", { revision: 1 }, 200)
|
||||
assert.deepEqual(draftRemoval.changes, [])
|
||||
const deleteDraft = { revision: 1, digest: draftRemoval.digest }
|
||||
await post(draftPath, deleteDraft, 403, reader, "DELETE")
|
||||
await post(draftPath, deleteDraft, 409, otherWriter, "DELETE")
|
||||
await post(draftPath, deleteDraft, 204, writer, "DELETE")
|
||||
assert.equal(deletes, 0)
|
||||
await post(draftPath, deleteDraft, 404, writer, "DELETE")
|
||||
const recreated = (await post("", { revision: 0, configuration: draftConfig }, 200)).segment
|
||||
|
||||
const removalInput = { revision: 4 }
|
||||
const blocked = await post(path + "/removal-plan", removalInput, 409)
|
||||
assert.match(blocked.error, /Отключите интерфейс.*gre-client/)
|
||||
rows["/interface"].find(row => row.name === "gre-client")!.disabled = "true"
|
||||
rows["/ip/address"].push({ ".id": "*FE", interface: "wg-ix-web", address: "192.0.2.1/32" })
|
||||
assert.match((await post(path + "/removal-plan", removalInput, 409)).error, /нет в применённой ревизии/)
|
||||
rows["/ip/address"].pop()
|
||||
const removal = await post(path + "/removal-plan", removalInput, 200)
|
||||
assert.equal(removal.changes.length, writes)
|
||||
assert(removal.changes.every((change: { action: string }) => change.action === "delete"))
|
||||
failDeleteAt = 1
|
||||
await post(path, { ...removalInput, digest: removal.digest }, 503, writer, "DELETE")
|
||||
assert.equal(deletes, 1)
|
||||
assert.equal((await pool.query("SELECT configuration->>'deleted' AS deleted FROM ix_segments WHERE id=$1", [segment.id])).rows[0].deleted, null)
|
||||
await post(path, { ...removalInput, digest: removal.digest }, 409, writer, "DELETE")
|
||||
failDeleteAt = -1
|
||||
const remaining = await post(path + "/removal-plan", removalInput, 200)
|
||||
assert.equal(remaining.changes.length, removal.changes.length - 1)
|
||||
await post(path, { ...removalInput, digest: remaining.digest }, 204, writer, "DELETE")
|
||||
assert.equal(deletes, writes)
|
||||
assert.equal(rows["/ip/ipsec/policy"].length, 1)
|
||||
assert.deepEqual(rows["/interface"].map(row => row.name), ["gre-client", "test-drift"])
|
||||
const { rows: [archive] } = await pool.query(`SELECT s.configuration->>'deleted' AS deleted,
|
||||
(SELECT count(*)::int FROM ix_segment_revisions WHERE segment_id=s.id) AS revisions,
|
||||
(SELECT count(*)::int FROM ix_segment_devices WHERE segment_id=s.id) AS devices
|
||||
FROM ix_segments s WHERE id=$1`, [segment.id])
|
||||
assert.deepEqual(archive, { deleted: "true", revisions: 4, devices: 0 })
|
||||
const listReply = await fetch(origin + "/api/ix/segments", { headers: { authorization: "Bearer " + reader } })
|
||||
assert.equal(listReply.status, 200)
|
||||
assert.deepEqual((await listReply.json()).items.map((item: { configuration: { name: string } }) => item.configuration.name), [draftConfig.name])
|
||||
|
||||
process.env.MCP_PUBLIC_URL = origin + "/mcp"
|
||||
const ownerPermissions = ["mm:network:write", "mm:network:read", "mm:mcp:admin", "mm:mcp:approve"]
|
||||
const issuedAt = Math.floor(Date.now() / 1000) - 1
|
||||
const ownerId = "ix-mcp-owner"
|
||||
const mcpJwt = app.jwt.sign({ iss: env.authIssuer, sub: ownerId, apps: ["mm"], permissions: ownerPermissions, iat: issuedAt, exp: issuedAt + 600 })
|
||||
const { updateMcpSettings } = await import("../../src/modules/mcp/store.js")
|
||||
await updateMcpSettings({ enabled: true }, { id: ownerId, email: "[email protected]", name: "IX acceptance", apps: ["mm"],
|
||||
permissions: ownerPermissions, issuedAt: issuedAt * 1000, expiresAt: (issuedAt + 600) * 1000 })
|
||||
async function mcpPost(path: string, body: object) {
|
||||
const reply = await fetch(origin + "/api/mcp/" + path, { method: "POST",
|
||||
headers: { authorization: "Bearer " + mcpJwt, "content-type": "application/json" }, body: JSON.stringify(body) })
|
||||
const data = await reply.json()
|
||||
assert(reply.ok, JSON.stringify(data))
|
||||
return data
|
||||
}
|
||||
const { token: mcpToken } = await mcpPost("connections", { name: "IX removal acceptance", mode: "approval",
|
||||
permissions: ["mm:network:write", "mm:network:read"], expiresAt: new Date(Date.now() + 300_000).toISOString(),
|
||||
scope: { allowGlobal: false, serverIds: [Number(server.id)], operationIds: ["network.ix.delete", "network.wireguard.export", "changes.apply", "operations.read"] } })
|
||||
mcp = new Client({ name: "ix-removal-acceptance", version: "1.0.0" })
|
||||
await mcp.connect(new StreamableHTTPClientTransport(new URL(origin + "/mcp"),
|
||||
{ requestInit: { headers: { authorization: "Bearer " + mcpToken } } }))
|
||||
async function call<T>(name: string, args: object, error = false) {
|
||||
const reply = await mcp!.callTool({ name, arguments: args })
|
||||
assert.equal(Boolean(reply.isError), error, JSON.stringify(reply.structuredContent ?? reply.content))
|
||||
return (reply.structuredContent as { result: T } | undefined)?.result as T
|
||||
}
|
||||
const mcpPlan = await call<{ planId: string; state: string }>(
|
||||
"mm_ix_delete_plan", { id: recreated.id, revision: 1 })
|
||||
assert.equal(mcpPlan.state, "awaiting-approval")
|
||||
const mcpApply = { planId: mcpPlan.planId, idempotencyKey: randomUUID() }
|
||||
await call("mm_change_apply", mcpApply, true)
|
||||
await mcpPost("plans/" + mcpPlan.planId + "/decision", { approve: true })
|
||||
type Operation = { id: string; state: string; verification: string }
|
||||
const operation = await call<Operation>("mm_change_apply", mcpApply)
|
||||
let terminal = operation
|
||||
for (let attempts = 0; attempts < 30 && ["pending", "running"].includes(terminal.state); attempts++) {
|
||||
await delay(200)
|
||||
terminal = await call<Operation>("mm_operation_get", { operationId: operation.id })
|
||||
}
|
||||
assert.equal(terminal.state, "applied", JSON.stringify(terminal))
|
||||
assert.equal(terminal.verification, "passed")
|
||||
assert.equal(deletes, writes)
|
||||
|
||||
const managed = (await post("", { revision: 0, configuration: { name: "ix-web-managed", sites: [
|
||||
{ serverId: Number(server.id), autonomousSystem: 64512, routerId: "192.0.2.6" },
|
||||
] } }, 200)).segment
|
||||
const managedPath = "/" + managed.id
|
||||
const clientInput = { serverId: Number(server.id), name: "linux-auto", kind: "wireguard", hubEndpoint: "192.0.2.20",
|
||||
prefixes: [], destinations: ["203.0.113.0/24"], enabled: true }
|
||||
const staged = await post(managedPath + "/linux", { ...clientInput, revision: managed.revision }, 200)
|
||||
const clientKey = { serverId: clientInput.serverId, interfaceName: staged.interfaceName }
|
||||
await post(managedPath + "/linux/credential", clientKey, 409)
|
||||
await post(managedPath + "/linux/credential", clientKey, 403, reader)
|
||||
const edited = await post(managedPath + "/linux", { ...clientInput, ...clientKey, revision: staged.segment.revision, name: "linux-renamed" }, 200)
|
||||
const provision = edited.segment.configuration.sites[0].interfaces[0].provisionWireguard
|
||||
assert.deepEqual(provision, staged.segment.configuration.sites[0].interfaces[0].provisionWireguard)
|
||||
const plan = await post(managedPath + "/plan", { revision: edited.segment.revision }, 200)
|
||||
await post(managedPath + "/apply", { revision: edited.segment.revision, digest: plan.digest }, 200)
|
||||
const credential = await post(managedPath + "/linux/credential", clientKey, 200)
|
||||
const privateKey = credential.template.match(/^PrivateKey = ([A-Za-z0-9+/]{43}=)$/m)?.[1]
|
||||
assert.ok(privateKey)
|
||||
const scalar = Buffer.from(privateKey, "base64")
|
||||
const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar]),
|
||||
format: "der", type: "pkcs8" })
|
||||
const publicKey = createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64")
|
||||
assert.equal(publicKey, provision.peerPublicKey)
|
||||
assert.equal(rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)?.["public-key"], publicKey)
|
||||
assert(!JSON.stringify([edited, plan, rows]).includes(privateKey))
|
||||
const templateResponse = await fetch(origin + "/api/ix/segments" + managedPath + "/linux?" + new URLSearchParams({
|
||||
serverId: String(clientKey.serverId), interfaceName: clientKey.interfaceName,
|
||||
}), { headers: { authorization: "Bearer " + reader } })
|
||||
assert.equal(templateResponse.status, 200)
|
||||
assert.match((await templateResponse.json()).template, /PrivateKey = <локальный_приватный_ключ>/)
|
||||
|
||||
const exportPlan = await call<{ planId: string; state: string }>("mm_wireguard_export_plan",
|
||||
{ ...clientKey, ixSegmentId: managed.id, format: "peer-conf" })
|
||||
assert.equal(exportPlan.state, "awaiting-approval")
|
||||
assert(!JSON.stringify(exportPlan).includes(privateKey))
|
||||
await mcpPost("plans/" + exportPlan.planId + "/decision", { approve: true })
|
||||
const exportOperation = await call<Operation>("mm_change_apply", { planId: exportPlan.planId, idempotencyKey: randomUUID() })
|
||||
let exported = exportOperation
|
||||
for (let attempts = 0; attempts < 50 && ["pending", "running"].includes(exported.state); attempts++) {
|
||||
await delay(200)
|
||||
exported = await call<Operation>("mm_operation_get", { operationId: exportOperation.id })
|
||||
}
|
||||
assert.equal(exported.state, "applied", JSON.stringify(exported))
|
||||
assert(!JSON.stringify(exported).includes(privateKey))
|
||||
const { rows: [{ result: receipt }] } = await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [exported.id])
|
||||
assert.equal(receipt.humanDownloadOnly, true)
|
||||
const secretRecords = await pool.query(`SELECT to_jsonb(s) AS record FROM mcp_operation_steps s WHERE operation_id=$1
|
||||
UNION ALL SELECT to_jsonb(p) FROM mcp_plans p WHERE id=$2
|
||||
UNION ALL SELECT to_jsonb(a) FROM mcp_artifacts a WHERE id=$3
|
||||
UNION ALL SELECT to_jsonb(a) FROM mcp_audit a WHERE actor_id IN ('ix-web-owner','ix-mcp-owner')`,
|
||||
[exported.id, exportPlan.planId, receipt.artifactId])
|
||||
assert(!JSON.stringify(secretRecords.rows).includes(privateKey))
|
||||
const download = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
|
||||
assert.equal(download.status, 200)
|
||||
assert.equal(await download.text(), credential.template)
|
||||
assert.equal(download.headers.get("cache-control"), "private, no-store")
|
||||
const denied = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + otherWriter } })
|
||||
assert.equal(denied.status, 403)
|
||||
const appliedPeer = rows["/interface/wireguard/peers"].find(row => row.interface === clientKey.interfaceName)!
|
||||
appliedPeer.disabled = "true"
|
||||
const inactive = await fetch(origin + receipt.downloadPath, { headers: { authorization: "Bearer " + mcpJwt } })
|
||||
assert.equal(inactive.status, 409)
|
||||
delete appliedPeer.disabled
|
||||
|
||||
const { rows: [exit] } = await pool.query(`INSERT INTO servers
|
||||
(name,host,port,enabled,type,username,password,use_ssl,verify_ssl)
|
||||
VALUES('owned-exit','127.0.0.1',$1,true,'exit-node','synthetic','synthetic',false,true) RETURNING id`, [port])
|
||||
rows["/interface"].push({ ".id": "*FA", name: "ether1", type: "ether", running: "true" })
|
||||
rows["/ip/address"].push(
|
||||
{ ".id": "*FB", interface: "ether1", address: "192.0.2.20/24" },
|
||||
{ ".id": "*FC", interface: "ether1", address: "192.0.2.30/24" },
|
||||
)
|
||||
rows["/ip/route"].push({ ".id": "*FD", "routing-table": "main", "dst-address": "0.0.0.0/0", "immediate-gw": "192.0.2.1%ether1", active: "true" })
|
||||
const transit = { targetServerId: Number(exit.id), localEndpoint: "192.0.2.20", remoteEndpoint: "192.0.2.30", family: 4, name: "remote-exit" }
|
||||
const remoteClient = { ...clientInput, name: "linux-remote", revision: credential.revision, transit }
|
||||
const beforeStage = writes
|
||||
await post(managedPath + "/linux", { ...remoteClient, localAddress: "10.254.21.1/30" }, 400)
|
||||
const stagedRemote = await post(managedPath + "/linux", remoteClient, 200)
|
||||
assert.equal(writes, beforeStage)
|
||||
assert.equal(stagedRemote.segment.revision, credential.revision + 1)
|
||||
assert.equal(stagedRemote.segment.appliedRevision, credential.revision)
|
||||
const remoteSite = stagedRemote.segment.configuration.sites[0]
|
||||
assert.equal(remoteSite.interfaces.find(row => row.name === stagedRemote.interfaceName).linux.exit, transit.name)
|
||||
const transitBinding = remoteSite.interfaces.find(row => row.name === remoteSite.groups.find(group => group.id === transit.name).primary.interface)
|
||||
assert.equal(transitBinding.peerServerId, Number(exit.id))
|
||||
const { ixReservedTunnelBindings } = await import("../../src/services/internet-exchange-store.js")
|
||||
assert((await ixReservedTunnelBindings(Number(exit.id))).some(binding => binding.name === transitBinding.name))
|
||||
const remotePlan = await post(managedPath + "/plan", { revision: stagedRemote.segment.revision }, 200)
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(exit.id) &&
|
||||
change.path === "/ip/firewall/nat" && change.fields["out-interface"] === "ether1"))
|
||||
assert(remotePlan.changes.some(change => change.serverId === Number(server.id) && change.path === "/interface/wireguard"))
|
||||
assert.equal(writes, beforeStage)
|
||||
|
||||
console.log(JSON.stringify({ appliedRevisions: [2, 4], writes, audit: audit.n, mcpConnections: connections.n,
|
||||
unauthenticated: 401, readOnly: 403, ownerMismatch: 409, drift: 409, replay: 409, protected: 409, linuxClients: clients.items.length,
|
||||
deletedDraft: true, removedNativeObjects: deletes, revisionsRetained: archive.revisions,
|
||||
mcpRemovalVerified: true, managedWireguardVerified: true, clientWithTransitStagedAtomically: true }))
|
||||
} finally {
|
||||
await mcp?.close()
|
||||
await app?.close()
|
||||
await new Promise<void>(resolve => router.close(() => resolve()))
|
||||
await pool.end()
|
||||
await pg.stop()
|
||||
}
|
||||
|
||||
// As in the MCP integration suite, close the standalone runner after teardown and log flushing.
|
||||
process.stderr.write("", () => process.stdout.write("", () => process.exit()))
|
||||
@@ -0,0 +1,97 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdtemp, readdir, readFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join, resolve } from "node:path"
|
||||
import { createServer } from "node:net"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import EmbeddedPostgres from "embedded-postgres"
|
||||
import { FIXED59_IX_DELTA } from "../writer-profile/fixed59-ix-delta.js"
|
||||
import { canonical } from "../writer-profile/application-writer-profile-canonical.js"
|
||||
import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js"
|
||||
import { FIXED44_CATALOGUE_BUILD_SQL } from "../writer-profile/fixed44-build-sql.js"
|
||||
import { CatalogueValueStream } from "../writer-profile/application-writer-profile-catalogue-values.js"
|
||||
import { projectCatalogueData, GROUPS, sorted, type Inventory, type Row } from "../writer-profile/catalogue-projection.js"
|
||||
|
||||
const root = await mkdtemp(join(tmpdir(), "mmapp-ix-profile-"))
|
||||
assert.equal(resolve(root, ".."), resolve(tmpdir()))
|
||||
const listener = createServer()
|
||||
await new Promise<void>((done, reject) => listener.listen(0, "127.0.0.1", done).on("error", reject))
|
||||
const port = (listener.address() as { port: number }).port
|
||||
await new Promise<void>((done, reject) => listener.close(error => error ? reject(error) : done()))
|
||||
const app = new EmbeddedPostgres({ databaseDir: root, user: "ixlab", password: randomBytes(24).toString("hex"),
|
||||
port, persistent: false, createPostgresUser: false, initdbFlags: ["--encoding=UTF8", "--no-locale"],
|
||||
postgresFlags: ["-h", "127.0.0.1", "-c", "jit=off"], onLog: () => {}, onError: () => {} })
|
||||
const roles = ["ix_operator", "ix_runtime", "ix_capture", "ix_publisher", "ix_control"]
|
||||
const tables = ["ix_segments", "ix_segment_devices", "ix_segment_revisions"]
|
||||
console.log("Initialising disposable PostgreSQL")
|
||||
await app.initialise()
|
||||
console.log("Starting disposable PostgreSQL")
|
||||
await app.start()
|
||||
const db = app.getPgClient("postgres", "127.0.0.1")
|
||||
try {
|
||||
await db.connect()
|
||||
console.log("Applying pinned migrations in the fixture")
|
||||
await db.query("CREATE TABLE schema_migrations(id text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())")
|
||||
const directory = resolve("backend/drizzle")
|
||||
for (const name of (await readdir(directory)).filter(name => name.endsWith(".sql")).sort()) {
|
||||
await db.query(await readFile(join(directory, name), "utf8"))
|
||||
await db.query("INSERT INTO schema_migrations(id) VALUES ($1) ON CONFLICT DO NOTHING", [name.slice(0,-4)])
|
||||
}
|
||||
for (const role of roles) await db.query("CREATE ROLE " + role)
|
||||
await db.query("CREATE SCHEMA IF NOT EXISTS mmapp_control; CREATE FUNCTION mmapp_control.candidate_truncate_preadmitted() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NULL; END; $$")
|
||||
for (const name of tables) await db.query("ALTER TABLE public." + name + " OWNER TO ix_operator")
|
||||
await db.query("GRANT USAGE ON SCHEMA mmapp_control TO ix_operator; GRANT EXECUTE ON FUNCTION mmapp_control.candidate_truncate_preadmitted() TO ix_operator")
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_operator")
|
||||
await db.query(ixWriterProfileEnrollmentSql("ix_runtime", "ix_capture"))
|
||||
await db.query("COMMIT")
|
||||
|
||||
const insert = "INSERT INTO ix_segments(id,name,revision,configuration) VALUES ('8dd5d978-83ac-4343-8cff-16655a0a77a7','fixture',1,'{}')"
|
||||
const maintenance = app.getPgClient("postgres", "127.0.0.1")
|
||||
await maintenance.connect()
|
||||
try {
|
||||
await maintenance.query("SELECT pg_advisory_lock(8723110::bigint)")
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_runtime; SET LOCAL lock_timeout='250ms'")
|
||||
await assert.rejects(db.query(insert), { code: "55P03" })
|
||||
await db.query("ROLLBACK")
|
||||
} finally {
|
||||
await maintenance.end()
|
||||
}
|
||||
await db.query("BEGIN; SET LOCAL ROLE ix_runtime; SELECT pg_advisory_xact_lock_shared(8723110::bigint)")
|
||||
await db.query(insert)
|
||||
await db.query("INSERT INTO ix_segment_revisions(segment_id,revision,configuration,actor_id) VALUES ('8dd5d978-83ac-4343-8cff-16655a0a77a7',1,'{}','fixture')")
|
||||
await assert.rejects(db.query("UPDATE ix_segment_revisions SET actor_id='other'"), { code: "42501" })
|
||||
await db.query("ROLLBACK")
|
||||
|
||||
console.log("Capturing exact IX catalogue rows")
|
||||
await db.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; SET LOCAL search_path=pg_catalog,public; SET LOCAL TimeZone='UTC'; SET LOCAL DateStyle='ISO, YMD'")
|
||||
const stream = new CatalogueValueStream()
|
||||
const raw = {} as Inventory
|
||||
for (const group of GROUPS) raw[group] = []
|
||||
const statement = FIXED44_CATALOGUE_BUILD_SQL.replace("LIMIT 104", "LIMIT 113")
|
||||
await db.query("DECLARE ix_capture_cursor NO SCROLL CURSOR WITHOUT HOLD FOR " + statement, roles)
|
||||
for (;;) {
|
||||
const page = (await db.query("FETCH FORWARD 128 FROM ix_capture_cursor")).rows
|
||||
if (!page.length) break
|
||||
for (const record of stream.acceptPage(page)) {
|
||||
if (record.kind === "global") raw[record.identity === "base_tables" ? "tables" : record.identity] = record.value.rows as Row[]
|
||||
if (record.kind === "base") for (const group of GROUPS) raw[group].push(...record.value[group] as Row[])
|
||||
}
|
||||
}
|
||||
stream.finish()
|
||||
const projected = projectCatalogueData(raw)
|
||||
const delta: Inventory = {}
|
||||
for (const group of ["tables", ...GROUPS]) delta[group] = sorted(projected[group].filter(row => tables.includes(String(row.relname))))
|
||||
delta.constraints.push(...projected.constraints.filter(row => row.relname === "servers" && row.conname === "servers_type_check"))
|
||||
delta.triggers.push(...projected.triggers.filter(row => row.relname === "servers" && String(row.definition).includes("ix_segment_devices")))
|
||||
assert.equal(delta.tables.length, 3)
|
||||
assert.equal(delta.triggers.filter(row => row.relname === "servers").length, 2)
|
||||
await db.query("ROLLBACK")
|
||||
let text = JSON.stringify(delta, null, 2)
|
||||
for (const [index, role] of roles.entries()) text = text.replaceAll(role, "@mm-role:" + ["operator","runtime","capture","publisher","control"][index] + "@")
|
||||
assert.equal(canonical(JSON.parse(text)), canonical(FIXED59_IX_DELTA), "PostgreSQL catalogue drifted from source59")
|
||||
console.log(JSON.stringify({ postgres: (await db.query("SHOW server_version")).rows[0].server_version, relations: delta.tables.length, constraints: delta.constraints.length,
|
||||
triggers: delta.triggers.length, leastPrivilege: true, sharedWriterLock: true }))
|
||||
} finally {
|
||||
await db.end().catch(() => {})
|
||||
await app.stop()
|
||||
}
|
||||
@@ -20,10 +20,11 @@ test('fixed artifact is reproducible, resolves the compiled backend graph, and r
|
||||
const packageJson=JSON.parse(await readFile(path.join(backend,'package.json'),'utf8'))
|
||||
await mkdir(projectBackend,{recursive:true});await writeFile(path.join(projectBackend,'package.json'),JSON.stringify({type:'module',dependencies:packageJson.dependencies}))
|
||||
const first=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output}),second=await buildDatabaseOperator({backendDirectory:backend,outputDirectory:output})
|
||||
assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,31);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,30)
|
||||
assert.deepEqual(first,second);assert.equal(first.modules.length,OPERATOR_SOURCES.length);assert.equal(first.modules.length,34);assert.deepEqual(first.runtimeDependencies,['dotenv','pg','zod']);assert.equal(first.backendDistModules.length,33)
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/registry-enrollment.mjs'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/marker-fence-enrollment.mjs'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/fixed58-build-definition.js'))
|
||||
assert(first.modules.some(item=>item.file==='writer-profile/fixed60-build-definition.js'))
|
||||
assert(first.backendDistImports.includes('db/database-restore-quarantine-profile.js'))
|
||||
assert(first.backendDistImports.includes('db/database-source-activation-record.js'))
|
||||
assert(first.backendDistImports.includes('services/server-probe-legacy-source-inventory.js'))
|
||||
|
||||
@@ -13,5 +13,5 @@ export const OPERATOR_SOURCES=Object.freeze([
|
||||
'writer-profile/catalogue.mts','writer-profile/catalogue-value-bridge.ts','writer-profile/catalogue-projection.ts','writer-profile/catalogue-leaves.ts',
|
||||
'writer-profile/application-writer-profile-catalogue.ts','writer-profile/application-writer-profile-catalogue-values.ts',
|
||||
'writer-profile/application-writer-profile-catalogue-parent-policy.ts','writer-profile/application-writer-profile-canonical.ts',
|
||||
'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/expanded44-data-policy.ts',
|
||||
'writer-profile/fixed44-build-sql.ts','writer-profile/fixed44-build-definition.ts','writer-profile/fixed56-build-definition.ts','writer-profile/fixed56-build-delta.ts','writer-profile/fixed57-build-definition.ts','writer-profile/fixed58-build-definition.ts','writer-profile/fixed59-build-definition.ts','writer-profile/fixed59-ix-delta.ts','writer-profile/fixed60-build-definition.ts','writer-profile/expanded44-data-policy.ts',
|
||||
])
|
||||
@@ -57,11 +57,11 @@ export async function main(args:string[]){
|
||||
// import so a newly loaded NODE_PG_FORCE_NATIVE cannot select another driver.
|
||||
const {createProtectedDatabaseSourceBindingVerifier}=await import('./writer-profile/protected-source-registry.mjs')
|
||||
assertJsDriverEnvironment(process.env)
|
||||
const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,approvedDefinition}]=await Promise.all([
|
||||
const [{default:pg},{createConnectedPublisher,requireCurrentCatalogueDefinition},{collectSource44Catalogue,collectSource56Catalogue,collectSource57Catalogue,collectSource58Catalogue,collectSource59Catalogue,collectSource60Catalogue,approvedDefinition}]=await Promise.all([
|
||||
import('pg'),import('./writer-profile/publisher.mjs'),import('./writer-profile/catalogue.mjs')])
|
||||
assertJsDriverEnvironment(process.env)
|
||||
const reviewedDefinition=legacyInspection?undefined:approvedDefinition(definition)
|
||||
const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue}
|
||||
const collectCatalogues={44:collectSource44Catalogue,56:collectSource56Catalogue,57:collectSource57Catalogue,58:collectSource58Catalogue,59:collectSource59Catalogue,60:collectSource60Catalogue}
|
||||
const collectCatalogue=collectCatalogues[reviewedDefinition&&'edition' in reviewedDefinition?reviewedDefinition.edition:44]
|
||||
if(!legacyInspection&&!catalogueInspection){
|
||||
assert.equal(reviewedDefinition!.definitionSha256,pinned!.definitionSha256)
|
||||
|
||||
@@ -7,6 +7,8 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
|
||||
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE,normalizeFixed58RestoreRows} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
|
||||
import {GLOBALS,GROUPS,object,rows,sorted,text,projectCatalogueData,type CatalogueEdition,type Inventory,type Row,type Json} from './catalogue-projection.js'
|
||||
import {validateCatalogueLeafData} from './catalogue-leaves.js'
|
||||
import {catalogueTopologyPolicy,Expanded44TopologyBudgetData} from './expanded44-data-policy.js'
|
||||
@@ -20,6 +22,8 @@ const definitions = {
|
||||
56: { provenance: BUILD56_PROVENANCE, template: FIXED56_ROLE_TEMPLATE },
|
||||
57: { provenance: BUILD57_PROVENANCE, template: FIXED57_ROLE_TEMPLATE },
|
||||
58: { provenance: BUILD58_PROVENANCE, template: FIXED58_ROLE_TEMPLATE },
|
||||
59: { provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE },
|
||||
60: { provenance: BUILD60_PROVENANCE, template: FIXED60_ROLE_TEMPLATE },
|
||||
}
|
||||
const exact=(a:unknown,b:unknown,label:string)=>{if(canonical(a)!==canonical(b))throw Error('Writer catalogue refused: '+label)}
|
||||
function captureBindings(input:InstallationRoleBindingsData):Readonly<Record<LogicalRole,string>> {
|
||||
@@ -68,7 +72,7 @@ export class Fixed44CatalogueDataVerifier {
|
||||
if(this.counts||table.relispartition!==false||this.bases.has(record.identity))throw Error('Duplicate/late base')
|
||||
const header=this.headers!.find(t=>t.relname===record.identity);if(!header)throw Error('Foreign base refused');exact(table,header,'header/table')
|
||||
const actual=projectCatalogueData({...this.globals,...groups,tables:this.headers!})
|
||||
for(const name of GROUPS)exact(this.edition===58?normalizeFixed58RestoreRows(record.identity,name,actual[name]):actual[name],
|
||||
for(const name of GROUPS)exact(this.edition>=58?normalizeFixed58RestoreRows(record.identity,name,actual[name]):actual[name],
|
||||
this.expected[name].filter(r=>r.relname===record.identity),'base '+name+' '+record.identity)
|
||||
this.topology.acceptRelation('base',record.identity,groups);this.bases.add(record.identity);if(fixedCatalogueParentPeriodData(record.identity))this.templates.set(record.identity,{table,groups});return
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ export type Json=null|boolean|number|string|Json[]|{[key:string]:Json}
|
||||
export type Row=Record<string,Json>
|
||||
export type Inventory=Record<string,Row[]>
|
||||
export const GROUPS=['columns','triggers','constraints','indexes','roleGrants','inheritance'] as const
|
||||
export type CatalogueEdition = 44 | 56 | 57 | 58
|
||||
export type CatalogueEdition = 44 | 56 | 57 | 58 | 59 | 60
|
||||
export const GLOBALS=['database','effectiveDatabase','effectiveFunctions','effectiveSchemas','effectiveSequences','events','functions','identities','memberships','parameters','roles','schemas','settings','sequences'] as const
|
||||
export const sorted=(rows:Row[])=>rows.slice().sort((a,b)=>canonical(a)<canonical(b)?-1:canonical(a)>canonical(b)?1:0)
|
||||
export const omit=(row:Row,names:readonly string[]):Row=>Object.fromEntries(Object.entries(row).filter(([key])=>!names.includes(key)))
|
||||
|
||||
@@ -5,6 +5,8 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
|
||||
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE,FIXED57_ROLE_TEMPLATE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE,FIXED58_ROLE_TEMPLATE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
|
||||
import {assertRestoreProfileQuarantine} from '../../src/db/database-restore-quarantine-profile.js'
|
||||
import {canonical,sha} from './application-writer-profile-canonical.js'
|
||||
import type {CatalogueEdition} from './catalogue-projection.js'
|
||||
@@ -23,6 +25,14 @@ export function approvedDefinition(value:unknown){
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD58_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED58_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:58 as const,definitionSha256:BUILD58_PROVENANCE.templateSha256,manifestSha256:BUILD58_PROVENANCE.manifestSha256})
|
||||
}
|
||||
if(v.format==='application-writer-source59-definition-approval-v1'){
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD59_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED59_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:59 as const,definitionSha256:BUILD59_PROVENANCE.templateSha256,manifestSha256:BUILD59_PROVENANCE.manifestSha256})
|
||||
}
|
||||
if(v.format==='application-writer-source60-definition-approval-v1'){
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD60_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED60_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:60 as const,definitionSha256:BUILD60_PROVENANCE.templateSha256,manifestSha256:BUILD60_PROVENANCE.manifestSha256})
|
||||
}
|
||||
assert.equal(v.format,'application-writer-source56-definition-approval-v1')
|
||||
assert.equal(canonical(v.provenance),canonical(BUILD56_PROVENANCE));assert.equal(canonical(v.template),canonical(FIXED56_ROLE_TEMPLATE))
|
||||
return Object.freeze({edition:56 as const,definitionSha256:BUILD56_PROVENANCE.templateSha256,manifestSha256:BUILD56_PROVENANCE.manifestSha256})
|
||||
@@ -31,11 +41,14 @@ type CatalogueSession = {query:(sql:string,values?:unknown[])=>Promise<{rows:Rec
|
||||
type CatalogueInstallation = {roleBindings:ConstructorParameters<typeof Fixed44CatalogueValueBridgeData>[0]}
|
||||
assert.equal(FIXED44_CATALOGUE_BUILD_SQL.split('LIMIT 104').length,2)
|
||||
const fixed56Sql = FIXED44_CATALOGUE_BUILD_SQL.replace('LIMIT 104','LIMIT 110')
|
||||
const fixed59Sql = FIXED44_CATALOGUE_BUILD_SQL.replace('LIMIT 104','LIMIT 113')
|
||||
/** Real incremental DATA verifier on caller's retained transaction. No pool or attestor. */
|
||||
export const collectSource44Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 44)
|
||||
export const collectSource56Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 56)
|
||||
export const collectSource57Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 57)
|
||||
export const collectSource58Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 58)
|
||||
export const collectSource59Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 59)
|
||||
export const collectSource60Catalogue = (s:CatalogueSession, installation:CatalogueInstallation) => collectCatalogue(s, installation, 60)
|
||||
async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstallation,edition:CatalogueEdition){
|
||||
const settings=(await s.query("SELECT pg_catalog.current_setting('search_path') AS path,pg_catalog.current_setting('TimeZone') AS zone,pg_catalog.current_setting('DateStyle') AS dates")).rows
|
||||
assert.equal(settings.length,1);assert(['path','zone','dates'].every(k=>typeof settings[0][k]==='string'))
|
||||
@@ -43,9 +56,9 @@ async function collectCatalogue(s:CatalogueSession,installation:CatalogueInstall
|
||||
try{
|
||||
await s.query("SELECT pg_catalog.set_config('search_path','pg_catalog, public',true),pg_catalog.set_config('TimeZone','UTC',true),pg_catalog.set_config('DateStyle','ISO, YMD',true)")
|
||||
const bindings=installation.roleBindings,values=['operator','runtime','capture','publisher','control'].map(k=>bindings[k as keyof typeof bindings].name)
|
||||
if(edition===58)await assertRestoreProfileQuarantine(s,bindings.runtime.name,bindings.operator.name,bindings.control.name)
|
||||
if(edition>=58)await assertRestoreProfileQuarantine(s,bindings.runtime.name,bindings.operator.name,bindings.control.name)
|
||||
const bridge=new Fixed44CatalogueValueBridgeData(bindings,edition)
|
||||
await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:fixed56Sql),values);cursor=true
|
||||
await s.query('DECLARE mm_publisher44 NO SCROLL CURSOR WITHOUT HOLD FOR '+(edition===44?FIXED44_CATALOGUE_BUILD_SQL:edition>=59?fixed59Sql:fixed56Sql),values);cursor=true
|
||||
for(;;){const page=(await s.query('FETCH FORWARD 128 FROM mm_publisher44')).rows;bridge.acceptPage(page);if(page.length===0)break}
|
||||
const result=bridge.finish();await s.query('CLOSE mm_publisher44');cursor=false
|
||||
return {catalogSha256:sha(canonical({values:result.values.snapshotSha256,catalogue:result.catalogue})),definitionSha256:result.catalogue.definitionSha256,manifestSha256:result.catalogue.manifestSha256,leafCount:result.catalogue.leafRelations}
|
||||
|
||||
@@ -3,6 +3,8 @@ import {BUILD44_PROVENANCE,FIXED44_ROLE_TEMPLATE} from './fixed44-build-definiti
|
||||
import {BUILD56_PROVENANCE,FIXED56_ROLE_TEMPLATE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE,FIXED59_ROLE_TEMPLATE} from './fixed59-build-definition.js'
|
||||
import {BUILD60_PROVENANCE,FIXED60_ROLE_TEMPLATE} from './fixed60-build-definition.js'
|
||||
import {fixedCatalogueParentPeriodData} from './application-writer-profile-catalogue-parent-policy.js'
|
||||
import {GROUPS,type CatalogueEdition,type Inventory} from './catalogue-projection.js'
|
||||
export const EXPANDED44_POLICY_VERSION='source44-managed-leaves-3000-data-v1' as const
|
||||
@@ -49,8 +51,35 @@ const EXPANDED58_DATA_POLICY = Object.freeze({
|
||||
version: 'source58-managed-leaves-3000-data-v1',
|
||||
definitionSha256: BUILD58_PROVENANCE.templateSha256,
|
||||
})
|
||||
const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY}
|
||||
const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation}
|
||||
const source59PerRelation = new Map(FIXED59_ROLE_TEMPLATE.tables.map(({relname}) => [String(relname), Object.fromEntries(
|
||||
GROUPS.map(group => [group, FIXED59_ROLE_TEMPLATE[group].filter(row => (group === 'inheritance' ? row.child : row.relname) === relname).length]),
|
||||
) as Record<typeof GROUPS[number],number>]))
|
||||
const source59BaseRows = Object.freeze(Object.fromEntries(GROUPS.map(group => [group,FIXED59_ROLE_TEMPLATE[group].length])) as Record<typeof GROUPS[number],number>)
|
||||
if (source59PerRelation.size !== 113 || parents.some(name => GROUPS.some(group => source59PerRelation.get(name)?.[group] !== source57PerRelation.get(name)?.[group]))) {
|
||||
throw Error('Unexpected source59 IX topology')
|
||||
}
|
||||
const EXPANDED59_DATA_POLICY = Object.freeze({
|
||||
...EXPANDED58_DATA_POLICY,
|
||||
version: 'source59-managed-leaves-3000-data-v1',
|
||||
baseRelations: source59PerRelation.size,
|
||||
maxRelations: source59PerRelation.size + LEAVES,
|
||||
baseRows: source59BaseRows,
|
||||
maxRows: Object.freeze(Object.fromEntries(GROUPS.map(group => [group,source59BaseRows[group] + LEAVES * leafMax[group]])) as Record<typeof GROUPS[number],number>),
|
||||
definitionSha256: BUILD59_PROVENANCE.templateSha256,
|
||||
})
|
||||
const source60PerRelation = new Map(source59PerRelation)
|
||||
const storageUsage = source59PerRelation.get('server_poll_storage_usage')!
|
||||
const removed = FIXED59_ROLE_TEMPLATE.constraints.length - FIXED60_ROLE_TEMPLATE.constraints.length
|
||||
source60PerRelation.set('server_poll_storage_usage', {...storageUsage, constraints: storageUsage.constraints - removed})
|
||||
const EXPANDED60_DATA_POLICY = Object.freeze({
|
||||
...EXPANDED59_DATA_POLICY,
|
||||
version: 'source60-managed-leaves-3000-data-v1',
|
||||
baseRows: Object.freeze({...source59BaseRows, constraints: source59BaseRows.constraints - removed}),
|
||||
maxRows: Object.freeze({...EXPANDED59_DATA_POLICY.maxRows, constraints: EXPANDED59_DATA_POLICY.maxRows.constraints - removed}),
|
||||
definitionSha256: BUILD60_PROVENANCE.templateSha256,
|
||||
})
|
||||
const policies = {44: EXPANDED44_DATA_POLICY, 56: EXPANDED56_DATA_POLICY, 57: EXPANDED57_DATA_POLICY, 58: EXPANDED58_DATA_POLICY, 59: EXPANDED59_DATA_POLICY, 60: EXPANDED60_DATA_POLICY}
|
||||
const relationCounts = {44: perRelation, 56: source56PerRelation, 57: source57PerRelation, 58: source57PerRelation, 59: source59PerRelation, 60: source60PerRelation}
|
||||
export const catalogueTopologyPolicy = (edition: CatalogueEdition) => policies[edition]
|
||||
export const expanded44ParentRowCountsData=()=>Object.freeze(Object.fromEntries(parents.map(name=>[name,Object.freeze({...perRelation.get(name)!})])))
|
||||
export interface ManagedLeafData {readonly parent:string;readonly name:string}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { createHash } from "node:crypto"
|
||||
import { MIGRATION_MANIFEST, migrationManifestDigest } from "../../src/db/migration-manifest.js"
|
||||
import { ixWriterProfileEnrollmentSql } from "../../src/db/internet-exchange-writer-profile.js"
|
||||
import { approvedDefinition } from "./catalogue.mjs"
|
||||
import { FIXED58_ROLE_TEMPLATE } from "./fixed58-build-definition.js"
|
||||
import { BUILD59_PROVENANCE, FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js"
|
||||
import { BUILD60_PROVENANCE, FIXED60_ROLE_TEMPLATE } from "./fixed60-build-definition.js"
|
||||
import { catalogueTopologyPolicy } from "./expanded44-data-policy.js"
|
||||
|
||||
test("source59 pins migration 0058 and alters only the IX catalogue and its existing servers references", () => {
|
||||
assert.equal(BUILD59_PROVENANCE.manifestSha256, createHash("sha256").update(JSON.stringify(MIGRATION_MANIFEST.slice(0, 58))).digest("hex"))
|
||||
assert.equal(catalogueTopologyPolicy(59).baseRelations, catalogueTopologyPolicy(58).baseRelations + 3)
|
||||
const added = new Set(FIXED59_ROLE_TEMPLATE.tables.filter(row => String(row.relname).startsWith("ix_segment")).map(row => row.relname))
|
||||
assert.deepEqual([...added].sort(), ["ix_segment_devices", "ix_segment_revisions", "ix_segments"])
|
||||
for (const group of ["tables", "columns", "roleGrants", "inheritance", "indexes"]) {
|
||||
assert.deepEqual(FIXED59_ROLE_TEMPLATE[group].filter(row => !added.has(row.relname)), FIXED58_ROLE_TEMPLATE[group])
|
||||
}
|
||||
assert.equal(FIXED59_ROLE_TEMPLATE.triggers.length - FIXED58_ROLE_TEMPLATE.triggers.length, 21)
|
||||
assert.equal(FIXED59_ROLE_TEMPLATE.constraints.length - FIXED58_ROLE_TEMPLATE.constraints.length, 24)
|
||||
})
|
||||
|
||||
test("source60 changes poll storage constraints without changing writer grants or table topology", () => {
|
||||
assert.equal(BUILD60_PROVENANCE.manifestSha256, migrationManifestDigest())
|
||||
const approval = { format: "application-writer-source60-definition-approval-v1", provenance: BUILD60_PROVENANCE, template: FIXED60_ROLE_TEMPLATE }
|
||||
assert.equal(approvedDefinition(approval).definitionSha256, BUILD60_PROVENANCE.templateSha256)
|
||||
assert.deepEqual(FIXED60_ROLE_TEMPLATE.tables, FIXED59_ROLE_TEMPLATE.tables)
|
||||
assert.deepEqual(FIXED60_ROLE_TEMPLATE.roleGrants, FIXED59_ROLE_TEMPLATE.roleGrants)
|
||||
assert.equal(catalogueTopologyPolicy(60).baseRows.constraints, catalogueTopologyPolicy(59).baseRows.constraints - 1)
|
||||
})
|
||||
|
||||
test("source59 accepts the exact independently reviewed definition and restricts IX runtime grants", () => {
|
||||
const approval = { format: "application-writer-source59-definition-approval-v1", provenance: BUILD59_PROVENANCE, template: FIXED59_ROLE_TEMPLATE }
|
||||
assert.equal(approvedDefinition(approval).definitionSha256, BUILD59_PROVENANCE.templateSha256)
|
||||
assert.throws(() => approvedDefinition({ ...approval, template: FIXED58_ROLE_TEMPLATE }))
|
||||
const granted = FIXED59_ROLE_TEMPLATE.roleGrants.filter(row => row.rolname === "@mm-role:runtime@" && String(row.relname).startsWith("ix_"))
|
||||
assert(granted.every(row => row.read === true && row.insert === true && row.truncate === false))
|
||||
assert.deepEqual(granted.filter(row => row.update === true).map(row => row.relname), ["ix_segments"])
|
||||
assert.deepEqual(granted.filter(row => row.delete === true).map(row => row.relname), ["ix_segment_devices"])
|
||||
assert.match(ixWriterProfileEnrollmentSql("ix_runtime", "ix_capture"), /GRANT SELECT, INSERT ON TABLE public.ix_segment_revisions TO "ix_runtime"/)
|
||||
assert.throws(() => ixWriterProfileEnrollmentSql('bad"role', "ix_capture"))
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { canonical, sha } from "./application-writer-profile-canonical.js"
|
||||
import { GROUPS, sorted, type Inventory } from "./catalogue-projection.js"
|
||||
import { FIXED58_ROLE_TEMPLATE } from "./fixed58-build-definition.js"
|
||||
import { FIXED59_IX_DELTA } from "./fixed59-ix-delta.js"
|
||||
import { IX_WRITER_PROFILE_DEFINITION_SHA256, IX_WRITER_PROFILE_MANIFEST_SHA256 } from "../../src/db/internet-exchange-writer-profile.js"
|
||||
|
||||
const prior: Inventory = {
|
||||
...FIXED58_ROLE_TEMPLATE,
|
||||
constraints: FIXED58_ROLE_TEMPLATE.constraints.filter(row => !(row.relname === "servers" && row.conname === "servers_type_check")),
|
||||
}
|
||||
|
||||
export const FIXED59_ROLE_TEMPLATE: Readonly<Inventory> = Object.freeze({
|
||||
...prior,
|
||||
...Object.fromEntries(["tables", ...GROUPS].map(group => [group, sorted([...prior[group], ...FIXED59_IX_DELTA[group]])])),
|
||||
})
|
||||
|
||||
export const BUILD59_PROVENANCE = Object.freeze({
|
||||
format: "source59-ix-profile-v1",
|
||||
manifestSha256: IX_WRITER_PROFILE_MANIFEST_SHA256,
|
||||
templateSha256: IX_WRITER_PROFILE_DEFINITION_SHA256,
|
||||
})
|
||||
|
||||
if (sha(canonical(FIXED59_ROLE_TEMPLATE)) !== BUILD59_PROVENANCE.templateSha256) {
|
||||
throw new Error("Fixed59 writer catalogue changed")
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// PostgreSQL 18.4 catalogue rows captured after migration 0058 and IX least-privilege enrollment.
|
||||
import type { Inventory } from "./catalogue-projection.js"
|
||||
|
||||
export const FIXED59_IX_DELTA: Inventory = {
|
||||
tables: [
|
||||
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=ar/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segment_revisions","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
|
||||
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=ard/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segment_devices","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
|
||||
{"acl":["@mm-role:capture@=r/@mm-role:operator@","@mm-role:operator@=arwdDxtm/@mm-role:operator@","@mm-role:runtime@=arw/@mm-role:operator@"],"owner":"@mm-role:operator@","relkind":"r","relname":"ix_segments","namespace":"public","reloptions":null,"partition_key":null,"relispartition":false,"relrowsecurity":false,"partition_bound":null,"relforcerowsecurity":false},
|
||||
],
|
||||
columns: [
|
||||
{"acl":null,"type":"text","attnum":4,"attname":"actor_id","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"integer","attnum":5,"attname":"applied_revision","relname":"ix_segments","attnotnull":false,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"jsonb","attnum":3,"attname":"configuration","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"jsonb","attnum":4,"attname":"configuration","relname":"ix_segments","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"timestamp with time zone","attnum":5,"attname":"created_at","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":"now()"},
|
||||
{"acl":null,"type":"uuid","attnum":1,"attname":"id","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"text","attnum":2,"attname":"name","relname":"ix_segments","attnotnull":true,"attstorage":"x","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"integer","attnum":2,"attname":"revision","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"integer","attnum":3,"attname":"revision","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"uuid","attnum":1,"attname":"segment_id","relname":"ix_segment_devices","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"uuid","attnum":1,"attname":"segment_id","relname":"ix_segment_revisions","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"bigint","attnum":2,"attname":"server_id","relname":"ix_segment_devices","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":null},
|
||||
{"acl":null,"type":"timestamp with time zone","attnum":6,"attname":"updated_at","relname":"ix_segments","attnotnull":true,"attstorage":"p","attidentity":"","attgenerated":"","attcompression":"","default_expression":"now()"},
|
||||
],
|
||||
triggers: [
|
||||
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_devices FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_revisions FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_application_statement_guard","tgtype":30,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segments FOR EACH STATEMENT EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segment_devices FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segment_revisions FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
|
||||
{"tgname":"candidate_truncate_preadmitted","tgtype":34,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON public.ix_segments FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"mmapp_control.candidate_truncate_preadmitted()","parent":false,"constraint":false},
|
||||
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_devices FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segment_revisions FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"server_partition_writer_guard","tgtype":31,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"A","definition":"CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.ix_segments FOR EACH ROW EXECUTE FUNCTION server_partition_writer_guard()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":false,"unconditional":true,"tginitdeferred":false,"function":"public.server_partition_writer_guard()","parent":false,"constraint":false},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.ix_segments FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_cascade_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1646","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.ix_segments FROM ix_segment_revisions NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_cascade_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1646","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.ix_segments FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"ix_segments","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.ix_segments FROM ix_segment_revisions NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_devices FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_devices FROM servers NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":5,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER INSERT ON public.ix_segment_revisions FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_ins\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1644","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_devices FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_devices","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_devices FROM servers NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_c_{oid}","tgtype":17,"relname":"ix_segment_revisions","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_c_{oid}\" AFTER UPDATE ON public.ix_segment_revisions FROM ix_segments NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_check_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1645","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":9,"relname":"servers","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER DELETE ON public.servers FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_restrict_del\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1648","parent":false,"constraint":true},
|
||||
{"tgname":"RI_ConstraintTrigger_a_{oid}","tgtype":17,"relname":"servers","tgnargs":0,"arg_bytes":0,"tgenabled":"O","definition":"CREATE CONSTRAINT TRIGGER \"RI_ConstraintTrigger_a_{oid}\" AFTER UPDATE ON public.servers FROM ix_segment_devices NOT DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION \"RI_FKey_noaction_upd\"()","tgnewtable":null,"tgoldtable":null,"tgdeferrable":false,"tgisinternal":true,"unconditional":true,"tginitdeferred":false,"function":"pg_catalog#1655","parent":false,"constraint":true},
|
||||
],
|
||||
constraints: [
|
||||
{"conname":"ix_segment_devices_pkey","contype":"p","relname":"ix_segment_devices","definition":"PRIMARY KEY (segment_id, server_id)","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_devices_segment_id_fkey","contype":"f","relname":"ix_segment_devices","definition":"FOREIGN KEY (segment_id) REFERENCES ix_segments(id) ON DELETE CASCADE","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_devices_segment_id_not_null","contype":"n","relname":"ix_segment_devices","definition":"NOT NULL segment_id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_devices_server_id_fkey","contype":"f","relname":"ix_segment_devices","definition":"FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE RESTRICT","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_devices_server_id_not_null","contype":"n","relname":"ix_segment_devices","definition":"NOT NULL server_id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_actor_id_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL actor_id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_configuration_check","contype":"c","relname":"ix_segment_revisions","definition":"CHECK ((jsonb_typeof(configuration) = 'object'::text))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_configuration_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL configuration","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_created_at_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL created_at","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_pkey","contype":"p","relname":"ix_segment_revisions","definition":"PRIMARY KEY (segment_id, revision)","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_revision_check","contype":"c","relname":"ix_segment_revisions","definition":"CHECK ((revision > 0))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_revision_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL revision","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_segment_id_fkey","contype":"f","relname":"ix_segment_revisions","definition":"FOREIGN KEY (segment_id) REFERENCES ix_segments(id) ON DELETE CASCADE","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segment_revisions_segment_id_not_null","contype":"n","relname":"ix_segment_revisions","definition":"NOT NULL segment_id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_check","contype":"c","relname":"ix_segments","definition":"CHECK (((applied_revision > 0) AND (applied_revision <= revision)))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_configuration_check","contype":"c","relname":"ix_segments","definition":"CHECK ((jsonb_typeof(configuration) = 'object'::text))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_configuration_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL configuration","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_id_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL id","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_name_key","contype":"u","relname":"ix_segments","definition":"UNIQUE (name)","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_name_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL name","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_pkey","contype":"p","relname":"ix_segments","definition":"PRIMARY KEY (id)","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_revision_check","contype":"c","relname":"ix_segments","definition":"CHECK ((revision > 0))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_revision_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL revision","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"ix_segments_updated_at_not_null","contype":"n","relname":"ix_segments","definition":"NOT NULL updated_at","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
{"conname":"servers_type_check","contype":"c","relname":"servers","definition":"CHECK ((type = ANY (ARRAY['jump-host'::text, 'exit-node'::text, 'home-router'::text, 'ix-node'::text])))","condeferred":false,"convalidated":true,"condeferrable":false},
|
||||
],
|
||||
indexes: [
|
||||
{"relname":"ix_segment_devices","definition":"CREATE INDEX ix_segment_devices_server_idx ON public.ix_segment_devices USING btree (server_id)","index_name":"ix_segment_devices_server_idx","indisready":true,"indisvalid":true,"indisunique":false,"indisprimary":false},
|
||||
{"relname":"ix_segment_devices","definition":"CREATE UNIQUE INDEX ix_segment_devices_pkey ON public.ix_segment_devices USING btree (segment_id, server_id)","index_name":"ix_segment_devices_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
|
||||
{"relname":"ix_segment_revisions","definition":"CREATE UNIQUE INDEX ix_segment_revisions_pkey ON public.ix_segment_revisions USING btree (segment_id, revision)","index_name":"ix_segment_revisions_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
|
||||
{"relname":"ix_segments","definition":"CREATE UNIQUE INDEX ix_segments_name_key ON public.ix_segments USING btree (name)","index_name":"ix_segments_name_key","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":false},
|
||||
{"relname":"ix_segments","definition":"CREATE UNIQUE INDEX ix_segments_pkey ON public.ix_segments USING btree (id)","index_name":"ix_segments_pkey","indisready":true,"indisvalid":true,"indisunique":true,"indisprimary":true},
|
||||
],
|
||||
roleGrants: [
|
||||
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
|
||||
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
|
||||
{"read":false,"delete":false,"insert":false,"update":false,"relname":"ix_segments","rolname":"@mm-role:publisher@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":false,"update":false,"relname":"ix_segments","rolname":"@mm-role:capture@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":true,"update":false,"relname":"ix_segment_revisions","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":false,"insert":true,"update":true,"relname":"ix_segments","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segment_devices","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
|
||||
{"read":true,"delete":true,"insert":true,"update":false,"relname":"ix_segment_devices","rolname":"@mm-role:runtime@","trigger":false,"truncate":false},
|
||||
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segment_revisions","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
|
||||
{"read":true,"delete":true,"insert":true,"update":true,"relname":"ix_segments","rolname":"@mm-role:operator@","trigger":true,"truncate":true},
|
||||
],
|
||||
inheritance: [
|
||||
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { canonical, sha } from "./application-writer-profile-canonical.js"
|
||||
import { sorted, type Inventory } from "./catalogue-projection.js"
|
||||
import { FIXED59_ROLE_TEMPLATE } from "./fixed59-build-definition.js"
|
||||
import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "../../src/db/server-poll-writer-profile.js"
|
||||
|
||||
const quotaConstraint = "server_poll_storage_usage_check2"
|
||||
const definitions = new Map([
|
||||
["server_poll_storage_usage_admissions_check", "CHECK ((admissions >= 0))"],
|
||||
["server_poll_storage_rows_charge", "CHECK ((reserved_rows = ((admissions * 4019) + (compacted_admissions * 2))))"],
|
||||
["server_poll_storage_bytes_charge", "CHECK ((reserved_bytes = (((admissions * 8421376) + (compacted_admissions * 32768)) + archive_bytes)))"],
|
||||
])
|
||||
|
||||
export const FIXED60_ROLE_TEMPLATE: Readonly<Inventory> = Object.freeze({
|
||||
...FIXED59_ROLE_TEMPLATE,
|
||||
constraints: sorted(FIXED59_ROLE_TEMPLATE.constraints.filter(row => row.conname !== quotaConstraint || row.relname !== "server_poll_storage_usage").map(row => {
|
||||
const definition = row.relname === "server_poll_storage_usage" ? definitions.get(String(row.conname)) : undefined
|
||||
return definition ? { ...row, definition } : row
|
||||
})),
|
||||
functions: sorted(FIXED59_ROLE_TEMPLATE.functions.map(row => row.proname !== "server_poll_storage_admission_guard" ? row : {
|
||||
...row,
|
||||
definition: String(row.definition)
|
||||
.replace(/^ IF\(SELECT count\(\*\) FROM public\.server_poll_storage_usage WHERE scope IN\('global','owner:'\|\|NEW\.owner_id\)\n[^]*?THEN RAISE EXCEPTION 'poll admission quota exhausted'; END IF;\n/m, "")
|
||||
.replace("poll admission quota unavailable", "poll admission counters unavailable"),
|
||||
})),
|
||||
})
|
||||
|
||||
export const BUILD60_PROVENANCE = Object.freeze({
|
||||
format: "source60-poll-journal-profile-v1",
|
||||
manifestSha256: POLL_WRITER_PROFILE_MANIFEST_SHA256,
|
||||
templateSha256: POLL_WRITER_PROFILE_DEFINITION_SHA256,
|
||||
})
|
||||
|
||||
const digest = sha(canonical(FIXED60_ROLE_TEMPLATE))
|
||||
if (digest !== BUILD60_PROVENANCE.templateSha256) throw new Error("Fixed60 writer catalogue changed: " + digest)
|
||||
@@ -12,8 +12,10 @@ const publicationFormat='application-writer-publication-approval-v1'
|
||||
export const UPGRADE_APPROVAL_FORMAT='application-writer-upgrade44-to56-approval-v1'
|
||||
export const UPGRADE57_APPROVAL_FORMAT='application-writer-upgrade56-to57-approval-v1'
|
||||
export const UPGRADE58_APPROVAL_FORMAT='application-writer-upgrade57-to58-approval-v1'
|
||||
export const UPGRADE59_APPROVAL_FORMAT='application-writer-upgrade58-to59-approval-v1'
|
||||
export const UPGRADE60_APPROVAL_FORMAT='application-writer-upgrade59-to60-approval-v1'
|
||||
export const REBIND58_APPROVAL_FORMAT='application-writer-rebind58-after-restore-approval-v1'
|
||||
export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format)
|
||||
export const isUpgradeApprovalFormat=format=>[UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,UPGRADE60_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT].includes(format)
|
||||
function parsedApproval(value,format=publicationFormat){
|
||||
const upgrade=isUpgradeApprovalFormat(format)
|
||||
const keys=['format','manifestSha256','definitionSha256','catalogSha256','expectedHeadSha256','validityMs','expiresAt']
|
||||
|
||||
@@ -3,11 +3,13 @@ import pg from 'pg'
|
||||
import {createPrivateKey,createPublicKey,sign,X509Certificate} from 'node:crypto'
|
||||
import {open,lstat,realpath,unlink} from 'node:fs/promises'
|
||||
import {readProtected,writeFile,withJournalLease} from './operator-files.mjs'
|
||||
import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs'
|
||||
import {retainPublisherTlsPeer,upgradeApproval,isUpgradeApprovalFormat,UPGRADE_APPROVAL_FORMAT,UPGRADE57_APPROVAL_FORMAT,UPGRADE58_APPROVAL_FORMAT,UPGRADE59_APPROVAL_FORMAT,UPGRADE60_APPROVAL_FORMAT,REBIND58_APPROVAL_FORMAT} from './operator-contract.mjs'
|
||||
import {BUILD44_PROVENANCE} from './fixed44-build-definition.js'
|
||||
import {BUILD56_PROVENANCE} from './fixed56-build-definition.js'
|
||||
import {BUILD57_PROVENANCE} from './fixed57-build-definition.js'
|
||||
import {BUILD58_PROVENANCE} from './fixed58-build-definition.js'
|
||||
import {BUILD59_PROVENANCE} from './fixed59-build-definition.js'
|
||||
import {BUILD60_PROVENANCE} from './fixed60-build-definition.js'
|
||||
import path from 'node:path'
|
||||
import {captureDatabaseSourceObservation,assertDatabaseSourceObservationCurrent} from '../../src/db/database-source-observation.js'
|
||||
import {MIGRATION_MANIFEST,migrationManifestDigest} from '../../src/db/migration-manifest.js'
|
||||
@@ -19,6 +21,8 @@ const upgradeTransitions = {
|
||||
[UPGRADE_APPROVAL_FORMAT]: { predecessor: BUILD44_PROVENANCE, successor: BUILD56_PROVENANCE, oldEdition: 44, newEdition: 56 },
|
||||
[UPGRADE57_APPROVAL_FORMAT]: { predecessor: BUILD56_PROVENANCE, successor: BUILD57_PROVENANCE, oldEdition: 56, newEdition: 57 },
|
||||
[UPGRADE58_APPROVAL_FORMAT]: { predecessor: BUILD57_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 57, newEdition: 58 },
|
||||
[UPGRADE59_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD59_PROVENANCE, oldEdition: 58, newEdition: 59 },
|
||||
[UPGRADE60_APPROVAL_FORMAT]: { predecessor: BUILD59_PROVENANCE, successor: BUILD60_PROVENANCE, oldEdition: 59, newEdition: 60 },
|
||||
[REBIND58_APPROVAL_FORMAT]: { predecessor: BUILD58_PROVENANCE, successor: BUILD58_PROVENANCE, oldEdition: 58, newEdition: 58 },
|
||||
}
|
||||
export function requireCurrentCatalogueDefinition(approval,definition){
|
||||
@@ -133,7 +137,7 @@ async function session(pool,deadlineAt,work){
|
||||
return value
|
||||
}
|
||||
async function observeCurrentCatalogue(s,manifestSha256){
|
||||
const security=await protectedStructure(s,installation,definition?.edition===58),catalogue=await collectFixedCatalogue(s)
|
||||
const security=await protectedStructure(s,installation,(definition?.edition??44)>=58),catalogue=await collectFixedCatalogue(s)
|
||||
if(catalogue.manifestSha256!==manifestSha256||catalogue.definitionSha256!==definition.definitionSha256)throw Error('Catalogue evidence differs from the approved migration manifest/definition')
|
||||
// Inspect one extra row so an unexpected marker cannot hide after the expected prefix.
|
||||
const expected=MIGRATION_MANIFEST.map(pin=>pin.file.slice(0,-4))
|
||||
@@ -209,7 +213,7 @@ async function inspectPublication(pool,proposal,{deadlineAt=Date.now()+120000}={
|
||||
if(!proposal||proposal.installationId!==installation.installationId||!(/^[a-f0-9]{64}$/).test(proposal.headSha256)||proposal.previousHeadSha256!==null&&!(/^[a-f0-9]{64}$/).test(proposal.previousHeadSha256))throw Error('Bounded public proposal required')
|
||||
return session(pool,deadlineAt,async s=>{
|
||||
s.phase('publication-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true)
|
||||
const first=await ownedContext(s,installation,PUBLISHER,'publisher-read');await protectedStructure(s,installation,definition?.edition===58)
|
||||
const first=await ownedContext(s,installation,PUBLISHER,'publisher-read');await protectedStructure(s,installation,(definition?.edition??44)>=58)
|
||||
if(canonical(sourceCoordinates(first))!==canonical(installation.expectedSource))throw Error('Pinned inspection source mismatch')
|
||||
const facade=Object.freeze({query:(sql,values)=>s.query(sql,values)}),options={deadlineAt}
|
||||
const observation=await captureDatabaseSourceObservation(facade,options);await sourceVerifier.verify(facade,observation,options)
|
||||
@@ -251,7 +255,8 @@ async function preflightCurrentProfile(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
}
|
||||
async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
const manifestSha256=migrationManifestDigest()
|
||||
if(definition?.edition!==58||definition.manifestSha256!==manifestSha256||definition.definitionSha256!==BUILD58_PROVENANCE.templateSha256)throw Error('Approved source58 definition required')
|
||||
const expected={58:BUILD58_PROVENANCE,59:BUILD59_PROVENANCE,60:BUILD60_PROVENANCE}[definition?.edition]
|
||||
if(!expected||definition.manifestSha256!==manifestSha256||definition.definitionSha256!==expected.templateSha256)throw Error('Approved current writer definition required')
|
||||
return session(pool,deadlineAt,async s=>{
|
||||
s.phase('source-catalogue-inspection');await s.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');s.begun(true)
|
||||
const first=await ownedContext(s,installation,PUBLISHER,'publisher-read')
|
||||
@@ -261,9 +266,10 @@ async function inspectCurrentCatalogue(pool,{deadlineAt=Date.now()+120000}={}){
|
||||
const initial=await sourceVerifier.verify(facade,observation,options)
|
||||
const {security,catalogSha256}=await observeCurrentCatalogue(s,manifestSha256)
|
||||
const current=await readCurrent(s,installation,{validNow:false})
|
||||
if(!current||current.policy.definitionSha256!==definition.definitionSha256||current.policy.manifestSha256!==manifestSha256||
|
||||
const allowedHeads=definition.edition===60?[BUILD59_PROVENANCE,BUILD60_PROVENANCE]:definition.edition===59?[BUILD58_PROVENANCE,BUILD59_PROVENANCE]:[BUILD58_PROVENANCE]
|
||||
if(!current||!allowedHeads.some(head=>head.templateSha256===current.policy.definitionSha256&&head.manifestSha256===current.policy.manifestSha256)||
|
||||
canonical(current.policy.source)!==canonical(sourceCoordinates(first))||canonical(current.policy.roles)!==canonical(security.roles)){
|
||||
throw Error('Approved source58 predecessor required')
|
||||
throw Error('Approved same-installation writer predecessor required')
|
||||
}
|
||||
const terminal=await sourceVerifier.verify(facade,observation,options)
|
||||
if(initial.platformProtectionVerified!==true||terminal.platformProtectionVerified!==true)throw Error('Protected source evidence required')
|
||||
|
||||
@@ -8,8 +8,10 @@ const digest = (value: string) => createHash("sha256").update(value).digest("hex
|
||||
export const REVIEWED_PREDECESSORS = [
|
||||
{ length: 44, manifestSha256: "fffae3381732e6f276ba276aca7185f6a87587edf8272ba42763b7f49bc59ef5" },
|
||||
{ length: 56, manifestSha256: "b371d8d261f7dd69cf0e2ebc48d4316e3ad804360046bbaaf20e715da8812521" },
|
||||
{ length: 57, manifestSha256: "7dbd678e59740c14a29594180c86b85b3b2dd53fd5aa7a72da6d14a513760dbc" },
|
||||
{ length: 58, manifestSha256: "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb" },
|
||||
] as const
|
||||
export const REVIEWED_SUCCESSOR_MANIFEST = "7dbd678e59740c14a29594180c86b85b3b2dd53fd5aa7a72da6d14a513760dbc"
|
||||
export const REVIEWED_SUCCESSOR_MANIFEST = "25913d7ea3e31361c6853084e9eed6f1a1b45806232122097ba2b7e830a315a9"
|
||||
export const canonical = (value: unknown): string => JSON.stringify(value, (_key, item: unknown) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)
|
||||
export async function observation(intent: DatabaseSchemaIntent, pin: MigrationReview, existingKey = false) {
|
||||
// Fixed, purpose-separated server-keyed ACK issuer. Caller-supplied hashes
|
||||
@@ -55,7 +57,7 @@ export async function exactHistory(rows: Record<string, unknown>[], current: Ret
|
||||
return refuse("Migration release is not the exact internally recorded legacy release")
|
||||
}
|
||||
if (pin ? terminal.observationSha256 !== await observation(terminal.intent, pin, existingKey) :
|
||||
terminal.intent.manifestSha256 !== manifest || terminal.observationSha256 !== await legacy0037AdoptionObservation(terminal.intent)) {
|
||||
terminal.observationSha256 !== await legacy0037AdoptionObservation(terminal.intent)) {
|
||||
return refuse("Migration receipt is not the exact internally recorded file ACK")
|
||||
}
|
||||
pin ??= MIGRATION_MANIFEST[36]
|
||||
|
||||
@@ -185,6 +185,7 @@ test("known completed prefix resumes after fresh ownership without replaying ear
|
||||
|
||||
const reviewed44 = "fffae3381732e6f276ba276aca7185f6a87587edf8272ba42763b7f49bc59ef5"
|
||||
const reviewed56 = "b371d8d261f7dd69cf0e2ebc48d4316e3ad804360046bbaaf20e715da8812521"
|
||||
const reviewed57 = "7dbd678e59740c14a29594180c86b85b3b2dd53fd5aa7a72da6d14a513760dbc"
|
||||
test("reviewed 44 migration history keeps its original keyed receipts and resumes only the current tail", async () => {
|
||||
const f = fixture()
|
||||
f.seedCompletedHistory(46, index => index < 44 ? reviewed44 : manifest.migrationManifestDigest())
|
||||
@@ -199,13 +200,13 @@ test("reviewed 44 migration history keeps its original keyed receipts and resume
|
||||
assert(f.events.every(event => !event.startsWith("file:")))
|
||||
})
|
||||
|
||||
test("complete 56 receipts with or without the inherited 44 prefix dispatch only index 0057", async () => {
|
||||
test("complete 56 receipts with or without the inherited 44 prefix dispatch the remaining files", async () => {
|
||||
for (const mixed of [false, true]) {
|
||||
const f = fixture()
|
||||
f.seedCompletedHistory(56, index => mixed && index < 44 ? reviewed44 : reviewed56)
|
||||
const previous = structuredClone([...f.history.values()])
|
||||
assert.equal((await f.run()).completedFiles, pins.length)
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0057_mcp_routing_charge_audit_index.sql"])
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0057_mcp_routing_charge_audit_index.sql", "file:0058_internet_exchange.sql", "file:0059_server_poll_journal_limits.sql"])
|
||||
assert.deepEqual([...f.history.values()].slice(0, 56), previous)
|
||||
f.events.length = 0
|
||||
assert.equal((await f.run()).completedFiles, pins.length)
|
||||
@@ -213,6 +214,23 @@ test("complete 56 receipts with or without the inherited 44 prefix dispatch only
|
||||
}
|
||||
})
|
||||
|
||||
test("the source58 migration history advances through IX and the poll journal migration", async () => {
|
||||
const f = fixture()
|
||||
f.seedCompletedHistory(57, index => index < 44 ? reviewed44 : index < 56 ? reviewed56 : reviewed57)
|
||||
const previous = structuredClone([...f.history.values()])
|
||||
assert.equal((await f.run()).completedFiles, pins.length)
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0058_internet_exchange.sql", "file:0059_server_poll_journal_limits.sql"])
|
||||
assert.deepEqual([...f.history.values()].slice(0, 57), previous)
|
||||
})
|
||||
|
||||
test("the source59 production prefix advances only through the poll journal migration", async () => {
|
||||
const f = fixture()
|
||||
f.seedCompletedHistory(58, index => index < 44 ? reviewed44 : index < 56 ? reviewed56 : index < 57 ? reviewed57 :
|
||||
"52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb")
|
||||
assert.equal((await f.run()).completedFiles, pins.length)
|
||||
assert.deepEqual(f.events.filter(event => event.startsWith("file:")), ["file:0059_server_poll_journal_limits.sql"])
|
||||
})
|
||||
|
||||
test("history 56 cannot omit a receipt or interleave another manifest", async () => {
|
||||
for (const invalid of ["incomplete", "interleaved"] as const) {
|
||||
const f = fixture()
|
||||
@@ -243,7 +261,7 @@ test("reviewed marker guards are rechecked after each file and a change stops th
|
||||
}
|
||||
const reviewed = prepare()
|
||||
assert.equal((await reviewed.run()).completedFiles, pins.length)
|
||||
assert.equal(reviewed.events.filter(event => event === "reviewed marker guards").length, 15)
|
||||
assert.equal(reviewed.events.filter(event => event === "reviewed marker guards").length, pins.length - 44 + 2)
|
||||
const damaged = prepare()
|
||||
damaged.faults.guardDrift = true
|
||||
await assert.rejects(damaged.run())
|
||||
|
||||
@@ -2,10 +2,10 @@ import assert from "node:assert/strict"
|
||||
import { HEAD_DOMAIN, POLICY_DOMAIN, sha } from "./application-writer-profile-format.js"
|
||||
import { stagedModelClient, syntheticFixture } from "./application-writer-profile-registry-read-model.test.js"
|
||||
import { approvedRuntimeWriterProfile } from "./database-runtime-writer-profile.js"
|
||||
import { RESTORE_WRITER_PROFILE_DEFINITION_SHA256, RESTORE_WRITER_PROFILE_MANIFEST_SHA256 } from "./database-restore-quarantine-profile.js"
|
||||
import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "./server-poll-writer-profile.js"
|
||||
|
||||
const { subject, policy: basePolicy, state, signBody } = syntheticFixture("1")
|
||||
const policy = { ...basePolicy, definitionSha256: RESTORE_WRITER_PROFILE_DEFINITION_SHA256, manifestSha256: RESTORE_WRITER_PROFILE_MANIFEST_SHA256 }
|
||||
const policy = { ...basePolicy, definitionSha256: POLL_WRITER_PROFILE_DEFINITION_SHA256, manifestSha256: POLL_WRITER_PROFILE_MANIFEST_SHA256 }
|
||||
const expected = { installationId: subject.installationId, source: policy.source, roles: policy.roles }
|
||||
|
||||
function publish(next: typeof policy, previous = state.latest[0]) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod"
|
||||
import { canonical, epoch, publicKey, type ApplicationWriterPolicy } from "./application-writer-profile-format.js"
|
||||
import { readCurrentApplicationWriterProfile, type ApplicationWriterRegistryReadSql } from "./application-writer-profile-registry-read.js"
|
||||
import { RESTORE_WRITER_PROFILE_DEFINITION_SHA256, RESTORE_WRITER_PROFILE_MANIFEST_SHA256 } from "./database-restore-quarantine-profile.js"
|
||||
import { POLL_WRITER_PROFILE_DEFINITION_SHA256, POLL_WRITER_PROFILE_MANIFEST_SHA256 } from "./server-poll-writer-profile.js"
|
||||
|
||||
const digest = z.string().regex(/^[a-f0-9]{64}$/)
|
||||
const approvalSchema = z.object({
|
||||
@@ -26,8 +26,8 @@ export function approvedRuntimeWriterProfile(
|
||||
async check(client: ApplicationWriterRegistryReadSql) {
|
||||
const current = await readCurrentApplicationWriterProfile(client, subject)
|
||||
const policy = current?.policy
|
||||
if (!current || !policy || policy.definitionSha256 !== RESTORE_WRITER_PROFILE_DEFINITION_SHA256 ||
|
||||
policy.manifestSha256 !== RESTORE_WRITER_PROFILE_MANIFEST_SHA256 ||
|
||||
if (!current || !policy || policy.definitionSha256 !== POLL_WRITER_PROFILE_DEFINITION_SHA256 ||
|
||||
policy.manifestSha256 !== POLL_WRITER_PROFILE_MANIFEST_SHA256 ||
|
||||
canonical(policy.source) !== canonical(expected.source) || canonical(policy.roles) !== canonical(expected.roles)) {
|
||||
throw new Error("Текущий подписанный профиль записи PostgreSQL не подтверждён")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
export const IX_WRITER_PROFILE_MANIFEST_SHA256 = "52c49786b6204dc11577131670cc0098c165ef54d419c25f0c70759e435c99fb"
|
||||
export const IX_WRITER_PROFILE_DEFINITION_SHA256 = "8f6bcf73d3304879e023beeccc11cd2fa443aa4dd43b913d6f30419267ca64f3"
|
||||
|
||||
const rights = {
|
||||
ix_segments: "SELECT, INSERT, UPDATE",
|
||||
ix_segment_devices: "SELECT, INSERT, DELETE",
|
||||
ix_segment_revisions: "SELECT, INSERT",
|
||||
} as const
|
||||
|
||||
function identifier(name: string) {
|
||||
if (!/^[a-z_][a-z0-9_]{0,62}$/.test(name)) throw new Error("Invalid IX profile role")
|
||||
return `"${name}"`
|
||||
}
|
||||
|
||||
/** Execute offline as application operator, within a retained preadmitted DDL transaction. */
|
||||
export function ixWriterProfileEnrollmentSql(runtimeRole: string, captureRole: string) {
|
||||
if (runtimeRole === captureRole) throw new Error("IX profile roles must be distinct")
|
||||
const runtime = identifier(runtimeRole), capture = identifier(captureRole)
|
||||
return Object.entries(rights).flatMap(([name, permissions]) => {
|
||||
const table = "public." + name
|
||||
return [
|
||||
`REVOKE ALL ON TABLE ${table} FROM PUBLIC, ${runtime}, ${capture}`,
|
||||
`GRANT ${permissions} ON TABLE ${table} TO ${runtime}`,
|
||||
`GRANT SELECT ON TABLE ${table} TO ${capture}`,
|
||||
`CREATE TRIGGER server_partition_writer_guard BEFORE INSERT OR UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION public.server_partition_writer_guard()`,
|
||||
`ALTER TABLE ${table} ENABLE ALWAYS TRIGGER server_partition_writer_guard`,
|
||||
`CREATE TRIGGER candidate_application_statement_guard BEFORE INSERT OR UPDATE OR DELETE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION public.server_partition_writer_guard()`,
|
||||
`ALTER TABLE ${table} ENABLE ALWAYS TRIGGER candidate_application_statement_guard`,
|
||||
`CREATE TRIGGER candidate_truncate_preadmitted BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION mmapp_control.candidate_truncate_preadmitted()`,
|
||||
`ALTER TABLE ${table} ENABLE ALWAYS TRIGGER candidate_truncate_preadmitted`,
|
||||
]
|
||||
}).join(";\n") + ";\n"
|
||||
}
|
||||
@@ -12,10 +12,10 @@ const reviewed = (source: string, extra: Partial<MigrationReview> = {}) => {
|
||||
const bytes = Buffer.from(source), file = "9000_fixture.sql"
|
||||
return () => analyzeMigration(file, bytes, { file, sha256: createHash("sha256").update(bytes).digest("hex"), transaction: "owner-transaction", selfMarker: false, opaqueBodies: 0, bodyReview: [], effects: ["Explicit inert fixture review"], ...extra })
|
||||
}
|
||||
await test("all 57 exact file pins and every top-level schema operation are inventoried", () => {
|
||||
assert.equal(inventory.length, 57); assert.equal(MIGRATION_MANIFEST.length, 57)
|
||||
await test("all 59 exact file pins and every top-level schema operation are inventoried", () => {
|
||||
assert.equal(inventory.length, 59); assert.equal(MIGRATION_MANIFEST.length, 59)
|
||||
assert.equal(inventory.filter(file => file.transaction === "owner-transaction").length, 17)
|
||||
assert.equal(inventory.filter(file => file.transaction === "self-managed-single-transaction").length, 40)
|
||||
assert.equal(inventory.filter(file => file.transaction === "self-managed-single-transaction").length, 42)
|
||||
assert(inventory.every(file => file.operations.length === file.statementCount && file.effects.length > 0))
|
||||
let tables = new Set<string>()
|
||||
for (const file of inventory) {
|
||||
@@ -32,8 +32,8 @@ await test("DO BEGIN and stored function BEGIN are never transaction boundaries"
|
||||
assert.equal(endpoint.topLevelTransactionControls.length, 2); assert.equal(endpoint.opaqueBodies.length, 2)
|
||||
assert.deepEqual(endpoint.opaqueBodies.map(body => body.kind), ["stored-function-body", "executed-do-body"])
|
||||
})
|
||||
await test("0035 through 0057 have exact atomic file-owned terminal markers", () => {
|
||||
assert.deepEqual(inventory.filter(file => file.selfMarker).map(file => file.id), ["0035_server_probe_journal", "0036_diagnostic_cancellations", "0037_server_probe_storage_v2", "0038_server_poll_journal_and_writer_guards", "0039_server_poll_storage", "0040_mcp_routing_reservations", "0041_server_poll_terminal_archives", "0042_server_poll_settings_epoch", "0043_mcp_routing_forward_charges", "0044_mcp_routing_manual_inverse_charges", "0045_mcp_operation_replay_tombstones", "0046_server_poll_operation_retirement", "0047_server_poll_retirement_claims", "0048_mcp_ordinary_retirement_claims", "0049_mcp_ordinary_telemetry_retirement", "0050_server_probe_retired_sources", "0051_server_probe_retirement_claims", "0052_server_probe_retired_gc", "0053_server_probe_terminal_proofs", "0054_mcp_geoip_retirement", "0055_mcp_backup_schedule_retirement", "0056_mcp_manual_inverse_recovery_v8", "0057_mcp_routing_charge_audit_index"])
|
||||
await test("0035 through 0059 have exact atomic file-owned terminal markers", () => {
|
||||
assert.deepEqual(inventory.filter(file => file.selfMarker).map(file => file.id), ["0035_server_probe_journal", "0036_diagnostic_cancellations", "0037_server_probe_storage_v2", "0038_server_poll_journal_and_writer_guards", "0039_server_poll_storage", "0040_mcp_routing_reservations", "0041_server_poll_terminal_archives", "0042_server_poll_settings_epoch", "0043_mcp_routing_forward_charges", "0044_mcp_routing_manual_inverse_charges", "0045_mcp_operation_replay_tombstones", "0046_server_poll_operation_retirement", "0047_server_poll_retirement_claims", "0048_mcp_ordinary_retirement_claims", "0049_mcp_ordinary_telemetry_retirement", "0050_server_probe_retired_sources", "0051_server_probe_retirement_claims", "0052_server_probe_retired_gc", "0053_server_probe_terminal_proofs", "0054_mcp_geoip_retirement", "0055_mcp_backup_schedule_retirement", "0056_mcp_manual_inverse_recovery_v8", "0057_mcp_routing_charge_audit_index", "0058_internet_exchange", "0059_server_poll_journal_limits"])
|
||||
for (const file of inventory.filter(file => file.selfMarker)) { assert.equal(file.selfMarker!.atomicWithAllFileEffects, true); assert.equal(file.selfMarker!.statement, file.statementCount - 2); assert.equal(file.currentOuterMarkerGap, false) }
|
||||
assert.equal(inventory.filter(file => file.currentOuterMarkerGap).length, 34)
|
||||
})
|
||||
|
||||
@@ -879,6 +879,31 @@ const classifiedMigrationPins: readonly MigrationReview[] = [
|
||||
"effects": [
|
||||
"Adds the partial routing charge audit lookup index. Retains all rows and permissions."
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "0058_internet_exchange.sql",
|
||||
"sha256": "75e2842f8d45909c37d1387bdfadf659606e6227b5542289e8c1d98269f5a0cd",
|
||||
"transaction": "self-managed-single-transaction",
|
||||
"selfMarker": true,
|
||||
"opaqueBodies": 0,
|
||||
"bodyReview": [],
|
||||
"effects": [
|
||||
"Allows the IX Node server type without changing existing rows.",
|
||||
"Adds versioned IX configuration and device references."
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "0059_server_poll_journal_limits.sql",
|
||||
"sha256": "9b638ed5649ef75359b24ef61c80bf59390372c98c713447ddb6e32e61b6f5be",
|
||||
"transaction": "self-managed-single-transaction",
|
||||
"selfMarker": true,
|
||||
"opaqueBodies": 1,
|
||||
"bodyReview": [
|
||||
"Replaces the existing invoker admission trigger function and removes only the aggregate count, row and byte ceilings from the insertion path. Authority, locking, accounting, compaction and GC checks remain enforced."
|
||||
],
|
||||
"effects": [
|
||||
"Removes the journal quota while preserving exact reconciliation constraints and all previously retained histories."
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -901,7 +926,7 @@ export const migrationManifestDigest = () => hash(JSON.stringify(MIGRATION_MANIF
|
||||
// resetting the accumulated public table set at the reviewed destructive0002.
|
||||
// This is a necessary presence check, not a substitute for exact live column,
|
||||
// constraint/index/function/trigger comparison by the control protocol.
|
||||
export const CURRENT_REQUIRED_TABLES: readonly string[] = Object.freeze(["acme_settings","alert_engine_confirm_pending","alert_engine_cursor","alert_engine_prev_live","alert_engine_state","alert_groups","alert_history","alert_outbox","alert_rule_conditions","alert_rule_targets","alert_rules","alert_telegram_settings","app_users","backup_entries","backup_schedule_settings","backup_storage_settings","certificate_issue_jobs","certificate_renew_settings","config_revisions","data_migration","events","evobgp_settings","filter_rules","flow_asn_meta","flow_buckets","flow_daily_dims","flow_daily_facts","flow_hour_facts","flow_ip_meta","flow_minute_dims","flow_minute_stats","flow_settings_intents","flow_write_receipts","geoip_settings","internet_path_settings","internet_path_snapshots","mcp_artifacts","mcp_audit","mcp_budget_buckets","mcp_connections","mcp_credentials","mcp_diagnostic_cancellations","mcp_drift","mcp_grants","mcp_management_channels","mcp_oauth_clients","mcp_oauth_requests","mcp_operation_checkpoints","mcp_operation_replay_tombstones","mcp_operation_steps","mcp_operations","mcp_ordinary_retirement_claims","mcp_owner_revocations","mcp_path_checks","mcp_plans","mcp_portal_events","mcp_protections","mcp_read_leases","mcp_recovery_intents","mcp_requests","mcp_routing_forward_charges","mcp_routing_manual_inverse_charges","mcp_routing_observations","mcp_routing_profiles","mcp_routing_reservation_slots","mcp_routing_reservations","mcp_scoped_recovery_intents","mcp_secrets","mcp_settings","mcp_unauthorized_buckets","recursive_routes","router_log_collection_state","router_log_entries","router_log_settings","scheduler_runs","schema_migrations","server_poll_acks","server_poll_archives","server_poll_executions","server_poll_intents","server_poll_quarantines","server_poll_receipts","server_poll_retirement_claims","server_poll_storage_admissions","server_poll_storage_usage","server_probe_execution_payloads","server_probe_execution_quarantines","server_probe_execution_stages","server_probe_executions","server_probe_retired_sources","server_probe_retirement_claims","server_probe_storage_admissions","server_probe_storage_usage","server_probe_terminal_proofs","server_snapshots","servers","servers_api_ping_settings","servers_rest_ping_samples","traffic_collection_state","traffic_flow_settings","traffic_samples","traffic_settings","uptime_probe_samples","uptime_probes","uptime_resource_samples","uptime_settings","uptime_speed_probes","uptime_speed_test_runs","user_interface_bindings","vrf_production_tickets"])
|
||||
export const CURRENT_REQUIRED_TABLES: readonly string[] = Object.freeze(["acme_settings","alert_engine_confirm_pending","alert_engine_cursor","alert_engine_prev_live","alert_engine_state","alert_groups","alert_history","alert_outbox","alert_rule_conditions","alert_rule_targets","alert_rules","alert_telegram_settings","app_users","backup_entries","backup_schedule_settings","backup_storage_settings","certificate_issue_jobs","certificate_renew_settings","config_revisions","data_migration","events","evobgp_settings","filter_rules","flow_asn_meta","flow_buckets","flow_daily_dims","flow_daily_facts","flow_hour_facts","flow_ip_meta","flow_minute_dims","flow_minute_stats","flow_settings_intents","flow_write_receipts","geoip_settings","internet_path_settings","internet_path_snapshots","ix_segment_devices","ix_segment_revisions","ix_segments","mcp_artifacts","mcp_audit","mcp_budget_buckets","mcp_connections","mcp_credentials","mcp_diagnostic_cancellations","mcp_drift","mcp_grants","mcp_management_channels","mcp_oauth_clients","mcp_oauth_requests","mcp_operation_checkpoints","mcp_operation_replay_tombstones","mcp_operation_steps","mcp_operations","mcp_ordinary_retirement_claims","mcp_owner_revocations","mcp_path_checks","mcp_plans","mcp_portal_events","mcp_protections","mcp_read_leases","mcp_recovery_intents","mcp_requests","mcp_routing_forward_charges","mcp_routing_manual_inverse_charges","mcp_routing_observations","mcp_routing_profiles","mcp_routing_reservation_slots","mcp_routing_reservations","mcp_scoped_recovery_intents","mcp_secrets","mcp_settings","mcp_unauthorized_buckets","recursive_routes","router_log_collection_state","router_log_entries","router_log_settings","scheduler_runs","schema_migrations","server_poll_acks","server_poll_archives","server_poll_executions","server_poll_intents","server_poll_quarantines","server_poll_receipts","server_poll_retirement_claims","server_poll_storage_admissions","server_poll_storage_usage","server_probe_execution_payloads","server_probe_execution_quarantines","server_probe_execution_stages","server_probe_executions","server_probe_retired_sources","server_probe_retirement_claims","server_probe_storage_admissions","server_probe_storage_usage","server_probe_terminal_proofs","server_snapshots","servers","servers_api_ping_settings","servers_rest_ping_samples","traffic_collection_state","traffic_flow_settings","traffic_samples","traffic_settings","uptime_probe_samples","uptime_probes","uptime_resource_samples","uptime_settings","uptime_speed_probes","uptime_speed_test_runs","user_interface_bindings","vrf_production_tickets"])
|
||||
|
||||
export interface LegacyBaselineEvidence {
|
||||
inventoryComplete: boolean; databaseGeneration: string; unresolvedAttemptIds: readonly string[]
|
||||
|
||||
@@ -63,7 +63,7 @@ export const servers = pgTable("servers", {
|
||||
useSsl: boolean("use_ssl").notNull().default(true),
|
||||
verifySsl: boolean("verify_ssl").notNull().default(false),
|
||||
routingEndpointEpoch: uuid("routing_endpoint_epoch").notNull().defaultRandom(),
|
||||
type: text("type", { enum: ["jump-host", "exit-node", "home-router"] })
|
||||
type: text("type", { enum: ["jump-host", "exit-node", "home-router", "ix-node"] })
|
||||
.notNull().default("home-router"),
|
||||
site: text("site").notNull().default(""),
|
||||
country: text("country").notNull().default(""),
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export const POLL_WRITER_PROFILE_MANIFEST_SHA256 = "25913d7ea3e31361c6853084e9eed6f1a1b45806232122097ba2b7e830a315a9"
|
||||
export const POLL_WRITER_PROFILE_DEFINITION_SHA256 = "0bf9596d6fec209959bb00761e1396ad292d50a1e7d4c9f17d1222da75007a49"
|
||||
@@ -39,6 +39,7 @@ import vxlanRoutes from "./routes/vxlan.js"
|
||||
import containersRoutes from "./routes/containers.js"
|
||||
import firewallRoutes from "./routes/firewall.js"
|
||||
import greRoutes from "./routes/gre.js"
|
||||
import ixRoutes from "./routes/internet-exchange.js"
|
||||
import usersRoutes from "./routes/users.js"
|
||||
import statisticsRoutes from "./routes/statistics.js"
|
||||
import logsRoutes from "./routes/logs.js"
|
||||
@@ -162,6 +163,7 @@ export async function buildApp(opts?: {
|
||||
await app.register(containersRoutes, { prefix: "/api" })
|
||||
await app.register(firewallRoutes, { prefix: "/api" })
|
||||
await app.register(greRoutes, { prefix: "/api" })
|
||||
await app.register(ixRoutes, { prefix: "/api" })
|
||||
await app.register(usersRoutes, { prefix: "/api" })
|
||||
await app.register(statisticsRoutes, { prefix: "/api" })
|
||||
await app.register(logsRoutes, { prefix: "/api" })
|
||||
|
||||
@@ -186,6 +186,7 @@ const RULES: Rule[] = [
|
||||
p.startsWith("/api/recursive") ||
|
||||
p.startsWith("/api/probes") ||
|
||||
p.startsWith("/api/internet-path") ||
|
||||
p === "/api/ix" || p.startsWith("/api/ix/") ||
|
||||
p.startsWith("/api/exec") ||
|
||||
p.startsWith("/api/wireguard") ||
|
||||
p.startsWith("/api/ipsec") ||
|
||||
@@ -201,6 +202,7 @@ const RULES: Rule[] = [
|
||||
p.startsWith("/api/recursive") ||
|
||||
p.startsWith("/api/probes") ||
|
||||
p.startsWith("/api/internet-path") ||
|
||||
p === "/api/ix" || p.startsWith("/api/ix/") ||
|
||||
p.startsWith("/api/exec") ||
|
||||
p.startsWith("/api/wireguard") ||
|
||||
p.startsWith("/api/ipsec") ||
|
||||
|
||||
@@ -76,6 +76,7 @@ import { prepareWireguardPeerDeletion, registerWireguardPeerDeleteActions } from
|
||||
import { registerFirewallActions } from "./firewall-actions.js"
|
||||
import { registerBfdMoveActions } from "./bfd-move-actions.js"
|
||||
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
||||
import { registerIxActions } from "./internet-exchange-actions.js"
|
||||
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
||||
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
||||
import { registerVpnCatalogActions } from "./vpn-catalog-actions.js"
|
||||
@@ -701,6 +702,7 @@ registerWireguardInterfaceDeleteActions(add)
|
||||
registerFirewallActions(add)
|
||||
registerBfdMoveActions(add)
|
||||
registerGreMutationActions(add)
|
||||
registerIxActions(add)
|
||||
registerGreRevisionActions(add)
|
||||
registerGreNativeServices()
|
||||
registerVpnCatalogActions(add)
|
||||
|
||||
@@ -8,9 +8,20 @@ const actual = await collectApplicationRoutes()
|
||||
assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length, "Duplicate coverage route")
|
||||
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/nodes",
|
||||
"GET /api/ix/segments/:id/linux",
|
||||
"GET /api/ix/topology",
|
||||
"POST /api/ix/preview",
|
||||
"POST /api/ix/segments",
|
||||
"POST /api/ix/segments/:id/linux",
|
||||
"POST /api/ix/segments/:id/linux/credential",
|
||||
"POST /api/ix/segments/:id/linux/revoke",
|
||||
"POST /api/ix/segments/:id/transit",
|
||||
])
|
||||
for (const route of coverage.routes) {
|
||||
assert.equal(route.status === "mediated", route.operations.length > 0, routeKey(route))
|
||||
for (const operation of route.operations) assert.ok(implemented.has(operation), `Unknown tool mapping: ${operation} for ${routeKey(route)}`)
|
||||
if (route.status === "excluded") assert.match(route.path, /^(?:\/api\/(?:mcp(?:\/|$)|auth\/config$)|\/mcp$|\/oauth\/|\/\.well-known\/|\/_internal\/mcp\/|\/health$)/, "Business endpoint cannot be silently excluded")
|
||||
if (route.status === "excluded" && !ixInterfaceRoutes.has(routeKey(route))) assert.match(route.path, /^(?:\/api\/(?:mcp(?:\/|$)|auth\/config$)|\/mcp$|\/oauth\/|\/\.well-known\/|\/_internal\/mcp\/|\/health$)/, "Business endpoint cannot be silently excluded")
|
||||
}
|
||||
console.log("MCP REST coverage:", JSON.stringify({ tools: listActions().length, routes: actual.length, mediated: coverage.routes.filter(route => route.status === "mediated").length, excluded: coverage.routes.filter(route => route.status === "excluded").length, pending: coverage.routes.filter(route => route.status === "pending").length }))
|
||||
@@ -0,0 +1,180 @@
|
||||
import { z } from "zod"
|
||||
import { ixChangeSchema, type IxChange } from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { applyIxChange, currentIxChange, ixTarget, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxNodeInventory, reconcileIxChange, removeIxSegment } from "../../services/internet-exchange-execution.js"
|
||||
import { IxConflict, ixDeviceIds } from "../../services/internet-exchange-plan.js"
|
||||
import { assertIxRevision, isIxSegmentArchived, listIxSegments, readIxRevision, readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import type { add } from "./actions.js"
|
||||
import type { ActionContext } from "./action-types.js"
|
||||
import { McpError } from "./security.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
|
||||
export const ixOperation = "network.ix.configure"
|
||||
export const ixRestoreOperation = "network.ix.restore"
|
||||
const service = "network.ix.configure"
|
||||
const removeService = "network.ix.delete"
|
||||
const id = z.string().uuid()
|
||||
const revision = z.number().int().positive()
|
||||
const changeArgs = z.object({ change: ixChangeSchema }).strict()
|
||||
const restoreArgs = z.object({ id, revision, restoreRevision: revision }).strict()
|
||||
const removeArgs = z.object({ id, revision }).strict()
|
||||
const sealedRemoval = removeArgs.extend({ actorId: z.string().min(1), digest: z.string().regex(/^[a-f0-9]{64}$/) })
|
||||
const sealedInput = z.object({
|
||||
id, change: ixChangeSchema, actorId: z.string().min(1),
|
||||
before: z.object({ revision: z.number().int().nonnegative(), devices: z.string().regex(/^[a-f0-9]{64}$/) }).strict(),
|
||||
}).strict()
|
||||
|
||||
async function present<T>(work: () => Promise<T>) {
|
||||
try { return await work() } catch (error) {
|
||||
if (error instanceof IxConflict) throw new McpError(error.statusCode === 400 ? "INVALID_INPUT" : error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function prepare(change: IxChange, context: ActionContext) {
|
||||
const serverIds = await ixTarget(change)
|
||||
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
|
||||
const result = await prepareIxChange(change)
|
||||
return {
|
||||
target: { scope: "servers" as const, serverIds },
|
||||
before: result.before, objects: await ixPlanObjects(serverIds, result.objects.map(object => object.serverId)), snapshots: [],
|
||||
steps: [{ kind: "service" as const, service, input: { id: result.id, change, before: result.before, actorId: context.connection.owner_id } }],
|
||||
mutationCost: result.native.tasks.length + 1,
|
||||
warnings: [
|
||||
"Изменение затрагивает только выделенные интерфейсы и управляемые объекты IX. Проверка конфигурации не подтверждает прохождение трафика.",
|
||||
...result.native.tasks.slice(0, 12).map(task => `Узел ${task.serverId} · ${task.path} · ${task.fields ? task.rosId ? "изменить" : "создать" : "удалить"}`),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
async function ixPlanObjects(serverIds: number[], nativeIds = serverIds) {
|
||||
const protections = await pool.query("SELECT object_ref FROM mcp_protections WHERE object_ref->>'serverId'=ANY($1::text[]) LIMIT 1001", [serverIds.map(String)])
|
||||
const servers = nativeIds.map(serverId => ({ kind: "server", id: String(serverId), serverId }))
|
||||
const objects = [...new Map(servers.concat(protections.rows.map(({ object_ref: object }) => ({
|
||||
kind: object.kind, id: object.id, serverId: object.serverId,
|
||||
}))).map(object => [JSON.stringify(object), object])).values()]
|
||||
if (objects.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Превышен лимит защищённых ресурсов плана IX", 409)
|
||||
return objects
|
||||
}
|
||||
|
||||
async function removalTarget(input: Record<string, unknown>, context: ActionContext) {
|
||||
const args = removeArgs.parse(input)
|
||||
const current = await readIxSegment(args.id, context.transactionClient)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, args.revision)
|
||||
const serverIds = await ixTarget({ id: current.id, revision: current.revision, configuration: current.configuration })
|
||||
if (serverIds.some(id => !context.connection.policy.scope.serverIds.includes(id))) {
|
||||
throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
|
||||
}
|
||||
return { scope: "servers" as const, serverIds }
|
||||
}
|
||||
|
||||
async function restore(input: Record<string, unknown>, context: ActionContext) {
|
||||
const args = restoreArgs.parse(input)
|
||||
const current = await readIxSegment(args.id, context.transactionClient)
|
||||
if (!current || ixDeviceIds(current.configuration).some(id => !context.connection.policy.scope.serverIds.includes(id))) {
|
||||
throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
}
|
||||
return { id: args.id, revision: args.revision, configuration: await readIxRevision(args.id, args.restoreRevision) }
|
||||
}
|
||||
|
||||
export function registerIxActions(register: typeof add) {
|
||||
registerMcpService(service, {
|
||||
current: input => present(() => {
|
||||
const args = sealedInput.parse(input)
|
||||
return currentIxChange(args.id, args.change)
|
||||
}),
|
||||
execute: input => present(() => {
|
||||
const args = sealedInput.parse(input)
|
||||
return applyIxChange(args.id, args.change, args.before, args.actorId)
|
||||
}),
|
||||
verify: async (input, result) => {
|
||||
const args = sealedInput.parse(input)
|
||||
const row = await readIxSegment(args.id)
|
||||
return (result as { configurationVerified?: boolean })?.configurationVerified === true && row?.appliedRevision === args.change.revision + 1
|
||||
},
|
||||
reconcile: (input, authorize) => {
|
||||
const args = sealedInput.parse(input)
|
||||
return reconcileIxChange(args.id, args.change, args.before, authorize)
|
||||
},
|
||||
})
|
||||
registerMcpService(removeService, {
|
||||
current: input => present(async () => {
|
||||
const { id, revision } = sealedRemoval.parse(input)
|
||||
return { revision, digest: (await prepareIxRemoval(id, revision)).digest }
|
||||
}),
|
||||
execute: input => present(() => {
|
||||
const { id, revision, digest, actorId } = sealedRemoval.parse(input)
|
||||
return removeIxSegment(id, revision, digest, actorId)
|
||||
}),
|
||||
verify: async (input, result) => {
|
||||
const { id, revision } = sealedRemoval.parse(input)
|
||||
return (result as { configurationVerified?: boolean } | undefined)?.configurationVerified === true && isIxSegmentArchived(id, revision)
|
||||
},
|
||||
})
|
||||
register(removeService, "mm_ix_delete_plan", "План удаления сегмента IX", "network", "mm:network:write", "write", "servers", removeArgs, {
|
||||
target: (input, context) => present(() => removalTarget(input, context)),
|
||||
prepare: (input, context) => present(async () => {
|
||||
const args = removeArgs.parse(input)
|
||||
const target = await removalTarget(input, context)
|
||||
const { segment, native, digest } = await prepareIxRemoval(args.id, args.revision)
|
||||
return {
|
||||
target, before: { revision: args.revision, digest }, objects: await ixPlanObjects(target.serverIds), snapshots: [],
|
||||
steps: [{ kind: "service" as const, service: removeService, input: { ...args, digest, actorId: context.connection.owner_id } }],
|
||||
mutationCost: native.tasks.length + 1, requiresHuman: true, verificationScope: "configuration" as const,
|
||||
warnings: [`Сегмент ${segment.configuration.name} будет удалён. Операций RouterOS: ${native.tasks.length}. История ревизий сохранится.`,
|
||||
...native.tasks.slice(0, 12).map(task => `Узел ${task.serverId} · удалить ${task.path}`)],
|
||||
}
|
||||
}),
|
||||
})
|
||||
register("network.ix.list", "mm_ix_segments_list", "Сегменты обмена трафиком", "network", "mm:network:read", "read", "servers",
|
||||
z.object({ limit: z.number().int().min(1).max(25).default(10), offset: z.number().int().nonnegative().max(1000000).default(0) }).strict(), {
|
||||
read: async (input, context) => {
|
||||
const items = await listIxSegments(Number(input.limit), Number(input.offset), context.connection.policy.scope.serverIds)
|
||||
return { items: items.map(segment => ({
|
||||
id: segment.id, name: segment.configuration.name, sites: segment.configuration.sites.map(site => site.serverId),
|
||||
revision: segment.revision, appliedRevision: segment.appliedRevision, updatedAt: segment.updatedAt,
|
||||
})) }
|
||||
},
|
||||
})
|
||||
register("network.ix.read", "mm_ix_segment_get", "Конфигурация сегмента IX", "network", "mm:network:read", "read", "servers",
|
||||
z.object({ id }).strict(), {
|
||||
target: async (input, context) => {
|
||||
const row = await readIxSegment(String(input.id), context.transactionClient)
|
||||
if (!row) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
return { scope: "servers", serverIds: await ixTarget({ id: row.id, revision: row.revision, configuration: row.configuration }) }
|
||||
},
|
||||
read: async (input, context) => {
|
||||
const row = await readIxSegment(String(input.id))
|
||||
if (!row) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
const ids = await ixTarget({ id: row.id, revision: row.revision, configuration: row.configuration })
|
||||
if (ids.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Нет доступа ко всем устройствам сегмента")
|
||||
return { segment: row, observations: await observeIxSegment(row) }
|
||||
},
|
||||
})
|
||||
const nodeInput = z.object({ serverId: z.number().int().positive().safe() }).strict()
|
||||
register("network.ix.inventory", "mm_ix_inventory_get", "Интерфейсы CHR и кандидат Router ID", "network", "mm:network:read", "read", "servers",
|
||||
nodeInput, {
|
||||
target: async input => ({ scope: "servers", serverIds: [nodeInput.parse(input).serverId] }),
|
||||
read: input => present(() => readIxNodeInventory(nodeInput.parse(input).serverId, undefined, true)),
|
||||
})
|
||||
const pathInput = nodeInput.extend({ id, interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) })
|
||||
register("network.ix.linux-path", "mm_ix_linux_path_get", "Маршруты Linux-клиента IX", "network", "mm:network:read", "read", "servers",
|
||||
pathInput, {
|
||||
target: async input => ({ scope: "servers", serverIds: [pathInput.parse(input).serverId] }),
|
||||
read: input => present(async () => {
|
||||
const args = pathInput.parse(input)
|
||||
const segment = await readIxSegment(args.id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return observeIxLinuxPath(segment, args.serverId, args.interfaceName)
|
||||
}),
|
||||
})
|
||||
register(ixOperation, "mm_ix_change_plan", "План изменения сегмента IX", "network", "mm:network:write", "write", "servers", changeArgs, {
|
||||
target: async input => ({ scope: "servers", serverIds: await ixTarget(changeArgs.parse(input).change) }),
|
||||
prepare: (input, context) => present(() => prepare(changeArgs.parse(input).change, context)),
|
||||
})
|
||||
register(ixRestoreOperation, "mm_ix_restore_plan", "План восстановления ревизии IX", "network", "mm:network:write", "write", "servers", restoreArgs, {
|
||||
target: async (input, context) => ({ scope: "servers", serverIds: await ixTarget(await restore(input, context)) }),
|
||||
prepare: (input, context) => present(async () => prepare(await restore(input, context), context)),
|
||||
})
|
||||
}
|
||||
@@ -34,6 +34,14 @@ export function publicRoutingCommunityChanges(evidence: ChangeEvidence) {
|
||||
|
||||
/** Service recovery has the same private native bodies as its forward plan. */
|
||||
export function publicMcpChangeEvidence(operationId: string, evidence: ChangeEvidence) {
|
||||
if (operationId === "network.ix.delete") {
|
||||
return { ...evidence, before: { revision: record(evidence.before).revision }, steps: evidence.steps.map(step => step.kind === "service"
|
||||
? { ...step, input: { id: step.input.id, revision: step.input.revision } } : step) }
|
||||
}
|
||||
if (operationId === "network.ix.configure" || operationId === "network.ix.restore") {
|
||||
return { ...evidence, before: { revision: record(evidence.before).revision }, steps: evidence.steps.map(step => step.kind === "service"
|
||||
? { ...step, input: { id: step.input.id, change: step.input.change } } : step) }
|
||||
}
|
||||
if (operationId === "routing.bfd.configuration.move") {
|
||||
const before = evidence.before as { order?: string[] } | undefined
|
||||
return { ...evidence, before: { order: before?.order }, steps: evidence.steps.map(step => step.kind === "service"
|
||||
|
||||
@@ -10,9 +10,8 @@ test("registration exposes one actual global write plan and fixed nondiagnostic
|
||||
registerServerPollAction(((...args: Parameters<typeof add>) => { calls.push(args) }) as typeof add)
|
||||
assert.equal(calls.length, 1)
|
||||
const [id, tool, description, section, permission, effect, scope, schema, handlers] = calls[0]
|
||||
assert.match(description, /8 на владельца, 128 на приложение/)
|
||||
assert.match(description, /Архивирование сохраняет аудит/)
|
||||
assert.match(description, /pollStorageCapacity/)
|
||||
assert.doesNotMatch(description, /8 на владельца|128 на приложение/)
|
||||
assert.match(description, /pollStorageUsage/)
|
||||
assert.equal(mcpOperationDescriptorSchema.shape.title.safeParse(description).success, true)
|
||||
assert.equal(id, "servers.poll"); assert.equal(tool, "mm_server_poll_plan"); assert.equal(section, "servers")
|
||||
assert.equal(permission, "mm:servers:write"); assert.equal(effect, "write"); assert.equal(scope, "global"); assert.equal(handlers.version, 1)
|
||||
|
||||
@@ -3,12 +3,11 @@ import { SERVER_POLL_OPERATION } from "../../services/server-poll-authority.js"
|
||||
import { SERVER_POLL_MCP_OPERATION_VERSION } from "./server-poll-actions.js"
|
||||
import { createProductionServerPollMcpAdapter } from "./server-poll-production.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
import { SERVER_POLL_STORAGE_POLICY } from "../../services/server-poll-storage-model.js"
|
||||
|
||||
/** Normal startup enrolls quota-bound storage before public tools are served. */
|
||||
/** Normal startup enrolls durable storage before public tools are served. */
|
||||
export function registerServerPollAction(register: typeof add) {
|
||||
const adapter = createProductionServerPollMcpAdapter()
|
||||
registerMcpService(SERVER_POLL_OPERATION, adapter.service)
|
||||
register(SERVER_POLL_OPERATION, "mm_server_poll_plan", `Полный опрос и история. Резерв: ${SERVER_POLL_STORAGE_POLICY.ownerAttempts} на владельца, ${SERVER_POLL_STORAGE_POLICY.globalAttempts} на приложение. Архивирование сохраняет аудит; остаток зависит от объёма истории. Статус: pollStorageCapacity в MCP overview.`, "servers", "mm:servers:write", "write", "global", adapter.schema,
|
||||
register(SERVER_POLL_OPERATION, "mm_server_poll_plan", "Полный опрос и история. Число журналов отображается в pollStorageUsage в MCP overview.", "servers", "mm:servers:write", "write", "global", adapter.schema,
|
||||
{ version: SERVER_POLL_MCP_OPERATION_VERSION, target: adapter.target, prepare: adapter.prepare })
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { fingerprint, accessGeneration, McpError } from "./security.js"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
import { registerMcpService } from "./service-registry.js"
|
||||
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
|
||||
import { wireguardExportAuthority, wireguardExportAuthoritySchema, createWireguardExportArtifact, mcpWireguardExportRequestSchema, readWireguardExportSource, verifyWireguardExportArtifact } from "./wireguard-export-artifact.js"
|
||||
import type { add } from "./actions.js"
|
||||
|
||||
export function registerWireguardExportActions(register: typeof add) {
|
||||
@@ -16,10 +15,10 @@ export function registerWireguardExportActions(register: typeof add) {
|
||||
return receipt?.humanDownloadOnly===true && receipt.wireguardContentReturned===false && !!receipt.artifactId && await verifyWireguardExportArtifact(receipt.artifactId,authority(input),String(input.expectedProof))
|
||||
},
|
||||
})
|
||||
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт для скачивания владельцем после человеческого подтверждения","network","mm:network:write","write","servers",wireguardExportRequestSchema,{
|
||||
target:input=>({scope:"servers",serverIds:[wireguardExportRequestSchema.parse(input).serverId]}),
|
||||
register("network.wireguard.export","mm_wireguard_export_plan","Подготовить WireGuard экспорт или готовый .conf для Linux-клиента IX","network","mm:network:write","write","servers",mcpWireguardExportRequestSchema,{
|
||||
target:input=>({scope:"servers",serverIds:[mcpWireguardExportRequestSchema.parse(input).serverId]}),
|
||||
prepare:async(input,context)=>{
|
||||
const request=wireguardExportRequestSchema.parse(input)
|
||||
const request=mcpWireguardExportRequestSchema.parse(input)
|
||||
const authorize=async()=>{
|
||||
if(context.signal?.aborted)throw new McpError("READ_CANCELLED","Экспорт WireGuard отменён",409)
|
||||
const fresh=await effectiveMcpConnection(context.principal)
|
||||
@@ -33,7 +32,10 @@ export function registerWireguardExportActions(register: typeof add) {
|
||||
await authorize()
|
||||
return {target:{scope:"servers",serverIds:[request.serverId]},objects:[{kind:"server",id:String(request.serverId),serverId:request.serverId},{kind:"wireguard-export",id:request.interfaceName,serverId:request.serverId},...protections.map(row=>row.object_ref)],snapshots:[],before:{proof:source.proof},requiresHuman:true,mutationCost:1,
|
||||
steps:[{kind:"service",service:"network.wireguard.export",input:{authority:access,expectedProof:source.proof,beforeFingerprint:fingerprint({proof:source.proof})}}],
|
||||
warnings:[request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
|
||||
warnings: request.ixSegmentId ? [
|
||||
"Готовый конфиг IX содержит приватный ключ Linux-клиента. Скачивание доступно вошедшему владельцу на 15 минут.",
|
||||
"MCP возвращает только квитанцию и ссылку. Изменение применённой ревизии, прав или защит блокирует выдачу.",
|
||||
] : [request.includePrivateKey && request.format!=="peer-conf" ? "Этот пакет включает приватный ключ интерфейса WireGuard. Скачивание разрешено только вошедшему владельцу на 15 минут." : "Приватные ключи в этот пакет не включаются. Файл доступен только вошедшему владельцу на 15 минут.","Модель получает только квитанцию и ссылку; содержимое, native ключи и комментарии в MCP не возвращаются. Предел файла — 1 МиБ, чтения — 45 секунд.","Изменение источника, прав, подключений или защит блокирует выдачу. Формат conf не воспроизводит отключённые интерфейсы/пиры; peer-conf не раскрывает ключи клиента.",request.format==="conf"?"Формат conf переносит параметры туннеля; имя интерфейса, имена пиров и клиентские подсказки RouterOS в нём не восстанавливаются.":request.format==="peer-conf"?"peer-conf — шаблон клиента: приватный ключ и AllowedIPs заполняются человеком; готовность клиентского подключения не подтверждается.":"RSC сохраняет поддержанные native поля и отключённые состояния; фактический путь проверяется отдельно."]}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import type { PoolClient } from "pg"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission, type AuthUser } from "../../lib/permissions.js"
|
||||
import { readWireguardExport, wireguardExportRequestSchema } from "../../services/wireguard-export.js"
|
||||
import { readIxLinuxClient } from "../../services/internet-exchange-execution.js"
|
||||
import { IxConflict } from "../../services/internet-exchange-plan.js"
|
||||
import { readIxSegment } from "../../services/internet-exchange-store.js"
|
||||
import { assertVerifiedConfigurationAccess, executeGuardedApplicationWrite } from "../../services/config-mutation-policy.js"
|
||||
import { assertLogArtifactBudget } from "./log-artifacts.js"
|
||||
import { assertPortalClaimsCurrent } from "./portal-revocation.js"
|
||||
@@ -13,7 +16,11 @@ import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError,
|
||||
const MAX_BYTES = 1048576, MAX_CIPHER = 2 * 1048576
|
||||
const digest = z.string().regex(/^[a-f0-9]{64}$/)
|
||||
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.iso.datetime() }).strict()
|
||||
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: wireguardExportRequestSchema }).strict()
|
||||
export const mcpWireguardExportRequestSchema = wireguardExportRequestSchema.extend({
|
||||
ixSegmentId: z.string().uuid().optional().describe("Для готового конфига Linux из IX укажите ID сегмента и формат peer-conf"),
|
||||
}).refine(request => !request.ixSegmentId || request.format === "peer-conf" && !request.peerId && !request.includePrivateKey,
|
||||
"Для клиента IX укажите peer-conf и имя интерфейса клиента. Его управляемый ключ будет включён в файл.")
|
||||
export const wireguardExportAuthoritySchema = z.object({ principal: principalSchema, ownerId: z.string().min(1).max(200), policyProof: digest, generation: digest, request: mcpWireguardExportRequestSchema }).strict()
|
||||
export type WireguardExportAuthority = z.infer<typeof wireguardExportAuthoritySchema>
|
||||
const scopeSchema = z.object({ version: z.literal(1), kind: z.literal("wireguard-export"), authority: wireguardExportAuthoritySchema, sourceProof: digest,
|
||||
bytes: z.number().int().min(0).max(MAX_BYTES), sha256: digest, encryptedSha256: digest, proof: digest }).strict()
|
||||
@@ -41,10 +48,25 @@ async function protectionProof(authority: WireguardExportAuthority, client: Pick
|
||||
export async function readWireguardExportSource(authority: WireguardExportAuthority, authorize: () => Promise<unknown> = async()=>{}, signal?: AbortSignal) {
|
||||
await authorize(); await assertWireguardExportAccess(authority)
|
||||
const protections=await protectionProof(authority)
|
||||
const source=await readWireguardExport(authority.request, { signal, authorize: async()=>{
|
||||
const check = async () => {
|
||||
signal?.throwIfAborted()
|
||||
await authorize(); await assertWireguardExportAccess(authority)
|
||||
if (await protectionProof(authority)!==protections) throw fail("Защиты экспорта изменились", "STATE_CONFLICT")
|
||||
} })
|
||||
}
|
||||
const { ixSegmentId, ...request } = authority.request
|
||||
if (ixSegmentId) {
|
||||
await check()
|
||||
const segment = await readIxSegment(ixSegmentId)
|
||||
if (!segment) throw new McpError("NOT_FOUND", "Сегмент IX не найден", 404)
|
||||
const access = await readIxLinuxClient(segment, request.serverId, request.interfaceName, "wireguard").catch(error => {
|
||||
if (error instanceof IxConflict) throw new McpError(error.statusCode === 404 ? "NOT_FOUND" : "STATE_CONFLICT", error.message, error.statusCode)
|
||||
throw error
|
||||
})
|
||||
await check()
|
||||
const proof = await sign({ protections, ixSegmentId, request, access })
|
||||
return { filename: access.filename, content: Buffer.from(access.template), protectionProof: protections, proof }
|
||||
}
|
||||
const source=await readWireguardExport(request, { signal, authorize: check })
|
||||
return {...source,protectionProof:protections,proof:await sign({nativeSource:source.proof,protections})}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
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 { fingerprint, McpError } from "../modules/mcp/security.js"
|
||||
import { audit } from "../modules/mcp/store.js"
|
||||
import { pool } from "../db/index.js"
|
||||
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
|
||||
import { withApplicationMutationLock } from "../services/config-mutation-lock.js"
|
||||
import { withConfigurationActor } from "../services/config-mutation-policy.js"
|
||||
import { applyIxChange, 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"
|
||||
|
||||
const paging = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(25),
|
||||
offset: z.coerce.number().int().min(0).max(1000000).default(0),
|
||||
}).strict()
|
||||
const segmentParams = z.object({ id: z.string().uuid() })
|
||||
const planRequest = z.object({ revision: z.number().int().positive() }).strict()
|
||||
const applyRequest = planRequest.extend({ digest: z.string().regex(/^[a-f0-9]{64}$/) })
|
||||
const clientKey = z.object({ serverId: z.number().int().positive().safe(), interfaceName: z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/) })
|
||||
const safeFields = (fields: Record<string, string>) => Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "secret" && key !== "private-key"))
|
||||
|
||||
async function prepareSavedRevision(id: string, revision: number, resume = false) {
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(segment, revision)
|
||||
if (segment.appliedRevision === revision) throw new IxConflict("Эта ревизия IX уже применена")
|
||||
return prepareIxChange({ id, revision, configuration: segment.configuration }, resume)
|
||||
}
|
||||
|
||||
function reviewDigest(prepared: Awaited<ReturnType<typeof prepareSavedRevision>>, actorId: string, resume: boolean) {
|
||||
return fingerprint({ operation: "ix.web.apply", actorId, change: prepared.change, before: prepared.before, tasks: prepared.native.tasks, resume })
|
||||
}
|
||||
|
||||
function removalDigest(id: string, revision: number, actorId: string, nativeDigest: string) {
|
||||
return fingerprint({ operation: "ix.web.delete", id, revision, actorId, nativeDigest })
|
||||
}
|
||||
|
||||
function summarizeTasks(tasks: Awaited<ReturnType<typeof prepareIxChange>>["native"]["tasks"]): IxWebPlan["changes"] {
|
||||
return tasks.map(task => ({
|
||||
serverId: task.serverId, path: task.path,
|
||||
action: task.fields ? task.rosId ? "update" : "create" : "delete",
|
||||
target: task.before?.name ?? task.before?.comment ?? task.fields?.name ?? task.fields?.comment ?? task.rosId,
|
||||
placeBefore: task.placeBefore,
|
||||
fields: task.fields ? safeFields(task.fields) : Object.fromEntries(Object.entries(task.before ?? {}).filter(([key]) => ["name", "comment", "dst-address", "chain"].includes(key))),
|
||||
}))
|
||||
}
|
||||
|
||||
const ixRoutes: FastifyPluginAsync = async app => {
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
|
||||
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
|
||||
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message })
|
||||
if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" })
|
||||
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
|
||||
const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
|
||||
: request.routeOptions.url?.endsWith("/apply")
|
||||
? "Результат применения IX не подтверждён"
|
||||
: "Не удалось получить данные для операции IX"
|
||||
return reply.code(503).send({ error: errorMessage })
|
||||
})
|
||||
app.get("/ix/segments", async request => {
|
||||
const input = paging.parse(request.query)
|
||||
return { items: await listIxSegments(input.limit, input.offset) }
|
||||
})
|
||||
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"),
|
||||
pool.query("SELECT id,name,site,country,enabled,type FROM servers ORDER BY name,id LIMIT 1000"),
|
||||
])
|
||||
return { items: nodes.rows, peers: peers.rows }
|
||||
})
|
||||
app.get("/ix/nodes/:serverId/inventory", async request => {
|
||||
const { serverId } = z.object({ serverId: z.coerce.number().int().positive().safe() }).parse(request.params)
|
||||
const { segmentId } = z.object({ segmentId: z.string().uuid().optional() }).strict().parse(request.query)
|
||||
const segment = segmentId ? await readIxSegment(segmentId) : null
|
||||
if (segmentId && !segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return readIxNodeInventory(serverId, segment ?? undefined, true)
|
||||
})
|
||||
app.get("/ix/topology", async () => {
|
||||
const segments = await listIxSegments(100, 0)
|
||||
const links = segments.filter(segment => segment.appliedRevision === segment.revision).flatMap(({ configuration }) =>
|
||||
configuration.sites.flatMap(site => site.interfaces.flatMap(binding => binding.peerServerId === undefined
|
||||
? []
|
||||
: [{ from: site.serverId, to: binding.peerServerId, segment: configuration.name }])))
|
||||
return { links }
|
||||
})
|
||||
app.get("/ix/segments/:id/status", async request => {
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(request.params)
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return { sites: await observeIxSegment(segment) }
|
||||
})
|
||||
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({}).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)
|
||||
})
|
||||
app.post("/ix/segments/:id/linux", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const input = ixLinuxClientRequest.parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, input.revision)
|
||||
const base = input.transit ? { ...current, configuration: await configureIxTransit(current, {
|
||||
...input.transit, revision: input.revision, serverId: input.serverId,
|
||||
}) } : current
|
||||
const { configuration, interfaceName } = await configureIxLinuxClient(base, {
|
||||
...input, exit: input.transit?.name ?? input.exit,
|
||||
})
|
||||
const segment = await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false)
|
||||
return { segment, interfaceName }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.get("/ix/segments/:id/linux/path", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName } = clientKey.extend({ serverId: z.coerce.number().int().positive().safe() }).strict().parse(request.query)
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
return observeIxLinuxPath(segment, serverId, interfaceName)
|
||||
})
|
||||
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName } = clientKey.parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + 60_000 }
|
||||
const token = await captureVerifiedRestRequest(request, scope)
|
||||
const { ownerId } = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
const access = await readIxLinuxClient(segment, serverId, interfaceName, true)
|
||||
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
|
||||
reply.header("Cache-Control", "no-store")
|
||||
return access
|
||||
})
|
||||
app.post("/ix/segments/:id/linux/revoke", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { serverId, interfaceName, revision } = clientKey.extend(planRequest.shape).strict().parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, revision)
|
||||
const site = current.configuration.sites.find(item => item.serverId === serverId)
|
||||
if (!site?.interfaces.some(item => item.name === interfaceName && item.linux)) throw new IxConflict("Управляемый клиент не найден", 404)
|
||||
const configuration = { ...current.configuration, sites: current.configuration.sites.map(item => item !== site ? item : {
|
||||
...item, interfaces: item.interfaces.filter(binding => binding.name !== interfaceName),
|
||||
neighbors: item.neighbors.filter(neighbor => neighbor.binding !== interfaceName),
|
||||
}) }
|
||||
compileIxConfiguration(id, configuration)
|
||||
return { segment: await writeIxRevision(id, revision, configuration, request.authUser?.id ?? "system", false) }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/segments/:id/transit", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const input = ixTransitRequest.parse(request.body)
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = await readIxSegment(id)
|
||||
if (!current) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(current, input.revision)
|
||||
const configuration = await configureIxTransit(current, input)
|
||||
return { segment: await writeIxRevision(id, current.revision, configuration, request.authUser?.id ?? "system", false) }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/segments", async request => {
|
||||
const input = ixChangeSchema.parse(request.body)
|
||||
const id = input.id ?? randomUUID()
|
||||
return withApplicationMutationLock(async () => {
|
||||
const current = input.id ? await readIxSegment(id) : null
|
||||
assertIxRevision(current, input.revision)
|
||||
const configuration = await assignIxRouterIds(id, input.configuration, current)
|
||||
compileIxConfiguration(id, configuration)
|
||||
const segment = await writeIxRevision(id, input.revision, configuration, request.authUser?.id ?? "system", false)
|
||||
return { segment }
|
||||
}, { waitMs: 5000 })
|
||||
})
|
||||
app.post("/ix/preview", async request => {
|
||||
const input = ixChangeSchema.parse(request.body)
|
||||
const id = input.id ?? randomUUID()
|
||||
assertIxRevision(input.id ? await readIxSegment(id) : null, input.revision)
|
||||
return { id, objects: compileIxConfiguration(id, input.configuration).map(object => ({ ...object, fields: safeFields(object.fields) })) }
|
||||
})
|
||||
|
||||
app.post("/ix/segments/:id/plan", async (request): Promise<IxWebPlan> => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { revision, resume = false } = planRequest.extend({ resume: z.boolean().optional() }).parse(request.body)
|
||||
const prepared = await prepareSavedRevision(id, revision, resume)
|
||||
return {
|
||||
revision, digest: reviewDigest(prepared, request.authUser?.id ?? "local-operator", resume), ...(resume && { resume }),
|
||||
changes: summarizeTasks(prepared.native.tasks),
|
||||
}
|
||||
})
|
||||
|
||||
app.post("/ix/segments/:id/apply", async request => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { revision, digest, resume = false } = applyRequest.extend({ resume: z.boolean().optional() }).parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + 180_000 }
|
||||
const token = await captureVerifiedRestRequest(request, scope)
|
||||
const inspect = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
const { ownerId } = await inspect()
|
||||
const prepared = await prepareSavedRevision(id, revision, resume)
|
||||
if (digest !== reviewDigest(prepared, ownerId, resume)) throw new IxConflict("План IX устарел. Постройте новый предпросмотр")
|
||||
const result = await withConfigurationActor(ownerId, () => applyIxChange(id, prepared.change, prepared.before, ownerId,
|
||||
async () => { await inspect() }, { resume }))
|
||||
return { segment: await readIxSegment(result.segmentId), result }
|
||||
})
|
||||
|
||||
app.post("/ix/segments/:id/removal-plan", async (request): Promise<IxWebPlan> => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { revision } = planRequest.parse(request.body)
|
||||
const prepared = await prepareIxRemoval(id, revision)
|
||||
return { revision, digest: removalDigest(id, revision, request.authUser?.id ?? "local-operator", prepared.digest),
|
||||
changes: summarizeTasks(prepared.native.tasks) }
|
||||
})
|
||||
|
||||
app.delete("/ix/segments/:id", async (request, reply) => {
|
||||
const { id } = segmentParams.parse(request.params)
|
||||
const { revision, digest } = applyRequest.parse(request.body)
|
||||
const scope = { deadlineAt: Date.now() + 180_000 }
|
||||
const token = await captureVerifiedRestRequest(request, scope)
|
||||
const inspect = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
|
||||
const { ownerId } = await inspect()
|
||||
const prepared = await prepareIxRemoval(id, revision)
|
||||
if (digest !== removalDigest(id, revision, ownerId, prepared.digest)) {
|
||||
throw new IxConflict("План удаления IX устарел. Подготовьте новый план")
|
||||
}
|
||||
await withConfigurationActor(ownerId, () => removeIxSegment(id, revision, prepared.digest, ownerId, async () => { await inspect() }))
|
||||
return reply.code(204).send()
|
||||
})
|
||||
}
|
||||
|
||||
export default ixRoutes
|
||||
@@ -19,6 +19,8 @@ import { accessGeneration, decryptSecret, encryptSecret, McpError, randomToken,
|
||||
import { createMcpConnection, listMcpConnections, getMcpSettings, updateMcpSettings, getConnection, assertConnectionVisible, rotateConnectionToken, setConnectionStatus, updateMcpConnection, connectionWrite, requestAccountingWrite, audit } from "../modules/mcp/store.js"
|
||||
import { approvePlan, loadPlan, publicPlan, readMcpPolicyPreviewInput } from "../modules/mcp/runtime.js"
|
||||
import { applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
|
||||
import { ixChangeSchema } from "@mmapp/contracts/internet-exchange"
|
||||
import { ixOperation, ixRestoreOperation } from "../modules/mcp/internet-exchange-actions.js"
|
||||
import { findOwnerPlanReplayTombstone } from "../modules/mcp/operation-replay-tombstones.js"
|
||||
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
||||
import { revalidateMcpOwner } from "../modules/mcp/store.js"
|
||||
@@ -37,7 +39,7 @@ import { humanWireguardExportMetadata, readHumanWireguardExportArtifact } from "
|
||||
import { humanArtifactReceipts } from "../modules/mcp/human-artifact-receipts.js"
|
||||
import { readHumanHostFilesArtifact } from "../modules/mcp/host-files-artifact.js"
|
||||
import { loadLogExportArtifactMetadata } from "../modules/mcp/log-artifacts.js"
|
||||
import { readServerPollCapacity } from "../services/server-poll-capacity.js"
|
||||
import { readServerPollUsage } from "../services/server-poll-capacity.js"
|
||||
import { connectProbeStorage } from "../services/server-probe-storage-connection.js"
|
||||
|
||||
const uuid = z.string().uuid()
|
||||
@@ -54,12 +56,12 @@ export function mcpDevicePlanArguments(serverId: number, input: z.infer<typeof m
|
||||
}
|
||||
const idOf = (params: unknown) => z.object({ id: uuid }).parse(params).id
|
||||
const actorOf = (actor?: AuthUser) => { if (!actor) throw new McpError("UNAUTHORIZED", "Требуется вход", 401); return actor }
|
||||
async function pollCapacityForPortal(ownerId:string,admin:boolean){
|
||||
async function pollUsageForPortal(ownerId:string,admin:boolean){
|
||||
const options={deadlineAt:Date.now()+3000}
|
||||
let connection:Awaited<ReturnType<typeof connectProbeStorage>>|undefined
|
||||
try{
|
||||
connection=await connectProbeStorage(options)
|
||||
return await readServerPollCapacity({query:(text,values)=>connection!.query(text,values,{timeoutMs:Math.max(1,options.deadlineAt-Date.now())})},ownerId,admin)
|
||||
return await readServerPollUsage({query:(text,values)=>connection!.query(text,values,{timeoutMs:Math.max(1,options.deadlineAt-Date.now())})},ownerId,admin)
|
||||
}catch{return {status:"unavailable" as const}}
|
||||
finally{connection?.release()}
|
||||
}
|
||||
@@ -252,7 +254,7 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent =
|
||||
(SELECT count(*)::int FROM mcp_requests r JOIN mcp_connections c ON c.id=r.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND r.created_at>now()-interval '24 hours' AND r.status IN ('error','denied')) AS errors,
|
||||
(SELECT count(*)::int FROM mcp_plans p JOIN mcp_connections c ON c.id=p.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND p.state='awaiting-approval' AND p.expires_at>now()) AS approvals,
|
||||
(SELECT count(*)::int FROM mcp_operations o JOIN mcp_connections c ON c.id=o.connection_id WHERE ($1::boolean OR c.owner_id=$2) AND o.state IN ('running','pending')) AS running`, [admin, actor.id])
|
||||
return { ...summary, pollStorageCapacity:await pollCapacityForPortal(actor.id,admin), enabled: (await getMcpSettings()).enabled, observedAt: new Date().toISOString() }
|
||||
return { ...summary, pollStorageUsage:await pollUsageForPortal(actor.id,admin), enabled: (await getMcpSettings()).enabled, observedAt: new Date().toISOString() }
|
||||
})
|
||||
for (const table of ["requests", "plans", "operations", "audit", "drift"] as const) {
|
||||
app.get(`/mcp/${table}`, async request => {
|
||||
@@ -411,6 +413,18 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent =
|
||||
await auditOwnerRequest(actor.id, "controller.web.plan", input.connectionId, { profileId: input.profileId ?? null })
|
||||
return ownerDelegate(async () => invokeMcpTool(principal, "mm_route_profile_save_plan", payload))
|
||||
})
|
||||
app.post("/mcp/ix/plan", async request => {
|
||||
const { connectionId, change } = z.object({ connectionId: uuid, change: ixChangeSchema }).strict().parse(request.body)
|
||||
const actor = actorOf(request.authUser), principal = await ownerPrincipal(connectionId, actor, ixOperation)
|
||||
await auditOwnerRequest(actor.id, "ix.web.plan", connectionId, { segmentId: change.id ?? null })
|
||||
return ownerDelegate(() => invokeMcpTool(principal, "mm_ix_change_plan", { change }))
|
||||
})
|
||||
app.post("/mcp/ix/restore", async request => {
|
||||
const { connectionId, ...input } = z.object({ connectionId: uuid, id: uuid, revision: z.number().int().positive(), restoreRevision: z.number().int().positive() }).strict().parse(request.body)
|
||||
const actor = actorOf(request.authUser), principal = await ownerPrincipal(connectionId, actor, ixRestoreOperation)
|
||||
await auditOwnerRequest(actor.id, "ix.web.restore", connectionId, { segmentId: input.id, revision: input.restoreRevision })
|
||||
return ownerDelegate(() => invokeMcpTool(principal, "mm_ix_restore_plan", input))
|
||||
})
|
||||
app.post("/mcp/secrets", async request => {
|
||||
const input = z.object({ purpose: z.string().min(1).max(512), serverId: z.number().int().positive().optional(), value: z.string().min(1).max(1000000) }).strict().parse(request.body), id = randomUUID(), actor = actorOf(request.authUser)
|
||||
await connectionWrite(async client => { await client.query("INSERT INTO mcp_secrets(id,purpose,server_id,ciphertext,created_by) VALUES($1,$2,$3,$4,$5)", [id, input.purpose, input.serverId ?? null, await encryptSecret(input.value), actor.id]); await audit(client, actor.id, "secret.create", null, { secretRef: id, purpose: input.purpose, serverId: input.serverId }) })
|
||||
|
||||
@@ -106,7 +106,11 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
app.get("/traffic/servers/:id/live", async (req, reply) => {
|
||||
const p = req.params as { id?: string | number }
|
||||
const q = req.query as { iface?: string }
|
||||
const q = req.query as { iface?: string; once?: string }
|
||||
if (q.once === "1" && (typeof q.iface !== "string" || !q.iface.trim() ||
|
||||
q.iface.length > 128 || q.iface === "__all__" || /[,\x00-\x1f\x7f]/.test(q.iface))) {
|
||||
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
|
||||
}
|
||||
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
|
||||
signal?.throwIfAborted()
|
||||
const row = await getEnabledServerById(id)
|
||||
@@ -117,11 +121,30 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
if (!server || !server.enabled) return reply.status(404).send({ error: "Server not found" })
|
||||
|
||||
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, async () => {
|
||||
const current = await readServer(server.id, signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
const abort = new AbortController()
|
||||
const onClose = () => abort.abort()
|
||||
registerDatabaseStreamAbort(req, onClose)
|
||||
if (abort.signal.aborted) return reply.code(503).send({ error: "Выполняется операция с базой приложения" })
|
||||
if (reply.raw.destroyed) return
|
||||
if (q.once === "1") {
|
||||
reply.raw.once("close", onClose)
|
||||
try {
|
||||
const sample = await readSample(abort.signal)
|
||||
return reply.header("Cache-Control", "no-store").send(sample)
|
||||
} catch {
|
||||
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
|
||||
return
|
||||
} finally {
|
||||
reply.raw.off("close", onClose)
|
||||
}
|
||||
}
|
||||
reply.raw.on("close", onClose)
|
||||
|
||||
reply.hijack()
|
||||
@@ -144,17 +167,10 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
reply.raw.writeHead(200, sseHeaders)
|
||||
reply.raw.write(":\n\n")
|
||||
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
|
||||
try {
|
||||
while (!abort.signal.aborted) {
|
||||
try {
|
||||
const sample = await readTrafficLiveSample(client, onlyInterface, cache, abort.signal, async () => {
|
||||
const current = await readServer(server.id, abort.signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Live-поток остановлен")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
const sample = await readSample(abort.signal)
|
||||
if (abort.signal.aborted) break
|
||||
writeSse(reply.raw, "sample", sample)
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import type { IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
import { IxConflict } from "./internet-exchange-plan.js"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
|
||||
export function ixLinuxBindingKind(binding: Binding) {
|
||||
if (binding.kind === "wireguard" && binding.provisionWireguard?.hubEndpoint) return "wireguard"
|
||||
if (binding.kind === "gre-ipsec" && binding.localEndpoint && binding.endpoint) return "gre-ipsec"
|
||||
return null
|
||||
}
|
||||
|
||||
export function ixLinuxInterfaceName(prefix: "ixw" | "ixg", serverId: number, binding: Binding) {
|
||||
return prefix + createHash("sha256").update(JSON.stringify([serverId, binding.name])).digest("hex").slice(0, 12)
|
||||
}
|
||||
|
||||
export function ixWireguardClientTemplate(binding: Binding, hubPublicKey: string, routes: string[], privateKey = "<локальный_приватный_ключ>") {
|
||||
const config = binding.provisionWireguard
|
||||
if (binding.kind !== "wireguard" || !config?.hubEndpoint || !/^[A-Za-z0-9+/]{43}=$/.test(hubPublicKey)) {
|
||||
throw new IxConflict("Для Linux нужны публичный ключ узла и заданный внешний адрес IX")
|
||||
}
|
||||
const serverAddress = config.localAddress.split("/")[0]
|
||||
const family = isIP(serverAddress)
|
||||
const address = (value: string) => value + (family === 4 ? "/32" : "/128")
|
||||
const endpoint = isIP(config.hubEndpoint) === 6 ? "[" + config.hubEndpoint + "]" : config.hubEndpoint
|
||||
return [
|
||||
"[Interface]",
|
||||
"Address = " + address(config.peerAddress),
|
||||
"PrivateKey = " + privateKey,
|
||||
binding.linux ? "Table = auto" : "Table = off",
|
||||
...(binding.linux?.exit && binding.linux.peerEndpoint && isIP(binding.linux.peerEndpoint) === family ? [
|
||||
"PostUp = ip -" + family + " rule add pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
|
||||
"PreDown = ip -" + family + " rule del pref 10450 from " + address(binding.linux.peerEndpoint) + " lookup main",
|
||||
] : []),
|
||||
"",
|
||||
"[Peer]",
|
||||
"PublicKey = " + hubPublicKey,
|
||||
"Endpoint = " + endpoint + ":" + config.listenPort,
|
||||
"AllowedIPs = " + [...new Set([address(serverAddress), ...routes.map(canonicalBgpPolicyPrefix)])].join(", "),
|
||||
"PersistentKeepalive = 25",
|
||||
"",
|
||||
].join("\n")
|
||||
}
|
||||
|
||||
export function ixGreClientTemplate(binding: Binding, serverId: number, bgp?: { address: string; localAddress: string }, credential?: string) {
|
||||
const hub = binding.localEndpoint
|
||||
const client = binding.endpoint
|
||||
if (binding.kind !== "gre-ipsec" || !hub || !client || isIP(hub) !== 4 || isIP(client) !== 4 || hub === client) {
|
||||
throw new IxConflict("Для Linux GRE/IPsec нужны два разных внешних IPv4-адреса")
|
||||
}
|
||||
const id = ixLinuxInterfaceName("ixg", serverId, binding)
|
||||
const hostMask = bgp && isIP(bgp.address) === 6 ? "/128" : "/32"
|
||||
const tunnel = binding.provisionGre
|
||||
const family = tunnel ? isIP(tunnel.peerAddress) : 4
|
||||
const protocol = "ip -" + family
|
||||
const local = tunnel?.localAddress.split("/")[0]
|
||||
const table = 30000 + parseInt(id.slice(-4), 16)
|
||||
const management = 10000 + parseInt(id.slice(-3), 16)
|
||||
return {
|
||||
filename: id + ".conf",
|
||||
template: [
|
||||
"# Сверьте предложения и идентификаторы IKE с профилем узла IX.",
|
||||
"connections {",
|
||||
" " + id + " {",
|
||||
" version = 2",
|
||||
" local_addrs = " + client,
|
||||
" remote_addrs = " + hub,
|
||||
" proposals = aes256-sha256-modp2048",
|
||||
" mobike = no",
|
||||
" local {",
|
||||
" auth = psk",
|
||||
" id = " + client,
|
||||
" }",
|
||||
" remote {",
|
||||
" auth = psk",
|
||||
" id = " + hub,
|
||||
" }",
|
||||
" children {",
|
||||
" " + id + " {",
|
||||
" local_ts = " + client + "/32[47]",
|
||||
" remote_ts = " + hub + "/32[47]",
|
||||
" mode = transport",
|
||||
" esp_proposals = aes256-sha256-modp2048",
|
||||
" start_action = trap",
|
||||
" }",
|
||||
" }",
|
||||
" }",
|
||||
"}",
|
||||
"secrets {",
|
||||
" ike-" + id + " {",
|
||||
" id-1 = " + client,
|
||||
" id-2 = " + hub,
|
||||
' secret = "' + (credential ?? "<PSK этого клиента>") + '"',
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
setup: [
|
||||
"swanctl --load-all",
|
||||
"swanctl --initiate --child " + id,
|
||||
"# Создайте GRE после успешного установления IPsec.",
|
||||
"ip tunnel add " + id + " mode gre local " + client + " remote " + hub,
|
||||
tunnel ? "ip address add " + tunnel.peerAddress + (family === 4 ? "/32" : "/128") + " dev " + id :
|
||||
bgp ? "ip address add " + bgp.address + hostMask + " dev " + id : "# Назначьте согласованный адрес Linux внутри туннеля.",
|
||||
"ip link set " + id + " up",
|
||||
...(tunnel ? [
|
||||
protocol + " route replace " + local + (family === 4 ? "/32" : "/128") + " dev " + id + " src " + tunnel.peerAddress,
|
||||
...(binding.linux?.destinations ?? []).map(prefix => protocol + " route replace " + prefix + " dev " + id + " src " + tunnel.peerAddress),
|
||||
...(binding.linux?.exit ? [
|
||||
protocol + " route replace default dev " + id + " src " + tunnel.peerAddress + " table " + table,
|
||||
...(family === 4 ? [
|
||||
"ip -4 rule add pref " + management + " to " + hub + "/32 lookup main",
|
||||
"ip -4 rule add pref " + management + " from " + client + "/32 lookup main",
|
||||
] : []),
|
||||
protocol + " rule add pref " + (management + 1) + " lookup " + table,
|
||||
"# Удаление политик: " + protocol + " rule del pref " + (management + 1) + " lookup " + table,
|
||||
] : []),
|
||||
] : []),
|
||||
...(bgp ? ["ip route add " + bgp.localAddress + hostMask + " dev " + id + " src " + bgp.address] : []),
|
||||
].join("\n"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import type { IxRouterObject } from "@mmapp/contracts/internet-exchange"
|
||||
import { planIxNative } from "./internet-exchange-execution.js"
|
||||
import { ixNamespace } from "./internet-exchange-plan.js"
|
||||
|
||||
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
|
||||
const name = ixNamespace(id)
|
||||
const vrf: IxRouterObject = {
|
||||
serverId: 17, path: "/ip/vrf", fields: { name, comment: name + ":vrf", interfaces: "wg-ix" },
|
||||
}
|
||||
const route: IxRouterObject = {
|
||||
serverId: 17, path: "/ip/route", fields: { comment: name + ":exit-4-0", "routing-table": name, "dst-address": "0.0.0.0/0", gateway: "192.0.2.1@" + name },
|
||||
}
|
||||
const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }]
|
||||
|
||||
test("a new VRF is inserted before main and no foreign route is altered", () => {
|
||||
const changes = planIxNative(id, [vrf, route], [], device({
|
||||
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
|
||||
"/ip/route": [{ ".id": "*B", "routing-table": "main", "dst-address": "0.0.0.0/0", gateway: "203.0.113.1" }],
|
||||
}))
|
||||
assert.deepEqual(changes.map(task => ({ path: task.path, position: task.placeBefore, id: task.rosId })),
|
||||
[{ path: "/ip/vrf", position: "*A", id: undefined }, { path: "/ip/route", position: undefined, id: undefined }])
|
||||
})
|
||||
|
||||
test("managed changes update one exact ID and never adopt unknown objects after an interrupted job", () => {
|
||||
const state = device({ "/ip/route": [{ ".id": "*B", ...route.fields }] })
|
||||
const next = { ...route, fields: { ...route.fields, gateway: "192.0.2.2@" + name } }
|
||||
const [task] = planIxNative(id, [next], [route], state)
|
||||
assert.equal(task.rosId, "*B")
|
||||
assert.deepEqual(task.fields, { gateway: "192.0.2.2@" + name })
|
||||
assert.throws(() => planIxNative(id, [next], [], state), /незавершённой операции/)
|
||||
assert.throws(() => planIxNative(id, [next], [route], device({ "/ip/route": [{ ".id": "*B", ...next.fields }] })), /изменён вне операции/)
|
||||
const resumed = planIxNative(id, [next, vrf], [route], device({
|
||||
"/ip/route": [{ ".id": "*B", ...next.fields }],
|
||||
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
|
||||
}), true)
|
||||
assert.deepEqual(resumed.map(task => task.path), ["/ip/vrf"])
|
||||
})
|
||||
|
||||
test("revocation disables the owned client tunnel before withdrawing rules and deleting its native object", () => {
|
||||
const tunnel = { serverId: 17, path: "/interface/gre", fields: {
|
||||
name: "il-client", comment: name + ":gre-il-client", disabled: "false",
|
||||
} }
|
||||
const changes = planIxNative(id, [], [tunnel, route], device({
|
||||
[tunnel.path]: [{ ".id": "*A", ...tunnel.fields }],
|
||||
[route.path]: [{ ".id": "*B", ...route.fields }],
|
||||
}))
|
||||
assert.deepEqual(changes.map(task => [task.rosId, task.fields, task.before?.disabled]), [
|
||||
["*A", { disabled: "true" }, "false"],
|
||||
["*B", undefined, undefined],
|
||||
["*A", undefined, "true"],
|
||||
])
|
||||
})
|
||||
|
||||
test("a foreign route in the IX table and implicit native field removal are refused", () => {
|
||||
assert.throws(() => planIxNative(id, [route], [], device({
|
||||
"/ip/route": [{ ".id": "*B", "routing-table": name, "dst-address": "192.0.2.0/24" }],
|
||||
})), /пересекается с существующей/)
|
||||
const { gateway: _gateway, ...fields } = route.fields
|
||||
assert.throws(() => planIxNative(id, [{ ...route, fields }], [route], device({ "/ip/route": [{ ".id": "*B", ...route.fields }] })), /неявно сбросить/)
|
||||
})
|
||||
|
||||
test("IX does not take a main-table service address from another route", () => {
|
||||
const resolver = { ...route, fields: { ...route.fields, comment: name + ":bgp-resolve-test", "routing-table": "main", "dst-address": "198.18.0.101/32" } }
|
||||
const occupied = { ".id": "*B", "routing-table": "main", "dst-address": "198.18.0.101/32", dynamic: "true" }
|
||||
assert.throws(() => planIxNative(id, [resolver], [], device({ "/ip/route": [occupied] })), /уже занят/)
|
||||
})
|
||||
|
||||
test("RouterOS REST host matches allow only the equivalent explicit host length", () => {
|
||||
for (const [address, hostLength, wider] of [["192.0.2.1", "32", "24"], ["2001:db8::1", "128", "64"]]) {
|
||||
const rule = { ...route, path: "/ip/firewall/filter", fields: { comment: name + ":host", "src-address": address + "/" + hostLength } }
|
||||
const rows = (source: string) => device({ [rule.path]: [{ ".id": "*B", ...rule.fields, "src-address": source }] })
|
||||
assert.deepEqual(planIxNative(id, [rule], [rule], rows(address)), [])
|
||||
assert.throws(() => planIxNative(id, [rule], [rule], rows(address + "/" + wider)), /изменён вне операции/)
|
||||
}
|
||||
})
|
||||
|
||||
test("RouterOS REST encodes an enabled blackhole route as a present empty flag", () => {
|
||||
const fields = { comment: name + ":default-discard-4", "routing-table": name, "dst-address": "0.0.0.0/0", blackhole: "yes" }
|
||||
const discard = { ...route, fields }
|
||||
const { blackhole: _blackhole, ...unflagged } = fields
|
||||
const observed = (fields: Record<string, string>) => device({ "/ip/route": [{ ".id": "*B", ...fields }] })
|
||||
|
||||
assert.deepEqual(planIxNative(id, [discard], [discard], observed({ ...fields, blackhole: "" })), [])
|
||||
assert.throws(() => planIxNative(id, [discard], [discard], observed(unflagged)), /изменён вне операции/)
|
||||
assert.throws(() => planIxNative(id, [discard], [discard], observed({ ...fields, blackhole: "false" })), /изменён вне операции/)
|
||||
})
|
||||
|
||||
test("the complete member filter can be added to a legacy applied segment", () => {
|
||||
const path = "/ip/firewall/filter"
|
||||
const object = (suffix: string, fields: Record<string, string>) => ({
|
||||
serverId: 17, path, fields: { comment: name + ":" + suffix, chain: "forward", ...fields },
|
||||
})
|
||||
const boundary = object("deny-outside-4", { action: "drop", "in-interface": name })
|
||||
const allow = object("egress-allow-4", { action: "accept", "in-interface": name, "out-interface-list": name })
|
||||
const deny = object("egress-deny-4", { action: "drop", "out-interface-list": name })
|
||||
const objects = [allow, boundary, deny]
|
||||
const legacy = { ".id": "*B", ...boundary.fields }
|
||||
|
||||
assert.deepEqual(planIxNative(id, objects, objects, device({ [path]: [legacy] })).map(task => [task.fields, task.placeBefore]),
|
||||
[[allow.fields, "*B"], [deny.fields, "*B"]])
|
||||
assert.throws(() => planIxNative(id, objects, objects, device({ [path]: [{ ".id": "*C", ...allow.fields }, legacy] })),
|
||||
/предыдущей ревизии IX исчез/)
|
||||
})
|
||||
@@ -0,0 +1,918 @@
|
||||
import { createPrivateKey, createPublicKey, randomUUID } from "node:crypto"
|
||||
import { isIP } from "node:net"
|
||||
import { setTimeout as delay } from "node:timers/promises"
|
||||
import { ixChangeSchema, type IxChange, type IxConfiguration, type IxLinuxAccess, type IxLinuxBinding, type IxLinuxClientRequest, type IxLinuxPath, type IxNodeInventory, type IxRouterObject, type IxSegment, type IxSite, type IxSiteObservation, type IxTransitRequest } from "@mmapp/contracts/internet-exchange"
|
||||
import { constantEqual, fingerprint, privateFingerprinter, privateFingerprinterExisting } from "../modules/mcp/security.js"
|
||||
import { pool } from "../db/index.js"
|
||||
import { audit } from "../modules/mcp/store.js"
|
||||
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
|
||||
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
|
||||
import { assertVerifiedConfigurationAccess } from "./config-mutation-policy.js"
|
||||
import { compileIxConfiguration, inIxNetwork, IxConflict, ixClientRoutingTable, ixDeviceIds, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
|
||||
import { archiveIxSegment, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
|
||||
import { MikrotikClient } from "./mikrotik.js"
|
||||
import { ixGreClientTemplate, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
|
||||
|
||||
type NativeRow = Record<string, string>
|
||||
type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete">
|
||||
interface NativeDevice {
|
||||
serverId: number
|
||||
source: string
|
||||
rows: Record<string, NativeRow[]>
|
||||
}
|
||||
interface Task { serverId: number; path: string; fields?: Record<string, string>; before?: NativeRow; rosId?: string; placeBefore?: string }
|
||||
interface IxNativeChange {
|
||||
objects: IxRouterObject[]
|
||||
before: NativeDevice[]
|
||||
tasks: Task[]
|
||||
}
|
||||
|
||||
function wireguardKeys(seed: string) {
|
||||
const scalar = Buffer.from(seed, "hex")
|
||||
scalar[0] &= 248
|
||||
scalar[31] = (scalar[31] & 127) | 64
|
||||
const der = Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), scalar])
|
||||
const key = createPrivateKey({ key: der, format: "der", type: "pkcs8" })
|
||||
return {
|
||||
privateKey: scalar.toString("base64"),
|
||||
publicKey: createPublicKey(key).export({ format: "der", type: "spki" }).subarray(-32).toString("base64"),
|
||||
}
|
||||
}
|
||||
|
||||
async function ixLinuxWireguardKeys(segmentId: string, serverId: number, name: string, credentialId: string, create = false) {
|
||||
const derive = await (create ? privateFingerprinter : privateFingerprinterExisting)("ix-linux-wireguard-credential-v1")
|
||||
return wireguardKeys(derive([segmentId, serverId, name, credentialId].join(":")))
|
||||
}
|
||||
|
||||
const nativePlanDigest = ({ before, tasks }: IxNativeChange) => fingerprint({ before, tasks })
|
||||
|
||||
const routerId = /^\*[a-z\d]+$/i
|
||||
const marker = (path: string, comment: string) => path + "\0" + comment
|
||||
const objectMarker = (object: IxRouterObject) => marker(object.path, object.fields.comment ?? object.fields.name)
|
||||
const deviceMarker = (object: IxRouterObject) => object.serverId + "\0" + objectMarker(object)
|
||||
const isTrue = (value: unknown) => value === true || value === "true" || value === "yes"
|
||||
const columns = [".id", "comment", "name", "type", "disabled", "dynamic", "builtin", "interfaces", "routing-table", "dst-address", "gateway", "chain"]
|
||||
const filterPath = (path: string) => /^\/(ip|ipv6)\/firewall\/(filter|nat|raw|mangle)$/.test(path)
|
||||
const greColumns = [".id", "name", "local-address", "remote-address", "allow-fast-path"]
|
||||
const ipsecPolicyColumns = [".id", "action", "level", "tunnel", "protocol", "src-address", "dst-address", "disabled", "template"]
|
||||
|
||||
function normalize(field: string, value: string | undefined) {
|
||||
if (["blackhole", "fib"].includes(field) && value === "") return "yes"
|
||||
if (["disabled", "advertise", "blackhole", "multihop", "fib", "passive", "tunnel", "allow-fast-path", "passthrough"].includes(field)) {
|
||||
return value === undefined ? null : isTrue(value) ? "yes" : "no"
|
||||
}
|
||||
if (field === "rule") return value?.trim()
|
||||
if (field === "gateway") return value?.replace(/@main$/, "")
|
||||
if (field === "interfaces") return value?.split(",").sort().join(",")
|
||||
if (field === "allowed-address") return value?.split(",").sort().join(",")
|
||||
if (field === "persistent-keepalive" && /^\d+(s)?$/.test(value ?? "")) return Number(value?.replace(/s$/, ""))
|
||||
if (value && ["address", "src-address", "dst-address", "remote.address"].includes(field)) {
|
||||
const slash = value.lastIndexOf("/")
|
||||
const address = value.slice(0, slash)
|
||||
if ((value.endsWith("/32") && isIP(address) === 4) || (value.endsWith("/128") && isIP(address) === 6)) return address
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function matches(row: NativeRow, fields: Record<string, string>) {
|
||||
return Object.entries(fields).every(([field, value]) => normalize(field, row[field]) === normalize(field, value))
|
||||
}
|
||||
|
||||
function rowsFor(device: NativeDevice, path: string) { return device.rows[path] ?? [] }
|
||||
function managedRow(device: NativeDevice, object: IxRouterObject) {
|
||||
const matches = rowsFor(device, object.path).filter(row => object.fields.comment ? row.comment === object.fields.comment : row.name === object.fields.name)
|
||||
if (matches.length > 1) throw new IxConflict("Дублируется идентификатор объекта IX на RouterOS")
|
||||
return matches[0]
|
||||
}
|
||||
|
||||
function verifyNativeId(row: NativeRow) {
|
||||
if (!routerId.test(row[".id"] ?? "") || isTrue(row.dynamic) || isTrue(row.builtin)) throw new IxConflict("Объект IX не имеет подтверждённого статического ID")
|
||||
return row[".id"]
|
||||
}
|
||||
|
||||
export function planIxNative(id: string, desired: IxRouterObject[], previous: IxRouterObject[], devices: NativeDevice[], resume = false): Task[] {
|
||||
const namespace = ixNamespace(id)
|
||||
const egressObject = (comment = "") => comment.startsWith(namespace + ":egress-")
|
||||
const withEgressList = new Set(devices.filter(device => Object.values(device.rows).some(rows =>
|
||||
rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
|
||||
// An older applied revision had no egress list. A partial set still needs reconciliation.
|
||||
previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId))
|
||||
const desiredKeys = new Set(desired.map(deviceMarker))
|
||||
const previousByKey = new Map(previous.map(object => [deviceMarker(object), object]))
|
||||
const result: Task[] = []
|
||||
const shutdown: Task[] = []
|
||||
const interfaceCleanup: Task[] = []
|
||||
// Never remove user objects by name or rebuild a whole RouterOS resource table.
|
||||
for (const object of [...previous].reverse()) {
|
||||
if (desiredKeys.has(deviceMarker(object))) continue
|
||||
const device = devices.find(entry => entry.serverId === object.serverId)!
|
||||
const row = managedRow(device, object)
|
||||
if (!row && resume) continue
|
||||
const tunnel = ["/interface/wireguard", "/interface/gre"].includes(object.path)
|
||||
const managedTunnel = tunnel && [":wg-il-", ":gre-il-", ":transit-it-"].some(sign => object.fields.comment?.includes(sign))
|
||||
const alreadyStopped = managedTunnel && resume && row && matches(row, { ...object.fields, disabled: "true" })
|
||||
if (!row || !alreadyStopped && !matches(row, object.fields)) throw new IxConflict("Объект предыдущей ревизии IX изменён вне операции")
|
||||
const task = { serverId: object.serverId, path: object.path, rosId: verifyNativeId(row), before: row }
|
||||
if (managedTunnel && !isTrue(row.disabled)) shutdown.push({ ...task, fields: { disabled: "true" } })
|
||||
const steps = tunnel ? interfaceCleanup : result
|
||||
steps.push(managedTunnel ? { ...task, before: { ...row, disabled: "true" } } : task)
|
||||
}
|
||||
for (const object of desired) {
|
||||
const device = devices.find(entry => entry.serverId === object.serverId)!
|
||||
const path = object.path, row = managedRow(device, object)
|
||||
if (object.fields["routing-table"] === "main" &&
|
||||
rowsFor(device, path).some(entry => entry !== row && entry["routing-table"] === "main" && entry["dst-address"] === object.fields["dst-address"])) {
|
||||
throw new IxConflict("Служебный next hop BGP уже занят в таблице main")
|
||||
}
|
||||
if (resume && row && !isTrue(row.invalid) && matches(row, object.fields)) { verifyNativeId(row); continue }
|
||||
if (row && !previousByKey.has(deviceMarker(object))) {
|
||||
throw new IxConflict(object.fields.comment ? "Найден объект незавершённой операции IX. Сначала выполните сверку" :
|
||||
"Имя объекта IX уже занято. Сначала выполните сверку")
|
||||
}
|
||||
if (row) {
|
||||
const before = previousByKey.get(deviceMarker(object))!
|
||||
if (!matches(row, before.fields)) throw new IxConflict("Объект IX изменён вне операции")
|
||||
if (Object.keys(before.fields).some(field => !(field in object.fields))) {
|
||||
throw new IxConflict("Поле RouterOS нельзя неявно сбросить. Замените объект с новым идентификатором")
|
||||
}
|
||||
const fields = Object.fromEntries(Object.entries(object.fields).filter(([field, value]) => normalize(field, row[field]) !== normalize(field, value)))
|
||||
if (Object.keys(fields).length) result.push({ serverId: object.serverId, path, rosId: verifyNativeId(row), fields, before: row })
|
||||
continue
|
||||
}
|
||||
if (previousByKey.has(deviceMarker(object))) throw new IxConflict("Объект предыдущей ревизии IX исчез. Сначала выполните сверку")
|
||||
const foreign = rowsFor(device, path).some(entry => !entry.comment?.startsWith(namespace + ":") &&
|
||||
(object.fields.name && entry.name === object.fields.name || object.fields.chain && entry.chain === object.fields.chain && path === "/routing/filter/rule" ||
|
||||
object.fields["routing-table"] && entry["routing-table"] === namespace && !isTrue(entry.dynamic)))
|
||||
if (foreign) throw new IxConflict("Объект IX пересекается с существующей конфигурацией RouterOS")
|
||||
const placeBefore = path === "/ip/vrf" ? rowsFor(device, path).find(entry => entry.name === "main")?.[".id"] :
|
||||
filterPath(path) ? rowsFor(device, path)[0]?.[".id"] : undefined
|
||||
if (path === "/ip/vrf" && !routerId.test(placeBefore ?? "")) throw new IxConflict("Не подтверждена позиция VRF main")
|
||||
if (placeBefore && !routerId.test(placeBefore)) throw new IxConflict("Не подтверждена позиция правила фильтра")
|
||||
result.push({ serverId: object.serverId, path, fields: object.fields, placeBefore })
|
||||
}
|
||||
return shutdown.concat(result, interfaceCleanup)
|
||||
}
|
||||
|
||||
function verifyEgressMembers(device: NativeDevice, id: string, objects: IxRouterObject[]) {
|
||||
const path = "/interface/list/member"
|
||||
const list = ixEgressList(id)
|
||||
const catalogue = rowsFor(device, "/interface/list").find(row => row.name === list)
|
||||
const expected = objects.filter(object => object.serverId === device.serverId && object.path === path)
|
||||
if ([catalogue?.include, catalogue?.exclude].some(value => value && value !== "none") ||
|
||||
rowsFor(device, path).some(row => row.list === list && (isTrue(row.disabled) || !expected.some(object => matches(row, object.fields))))) {
|
||||
throw new IxConflict("В списке выходов IX есть посторонний интерфейс")
|
||||
}
|
||||
}
|
||||
|
||||
async function readRows(client: IpCore, path: string, props: readonly string[]) {
|
||||
const raw = await client.get<unknown>(path + "?" + new URLSearchParams({ ".proplist": [...new Set(props)].join(",") }))
|
||||
if (!Array.isArray(raw) || raw.length > 10000 || raw.some(value => !value || typeof value !== "object" || Array.isArray(value))) {
|
||||
throw new IxConflict("Не удалось прочитать полный каталог RouterOS")
|
||||
}
|
||||
return raw.map(entry => Object.fromEntries(props.flatMap(key => {
|
||||
const value = entry[key]
|
||||
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" ? [[key, String(value)]] : []
|
||||
}))) as NativeRow[]
|
||||
}
|
||||
|
||||
async function requiredIxNode(serverId: number, allowExitNode = false) {
|
||||
const server = await getServerRowById(serverId)
|
||||
if (!server?.enabled || (server.type !== "ix-node" && !(allowExitNode && server.type === "exit-node"))) {
|
||||
throw new IxConflict("Узел IX или ExitNode не найден либо отключён", 404)
|
||||
}
|
||||
return MikrotikClient.fromServer(server)
|
||||
}
|
||||
|
||||
async function observedIxRouterIds(client: IpCore, segmentId?: string) {
|
||||
const [bgp, ospf, named, sessions] = await Promise.all([
|
||||
readRows(client, "/routing/bgp/instance", ["name", "router-id"]),
|
||||
readRows(client, "/routing/ospf/instance", ["router-id"]),
|
||||
readRows(client, "/routing/id", ["name", "id", "dynamic-id"]),
|
||||
readRows(client, "/routing/bgp/session", ["remote.id"]),
|
||||
])
|
||||
const others = bgp.filter(row => !segmentId || row.name !== ixNamespace(segmentId))
|
||||
const selected = [...others, ...ospf].map(row => row["router-id"])
|
||||
return new Set([...selected, ...named.flatMap(row => [row.id, row["dynamic-id"]]),
|
||||
...sessions.map(row => row["remote.id"])].filter(value => isIP(value ?? "") === 4 && value !== "0.0.0.0"))
|
||||
}
|
||||
|
||||
export async function readIxNodeInventory(serverId: number, segment?: IxSegment, allowExitNode = false): Promise<IxNodeInventory> {
|
||||
const client = await requiredIxNode(serverId, allowExitNode)
|
||||
const [interfaces, bridgePorts, vrfs, routes, ipv6Routes, addresses, ipv6Addresses, wireguard, observed, reserved] = await Promise.all([
|
||||
readRows(client, "/interface", ["name", "type", "running", "disabled", "comment"]),
|
||||
readRows(client, "/interface/bridge/port", ["interface", "bridge"]),
|
||||
readRows(client, "/ip/vrf", ["name", "interfaces"]),
|
||||
readRows(client, "/ip/route", ["routing-table", "dst-address", "gateway", "immediate-gw", "active"]),
|
||||
readRows(client, "/ipv6/route", ["routing-table", "dst-address", "gateway", "immediate-gw", "active"]),
|
||||
readRows(client, "/ip/address", ["interface", "address"]),
|
||||
readRows(client, "/ipv6/address", ["interface", "address"]),
|
||||
readRows(client, "/interface/wireguard", ["listen-port"]),
|
||||
observedIxRouterIds(client, segment?.id).catch(() => null),
|
||||
ixReservedRouterIds(segment?.id),
|
||||
])
|
||||
const namespace = segment ? ixNamespace(segment.id) : null
|
||||
const owned = segment?.configuration.sites.find(site => site.serverId === serverId)
|
||||
const allAddresses = addresses.concat(ipv6Addresses)
|
||||
return {
|
||||
observedAt: new Date().toISOString(),
|
||||
routerId: owned?.routerId ?? (observed ? nextIxRouterId(new Set([...observed, ...reserved,
|
||||
...allAddresses.map(row => row.address?.split("/")[0]), ...(segment?.configuration.sites.map(site => site.routerId) ?? [])])) : null),
|
||||
wireguardPorts: wireguard.map(row => Number(row["listen-port"])).filter(port => Number.isInteger(port) && port > 0),
|
||||
defaultRoutes: ([4, 6] as const).flatMap(family => (family === 4 ? routes : ipv6Routes).flatMap(row => {
|
||||
if (row["routing-table"] !== "main" || row["dst-address"] !== (family === 4 ? "0.0.0.0/0" : "::/0") || !isTrue(row.active)) return []
|
||||
const [gateway, iface] = (row["immediate-gw"] ?? row.gateway ?? "").split("%")
|
||||
const name = iface?.split("@")[0]
|
||||
return name && isIP(gateway) === family && interfaces.some(item => item.name === name && !isTrue(item.disabled))
|
||||
? [{ family, gateway, interface: name }] : []
|
||||
})),
|
||||
interfaces: interfaces.filter(row => row.name).map(row => {
|
||||
const foreign = vrfs.find(vrf => vrf.name !== "main" && vrf.name !== namespace && vrf.interfaces?.split(",").includes(row.name))
|
||||
const bridge = bridgePorts.find(port => port.interface === row.name)
|
||||
const main = routes.concat(ipv6Routes).some(route => route["routing-table"] === "main" &&
|
||||
(route.gateway === row.name || [route.gateway, route["immediate-gw"]].some(value => value?.split("%")[1]?.split("@")[0] === row.name)))
|
||||
return {
|
||||
name: row.name, type: row.type ?? "", running: isTrue(row.running), disabled: isTrue(row.disabled),
|
||||
addresses: allAddresses.filter(address => address.interface === row.name && address.address).map(address => address.address),
|
||||
restriction: row.name === namespace || row.name === (segment && ixDiscardInterface(segment.id)) ? "Служебный интерфейс IX" :
|
||||
foreign ? "Интерфейс используется в VRF " + foreign.name : bridge ? "Порт моста " + bridge.bridge :
|
||||
main ? "Интерфейс используется в таблице main" : null,
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export async function assignIxRouterIds(id: string, configuration: IxConfiguration, existing: IxSegment | null) {
|
||||
const used = await ixReservedRouterIds(id)
|
||||
const sites = await Promise.all(configuration.sites.map(async site => {
|
||||
if (!site.autoRouterId || existing?.configuration.sites.some(old => old.serverId === site.serverId && old.routerId === site.routerId)) {
|
||||
return { site }
|
||||
}
|
||||
const routerIds = await observedIxRouterIds(await requiredIxNode(site.serverId), id).catch(() => new Set<string>())
|
||||
return { site, routerIds }
|
||||
}))
|
||||
const candidates = new Set([...used, ...sites.flatMap(({ site, routerIds }) => routerIds ? [...routerIds] : [site.routerId])])
|
||||
return { ...configuration, sites: sites.map(({ site, routerIds }) => {
|
||||
if (!routerIds) return site
|
||||
const routerId = !candidates.has(site.routerId) && site.routerId !== "0.0.0.0" ? site.routerId : nextIxRouterId(candidates)
|
||||
candidates.add(routerId)
|
||||
return { ...site, routerId }
|
||||
}) }
|
||||
}
|
||||
|
||||
export async function configureIxLinuxClient(segment: IxSegment, input: IxLinuxClientRequest) {
|
||||
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
|
||||
if (!site) throw new IxConflict("Узел не входит в сегмент IX", 404)
|
||||
const previous = site.interfaces.find(binding => binding.name === input.interfaceName && binding.linux)
|
||||
if (input.interfaceName && !previous) throw new IxConflict("Управляемый клиент не найден", 404)
|
||||
if (previous && previous.kind !== input.kind) throw new IxConflict("Для смены протокола создайте новое подключение", 400)
|
||||
const [inventory, reserved] = await Promise.all([
|
||||
readIxNodeInventory(site.serverId, segment), ixReservedTunnelBindings(site.serverId),
|
||||
])
|
||||
const currentTunnel = previous?.provisionWireguard ?? previous?.provisionGre
|
||||
let localAddress = input.localAddress ?? currentTunnel?.localAddress
|
||||
let peerAddress = input.peerAddress ?? currentTunnel?.peerAddress
|
||||
if (!localAddress && !peerAddress) {
|
||||
const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved
|
||||
.concat(segment.configuration.sites.flatMap(candidate => candidate.interfaces))
|
||||
.flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress,
|
||||
binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined)))
|
||||
for (let index = 0; index < 65536; index += 4) {
|
||||
const base = "10.254." + (index >> 8) + "."
|
||||
const next = base + ((index & 255) + 1) + "/30"
|
||||
if (used.some(network => inIxNetwork(network, next) || inIxNetwork(next, network))) continue
|
||||
localAddress = next
|
||||
peerAddress = base + ((index & 255) + 2)
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!localAddress || !peerAddress) throw new IxConflict("Укажите оба адреса туннеля или оставьте их для автоматического подбора", 400)
|
||||
const ports = new Set(inventory.wireguardPorts)
|
||||
for (const binding of [...reserved, ...site.interfaces]) {
|
||||
if (binding.provisionWireguard) ports.add(binding.provisionWireguard.listenPort)
|
||||
if (binding.provisionTransit) {
|
||||
ports.add(binding.provisionTransit.localPort)
|
||||
ports.add(binding.provisionTransit.remotePort)
|
||||
}
|
||||
}
|
||||
let listenPort = 51820
|
||||
while (ports.has(listenPort) && listenPort <= 65535) listenPort++
|
||||
const name = previous?.name ?? "il-" + randomUUID().replace(/-/g, "").slice(0, 12)
|
||||
const family = isIP(peerAddress)
|
||||
const localExit = "ix-wan" + family
|
||||
const groups = [...site.groups]
|
||||
if (input.exit === "local-wan" && !groups.some(group => group.id === localExit)) {
|
||||
const wan = inventory.defaultRoutes.find(route => route.family === family)
|
||||
if (!wan) throw new IxConflict("Не найден действующий WAN в таблице main для этого семейства")
|
||||
const occupied = new Set(groups.map(group => group.gateway))
|
||||
let gateway = family === 4 ? "198.19.255.254" : "fd00:198:18::ffff"
|
||||
for (let suffix = 1; occupied.has(gateway) && suffix < 255; suffix++) {
|
||||
gateway = family === 4 ? "198.19.254." + suffix : "fd00:198:18::" + suffix.toString(16)
|
||||
}
|
||||
groups.push({ id: localExit, gateway, onFailure: "block",
|
||||
primary: { interface: wan.interface, nextHop: wan.gateway, probe: wan.gateway, viaMain: true } })
|
||||
}
|
||||
const binding: IxSite["interfaces"][number] = {
|
||||
name, kind: input.kind, prefixes: input.prefixes,
|
||||
linux: { name: input.name, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
|
||||
exit: input.exit === "local-wan" ? localExit : input.exit },
|
||||
}
|
||||
if (input.kind === "wireguard") {
|
||||
const existing = previous?.provisionWireguard
|
||||
if (!existing && listenPort > 65535) throw new IxConflict("Нет свободного порта WireGuard", 400)
|
||||
let peerPublicKey = input.peerPublicKey ?? existing?.peerPublicKey
|
||||
let credentialId = peerPublicKey === existing?.peerPublicKey ? existing?.credentialId : undefined
|
||||
if (!peerPublicKey) {
|
||||
credentialId = randomUUID()
|
||||
peerPublicKey = (await ixLinuxWireguardKeys(segment.id, site.serverId, name, credentialId, true)).publicKey
|
||||
}
|
||||
binding.provisionWireguard = { peerPublicKey, credentialId, listenPort: existing?.listenPort ?? listenPort,
|
||||
localAddress, peerAddress, hubEndpoint: input.hubEndpoint }
|
||||
} else {
|
||||
if (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4) throw new IxConflict("Укажите два внешних IPv4 для GRE/IPsec", 400)
|
||||
binding.endpoint = input.peerEndpoint
|
||||
binding.localEndpoint = input.hubEndpoint
|
||||
binding.provisionGre = { localAddress, peerAddress,
|
||||
credentialId: !input.rotate && previous?.provisionGre?.credentialId || randomUUID() }
|
||||
}
|
||||
const interfaces = previous ? site.interfaces.map(candidate => candidate === previous ? binding : candidate) : [...site.interfaces, binding]
|
||||
const configuration = { ...segment.configuration, sites: segment.configuration.sites.map(candidate => candidate === site
|
||||
? { ...site, interfaces, groups } : candidate) }
|
||||
compileIxConfiguration(segment.id, configuration)
|
||||
return { configuration, interfaceName: name }
|
||||
}
|
||||
|
||||
export async function configureIxTransit(segment: IxSegment, input: IxTransitRequest) {
|
||||
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
|
||||
if (!site || input.targetServerId === input.serverId) throw new IxConflict("Выберите другую площадку IX или ExitNode", 400)
|
||||
if (site.groups.some(group => group.id === input.name)) throw new IxConflict("Имя группы шлюзов уже занято")
|
||||
const [origin, remote, a, b] = await Promise.all([
|
||||
readIxNodeInventory(site.serverId, segment), readIxNodeInventory(input.targetServerId, segment, true),
|
||||
ixReservedTunnelBindings(site.serverId), ixReservedTunnelBindings(input.targetServerId),
|
||||
])
|
||||
const wan = remote.defaultRoutes.find(route => route.family === input.family)
|
||||
if (!wan) throw new IxConflict("У выбранного узла нет активного IPv" + input.family + " WAN")
|
||||
const localIps = origin.interfaces.flatMap(item => item.addresses)
|
||||
const remoteIps = remote.interfaces.flatMap(item => item.addresses)
|
||||
if (!localIps.some(ip => ip.split("/")[0] === input.localEndpoint) || !remoteIps.some(ip => ip.split("/")[0] === input.remoteEndpoint)) {
|
||||
throw new IxConflict("Внешние IP транзита должны принадлежать выбранным маршрутизаторам", 400)
|
||||
}
|
||||
const occupied = a.concat(b).flatMap(binding =>
|
||||
[binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress, binding.provisionTransit?.localAddress, ...binding.prefixes]
|
||||
.filter(value => value !== undefined))
|
||||
const credentialId = randomUUID()
|
||||
const name = "it-" + credentialId.replace(/-/g, "").slice(0, 12)
|
||||
let third = parseInt(credentialId.slice(0, 2), 16)
|
||||
const addressBase = (value: number) => input.family === 4 ? "10.253." + value + "." : "fd00:253:" + value.toString(16) + "::"
|
||||
const mask = input.family === 4 ? "/30" : "/126"
|
||||
let base = addressBase(third)
|
||||
for (let tries = 0; occupied.concat(localIps, remoteIps).some(network =>
|
||||
inIxNetwork(network, base + "1" + mask) || inIxNetwork(base + "1" + mask, network)); tries++) {
|
||||
if (tries >= 255) throw new IxConflict("Пул адресов транзитных туннелей занят")
|
||||
third = (third + 1) % 256
|
||||
base = addressBase(third)
|
||||
}
|
||||
const freePort = (inventory: IxNodeInventory, start: number) => {
|
||||
const used = new Set(inventory.wireguardPorts)
|
||||
for (const binding of a.concat(b)) {
|
||||
if (binding.provisionWireguard) used.add(binding.provisionWireguard.listenPort)
|
||||
if (binding.provisionTransit) {
|
||||
used.add(binding.provisionTransit.localPort)
|
||||
used.add(binding.provisionTransit.remotePort)
|
||||
}
|
||||
}
|
||||
while (used.has(start) && start <= 65535) start++
|
||||
if (start > 65535) throw new IxConflict("Свободные порты WireGuard закончились")
|
||||
return start
|
||||
}
|
||||
const localPort = freePort(origin, 52000)
|
||||
const remotePort = freePort(remote, localPort + 1)
|
||||
const binding: IxSite["interfaces"][number] = { name, kind: "wireguard", prefixes: [], peerServerId: input.targetServerId,
|
||||
provisionTransit: { localEndpoint: input.localEndpoint, remoteEndpoint: input.remoteEndpoint, localAddress: base + "1" + mask,
|
||||
remoteAddress: base + "2", localPort, remotePort, credentialId,
|
||||
remoteWan: { interface: wan.interface, nextHop: wan.gateway, probe: wan.gateway, viaMain: true } } }
|
||||
const group: IxSite["groups"][number] = { id: input.name,
|
||||
gateway: input.family === 4 ? "198.19.253." + third : "fd00:198:18:253::" + (third + 1).toString(16), onFailure: "block",
|
||||
primary: { interface: binding.name, nextHop: base + "2", probe: input.probe ?? base + "2" } }
|
||||
const configuration = { ...segment.configuration, sites: segment.configuration.sites.map(candidate => candidate === site
|
||||
? { ...site, interfaces: [...site.interfaces, binding], groups: [...site.groups, group] } : candidate) }
|
||||
compileIxConfiguration(segment.id, configuration)
|
||||
return configuration
|
||||
}
|
||||
|
||||
async function readDevice(server: ServerRow, objects: IxRouterObject[], removing = false): Promise<NativeDevice> {
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const fieldsByPath = new Map<string, string[]>([["/interface", columns], ["/interface/bridge/port", [".id", "bridge", "interface"]],
|
||||
["/ip/vrf", columns], ["/ip/route", columns], ["/ipv6/route", columns]])
|
||||
if (removing || objects.some(object => object.fields.gateway?.endsWith("@main"))) {
|
||||
for (const path of ["/ip/address", "/ipv6/address"]) fieldsByPath.set(path, [...columns, "interface"])
|
||||
for (const path of ["/ip/address", "/ipv6/address"]) fieldsByPath.get(path)!.push("address")
|
||||
}
|
||||
for (const object of objects) {
|
||||
fieldsByPath.set(object.path, [...new Set([...(fieldsByPath.get(object.path) ?? columns),
|
||||
...(filterPath(object.path) ? ["invalid"] : []), ...Object.keys(object.fields)])])
|
||||
}
|
||||
if (fieldsByPath.has("/interface/list")) fieldsByPath.get("/interface/list")!.push("include", "exclude")
|
||||
if (objects.some(object => object.fields["ipsec-policy"])) {
|
||||
fieldsByPath.set("/interface/gre", [...new Set([...greColumns, ...(fieldsByPath.get("/interface/gre") ?? [])])])
|
||||
fieldsByPath.set("/ip/ipsec/policy", [...new Set([...ipsecPolicyColumns, ...(fieldsByPath.get("/ip/ipsec/policy") ?? [])])])
|
||||
}
|
||||
const rows: Record<string, NativeRow[]> = {}
|
||||
for (const [path, keys] of fieldsByPath) rows[path] = await readRows(client, path, keys)
|
||||
for (const path of ["/ip/route", "/ipv6/route"]) {
|
||||
const reserved = new Set(objects.filter(object => object.path === path && object.fields["routing-table"] === "main").map(object => object.fields["dst-address"]))
|
||||
rows[path] = rows[path].filter(row => !isTrue(row.dynamic) || (row["routing-table"] === "main" && reserved.has(row["dst-address"])))
|
||||
}
|
||||
return { serverId: server.id, source: fingerprint(server), rows }
|
||||
}
|
||||
|
||||
function verifyGreBinding(binding: IxSite["interfaces"][number], interfaces: NativeRow[], policies: NativeRow[]) {
|
||||
const gre = interfaces.find(row => row.name === binding.name)
|
||||
const policy = policies.some(row =>
|
||||
!isTrue(row.disabled) && !isTrue(row.template) && !isTrue(row.tunnel) &&
|
||||
row.action === "encrypt" && ["require", "unique"].includes(row.level) && ["gre", "47"].includes(row.protocol) &&
|
||||
row["src-address"] === binding.localEndpoint + "/32" && row["dst-address"] === binding.endpoint + "/32")
|
||||
if (!gre || gre["local-address"] !== binding.localEndpoint || gre["remote-address"] !== binding.endpoint || !policy) {
|
||||
throw new IxConflict("Для " + binding.name + " не подтверждены адреса и обязательная политика GRE/IPsec")
|
||||
}
|
||||
if (!["false", "no"].includes(gre["allow-fast-path"])) {
|
||||
throw new IxConflict("Отключите FastPath на интерфейсе GRE/IPsec " + binding.name)
|
||||
}
|
||||
return gre
|
||||
}
|
||||
|
||||
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[]) {
|
||||
for (const site of configuration.sites) {
|
||||
const device = devices.find(entry => entry.serverId === site.serverId)!
|
||||
if (rowsFor(device, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) {
|
||||
throw new IxConflict("Изолированный bridge отбрасывания IX содержит порты")
|
||||
}
|
||||
for (const binding of site.interfaces) {
|
||||
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
|
||||
if (!iface && (binding.provisionWireguard || binding.provisionGre || binding.provisionTransit)) continue
|
||||
const expected = binding.kind === "wireguard" ? "wg" : binding.kind === "gre-ipsec" ? "gre-tunnel" : null
|
||||
if (!iface || (expected && iface.type !== expected && !(expected === "wg" && iface.type === "wireguard") &&
|
||||
!(expected === "gre-tunnel" && iface.type === "gre"))) {
|
||||
throw new IxConflict("Не найден подготовленный интерфейс " + binding.name)
|
||||
}
|
||||
// Moving an existing interface into a VRF affects the entire interface.
|
||||
// Explicit staging on the CHR separates IX handoff from existing services.
|
||||
if (iface.comment !== "IX:" + configuration.name &&
|
||||
!(binding.provisionWireguard && iface.comment?.startsWith(ixNamespace(id) + ":wg-")) &&
|
||||
!(binding.provisionGre && iface.comment === ixNamespace(id) + ":gre-" + binding.name) &&
|
||||
!(binding.provisionTransit && iface.comment === ixNamespace(id) + ":transit-" + binding.name + "-source-wg")) {
|
||||
throw new IxConflict("Интерфейс " + binding.name + " не выделен для данного сегмента IX")
|
||||
}
|
||||
const foreignVrf = rowsFor(device, "/ip/vrf").find(row => row.name !== "main" && row.name !== ixNamespace(id) && row.interfaces?.split(",").includes(binding.name))
|
||||
const mainRoutes = [...rowsFor(device, "/ip/route"), ...rowsFor(device, "/ipv6/route")].filter(row => row["routing-table"] === "main" && !isTrue(row.dynamic))
|
||||
if (foreignVrf || mainRoutes.some(row => row.gateway === binding.name || row.gateway?.includes("%" + binding.name))) {
|
||||
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
|
||||
}
|
||||
if (binding.kind === "gre-ipsec") {
|
||||
verifyGreBinding(binding, rowsFor(device, "/interface/gre"), rowsFor(device, "/ip/ipsec/policy"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function verifyIxMainGateways(device: NativeDevice, objects: IxRouterObject[]) {
|
||||
for (const object of objects) {
|
||||
const gateway = object.fields.gateway
|
||||
if (!gateway?.endsWith("@main")) continue
|
||||
const [nextHop, scoped] = gateway.split("%")
|
||||
const name = scoped?.split("@")[0]
|
||||
if (!name) continue
|
||||
const iface = rowsFor(device, "/interface").find(row => row.name === name)
|
||||
const addressPath = isIP(nextHop) === 6 ? "/ipv6/address" : "/ip/address"
|
||||
const inMain = !rowsFor(device, "/ip/vrf").some(row => row.name !== "main" && row.interfaces?.split(",").includes(name))
|
||||
const onLink = rowsFor(device, addressPath).some(row => row.interface === name && !isTrue(row.disabled) &&
|
||||
row.address?.includes("/") && inIxNetwork(row.address, nextHop))
|
||||
if (!iface || isTrue(iface.disabled) || !inMain || !onLink) {
|
||||
throw new IxConflict("WAN-шлюз " + nextHop + " недоступен напрямую через " + name + " в таблице main")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveIxCredentials(id: string, objects: IxRouterObject[], existing: boolean) {
|
||||
const key = existing ? privateFingerprinterExisting : privateFingerprinter
|
||||
const [psk, wg] = await Promise.all([
|
||||
objects.some(object => object.fields.secret?.startsWith("ix-credential:")) ? key("ix-gre-client-credential-v1") : null,
|
||||
objects.some(object => object.fields["private-key"]?.startsWith("ix-transit:")) ? key("ix-transit-wireguard-v1") : null,
|
||||
])
|
||||
if (!psk && !wg) return objects
|
||||
return objects.map(object => ({ ...object, fields: Object.fromEntries(Object.entries(object.fields).map(([name, value]) => {
|
||||
if (name === "secret" && psk && value.startsWith("ix-credential:")) return [name, psk(id + ":" + object.serverId + ":" + value)]
|
||||
if (wg && ["public-key", "private-key"].includes(name) && value.startsWith("ix-transit:")) {
|
||||
const [, variant, version, side] = value.split(":")
|
||||
const keys = wireguardKeys(wg([id, version, side].join(":")))
|
||||
return [name, variant === "private" ? keys.privateKey : keys.publicKey]
|
||||
}
|
||||
return [name, value]
|
||||
})) }))
|
||||
}
|
||||
|
||||
async function prepareNative(id: string, configuration: IxConfiguration | null, previousConfiguration: IxConfiguration | null, resume = false): Promise<IxNativeChange> {
|
||||
for (const site of configuration?.sites ?? []) for (const binding of site.interfaces) {
|
||||
const wg = binding.provisionWireguard
|
||||
if (!wg?.credentialId) continue
|
||||
const keys = await ixLinuxWireguardKeys(id, site.serverId, binding.name, wg.credentialId)
|
||||
if (!binding.linux || !constantEqual(keys.publicKey, wg.peerPublicKey)) {
|
||||
throw new IxConflict("Ключ WireGuard не соответствует управляемому клиенту IX")
|
||||
}
|
||||
}
|
||||
const previous = previousConfiguration ? await resolveIxCredentials(id, compileIxConfiguration(id, previousConfiguration), true) : []
|
||||
const objects = configuration ? await resolveIxCredentials(id, compileIxConfiguration(id, configuration), false) : []
|
||||
const before: NativeDevice[] = []
|
||||
for (const serverId of [...new Set([...objects, ...previous].map(object => object.serverId))].sort((a, b) => a - b)) {
|
||||
const server = await getServerRowById(serverId)
|
||||
const isSite = [configuration, previousConfiguration].some(config => config?.sites.some(site => site.serverId === serverId))
|
||||
if (!server?.enabled || server.type !== "ix-node" && (isSite || server.type !== "exit-node")) {
|
||||
throw new IxConflict("Узел транзита отключён или изменил тип")
|
||||
}
|
||||
const site = configuration?.sites.find(candidate => candidate.serverId === serverId)
|
||||
if (site?.autoRouterId && (await observedIxRouterIds(MikrotikClient.fromServer(server), id)).has(site.routerId)) {
|
||||
throw new IxConflict("Router ID " + site.routerId + " уже используется на CHR")
|
||||
}
|
||||
before.push(await readDevice(server, [...objects, ...previous].filter(object => object.serverId === serverId), !configuration))
|
||||
verifyIxMainGateways(before.at(-1)!, objects.filter(object => object.serverId === serverId))
|
||||
}
|
||||
if (configuration) validateBindings(configuration, id, before)
|
||||
for (const device of before) verifyEgressMembers(device, id, resume ? previous.concat(objects) : previous)
|
||||
for (const old of previousConfiguration?.sites ?? []) {
|
||||
const next = configuration?.sites.find(site => site.serverId === old.serverId)
|
||||
const device = before.find(device => device.serverId === old.serverId)!
|
||||
if (!configuration) verifyRemovalScope(id, device, previous)
|
||||
for (const binding of old.interfaces.filter(binding => !next?.interfaces.some(candidate => candidate.name === binding.name))) {
|
||||
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
|
||||
if (binding.linux || binding.provisionTransit || !configuration &&
|
||||
(!iface || binding.provisionWireguard || !rowsFor(device, "/ip/vrf").some(row => row.name === ixNamespace(id)))) continue
|
||||
if (!isTrue(iface?.disabled)) {
|
||||
throw new IxConflict("Отключите интерфейс перед исключением из VRF IX: " + binding.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
const remaining = configuration ? previous : previous.filter(object =>
|
||||
managedRow(before.find(device => device.serverId === object.serverId)!, object))
|
||||
return { objects, before, tasks: planIxNative(id, objects, remaining, before, resume) }
|
||||
}
|
||||
|
||||
async function assertIxResume(id: string, revision: number, native: IxNativeChange) {
|
||||
const { rows: [attempt] } = await pool.query<{ sources: unknown }>(`
|
||||
SELECT payload->'sources' AS sources FROM mcp_audit
|
||||
WHERE action='ix.web.apply_started' AND payload->>'segmentId'=$1 AND payload->>'revision'=$2
|
||||
ORDER BY id DESC LIMIT 1
|
||||
`, [id, String(revision)])
|
||||
const sources = native.before.map(device => [device.serverId, device.source])
|
||||
if (!attempt || fingerprint(attempt.sources) !== fingerprint(sources)) {
|
||||
throw new IxConflict("Нет подтверждённой попытки применения этой ревизии к этим устройствам")
|
||||
}
|
||||
}
|
||||
|
||||
function verifyRemovalScope(id: string, device: NativeDevice, previous: IxRouterObject[]) {
|
||||
const namespace = ixNamespace(id)
|
||||
const managed = previous.filter(object => object.serverId === device.serverId)
|
||||
const known = new Set(managed.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 ?? "")) &&
|
||||
(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)) ||
|
||||
managed.some(object => object.path === path && object.fields.name && object.fields.name === row.name)))) {
|
||||
throw new IxConflict("На узле остались объекты, которых нет в применённой ревизии IX")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareIxRemoval(id: string, revision: number) {
|
||||
const segment = await readIxSegment(id)
|
||||
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
|
||||
assertIxRevision(segment, revision)
|
||||
const applied = segment.appliedRevision === null ? null : await readIxRevision(id, segment.appliedRevision)
|
||||
const native = await prepareNative(id, null, applied)
|
||||
return { segment, native, digest: nativePlanDigest(native) }
|
||||
}
|
||||
|
||||
export async function ixTarget(change: IxChange) {
|
||||
const current = change.id ? await readIxSegment(change.id) : null
|
||||
const applied = current?.appliedRevision && current.id ? await readIxRevision(current.id, current.appliedRevision) : null
|
||||
return [...new Set([...ixDeviceIds(change.configuration), ...(current ? ixDeviceIds(current.configuration) : []), ...(applied ? ixDeviceIds(applied) : [])])].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
export async function prepareIxChange(raw: unknown, resume = false) {
|
||||
const change = ixChangeSchema.parse(raw)
|
||||
const id = change.id ?? randomUUID()
|
||||
const current = change.id ? await readIxSegment(id) : null
|
||||
assertIxRevision(current, change.revision)
|
||||
await assertIxName(id, change.configuration.name)
|
||||
await assertIxSites(change.configuration)
|
||||
const previous = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
|
||||
const native = await prepareNative(id, change.configuration, previous, resume)
|
||||
if (resume) await assertIxResume(id, change.revision, native)
|
||||
const before = { revision: current?.revision ?? 0, devices: nativePlanDigest(native) }
|
||||
const objects = native.before.flatMap(device => [{ kind: "server", id: String(device.serverId), serverId: device.serverId }])
|
||||
return { id, change, before, native, objects }
|
||||
}
|
||||
|
||||
export async function currentIxChange(id: string, change: IxChange) {
|
||||
const current = await readIxSegment(id)
|
||||
if (current?.revision !== change.revision && !(current === null && change.revision === 0)) return { revision: current?.revision ?? 0 }
|
||||
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
|
||||
const native = await prepareNative(id, change.configuration, applied)
|
||||
return { revision: current?.revision ?? 0, devices: nativePlanDigest(native) }
|
||||
}
|
||||
|
||||
export async function reconcileIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, authorize: () => Promise<void>) {
|
||||
const current = await readIxSegment(id)
|
||||
if (current?.revision === expected.revision + 1 && current.appliedRevision === current.revision &&
|
||||
fingerprint(current.configuration) === fingerprint(change.configuration)) {
|
||||
const desired = await resolveIxCredentials(id, compileIxConfiguration(id, change.configuration), true)
|
||||
let matchesDesiredState = true
|
||||
for (const serverId of [...new Set(desired.map(object => object.serverId))]) {
|
||||
await authorize()
|
||||
const server = await getServerRowById(serverId)
|
||||
if (!server?.enabled) return { matchesDesiredState: false, matchesOriginalState: false }
|
||||
const objects = desired.filter(object => object.serverId === serverId)
|
||||
const observed = await readDevice(server, objects)
|
||||
try { verifyEgressMembers(observed, id, objects) }
|
||||
catch { return { matchesDesiredState: false, matchesOriginalState: false } }
|
||||
matchesDesiredState &&= objects.every(object => {
|
||||
const row = managedRow(observed, object)
|
||||
return row && !isTrue(row.invalid) && matches(row, object.fields)
|
||||
})
|
||||
}
|
||||
return { matchesDesiredState, matchesOriginalState: false }
|
||||
}
|
||||
try {
|
||||
await authorize()
|
||||
return { matchesDesiredState: false, matchesOriginalState: fingerprint(await currentIxChange(id, change)) === fingerprint(expected) }
|
||||
} catch {
|
||||
return { matchesDesiredState: false, matchesOriginalState: false }
|
||||
}
|
||||
}
|
||||
|
||||
export async function observeIxSegment(segment: IxSegment): Promise<IxSiteObservation[]> {
|
||||
if (!segment.appliedRevision) return []
|
||||
const applied = await readIxRevision(segment.id, segment.appliedRevision)
|
||||
const namespace = ixNamespace(segment.id)
|
||||
return Promise.all(applied.sites.map(async ({ serverId }) => {
|
||||
const observedAt = new Date().toISOString()
|
||||
try {
|
||||
const server = await getServerRowById(serverId)
|
||||
if (!server?.enabled || server.type !== "ix-node") throw new IxConflict("Площадка IX недоступна")
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const routeFields = ["dst-address", "routing-table", "gateway", "immediate-gw", "active"]
|
||||
const lookup = new URLSearchParams({ ".proplist": routeFields.join(","), "routing-table": namespace })
|
||||
const [routes, sessions] = await Promise.all([
|
||||
client.get<unknown>("/routing/route?" + lookup),
|
||||
readRows(client, "/routing/bgp/session", ["name", "established"]),
|
||||
])
|
||||
if (!Array.isArray(routes) || routes.length > 10000) throw new IxConflict("Таблица IX недоступна")
|
||||
return {
|
||||
serverId, observedAt, available: true,
|
||||
routes: routes.filter(row => row && row["routing-table"] === namespace && typeof row["dst-address"] === "string").slice(0, 100).map(row => ({
|
||||
prefix: row["dst-address"], gateway: typeof row.gateway === "string" ? row.gateway : "",
|
||||
immediateGateway: typeof row["immediate-gw"] === "string" ? row["immediate-gw"] : null,
|
||||
active: isTrue(row.active),
|
||||
})),
|
||||
neighbors: sessions.filter(row => row.name?.startsWith(namespace + "-")).map(row => ({ name: row.name, established: isTrue(row.established) })),
|
||||
}
|
||||
} catch {
|
||||
return { serverId, observedAt, available: false, routes: [], neighbors: [] }
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
export async function listIxLinuxClients(segment: IxSegment) {
|
||||
const revision = segment.appliedRevision
|
||||
if (revision === null) return { revision, items: [] }
|
||||
const configuration = await readIxRevision(segment.id, revision)
|
||||
const sites = await Promise.all(configuration.sites.map(async site => {
|
||||
const bindings = site.interfaces.filter(binding => ixLinuxBindingKind(binding) && !binding.peerServerId)
|
||||
const items: IxLinuxBinding[] = bindings.map(binding => ({
|
||||
serverId: site.serverId, interfaceName: binding.name, kind: ixLinuxBindingKind(binding)!,
|
||||
...(binding.provisionWireguard?.credentialId && { managedWireguard: true }),
|
||||
...(binding.linux && { name: binding.linux.name, enabled: binding.linux.enabled, policy: binding.linux }),
|
||||
}))
|
||||
if (!bindings.some(binding => binding.linux?.enabled)) return items
|
||||
const observedAt = new Date().toISOString()
|
||||
try {
|
||||
const client = await requiredIxNode(site.serverId)
|
||||
const [peers, ipsec] = await Promise.all([
|
||||
bindings.some(binding => binding.linux && binding.provisionWireguard) ? readRows(client, "/interface/wireguard/peers",
|
||||
["interface", "public-key", "last-handshake", "rx", "tx"]) : [],
|
||||
bindings.some(binding => binding.linux && binding.provisionGre) ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]) : [],
|
||||
])
|
||||
for (const [index, binding] of bindings.entries()) {
|
||||
if (!binding.linux?.enabled) continue
|
||||
const peer = peers.find(row => row.interface === binding.name && row["public-key"] === binding.provisionWireguard?.peerPublicKey)
|
||||
const handshake = peer?.["last-handshake"]?.trim()
|
||||
const age = handshake && /^\d+:\d{2}:\d{2}$/.test(handshake)
|
||||
? handshake.split(":").reduce((total, part) => total * 60 + Number(part), 0)
|
||||
: handshake && /^(?:(\d+)m)?(?:(\d+)s)?$/.exec(handshake)
|
||||
const fresh = typeof age === "number" ? age < 180 :
|
||||
Array.isArray(age) && Number(age[1] ?? 0) * 60 + Number(age[2] ?? 0) < 180
|
||||
const established = binding.provisionGre && ipsec.some(row => row.state === "established" &&
|
||||
(row["remote-address"] === binding.endpoint || row["remote-address"]?.startsWith(binding.endpoint + ":")))
|
||||
items[index].connection = { observedAt, state: fresh || established ? "connected" : "waiting", ...(peer && { rx: peer.rx, tx: peer.tx }) }
|
||||
}
|
||||
} catch {
|
||||
for (const item of items) if (item.enabled) item.connection = { observedAt, state: "unknown" }
|
||||
}
|
||||
return items
|
||||
}))
|
||||
return { revision, items: sites.flat() }
|
||||
}
|
||||
|
||||
export async function observeIxLinuxPath(segment: IxSegment, serverId: number, name: string): Promise<IxLinuxPath> {
|
||||
if (!segment.appliedRevision) throw new IxConflict("Сначала примените конфигурацию площадки")
|
||||
const applied = await readIxRevision(segment.id, segment.appliedRevision)
|
||||
const binding = applied.sites.find(site => site.serverId === serverId)?.interfaces.find(item => item.name === name && item.linux)
|
||||
if (!binding?.linux) throw new IxConflict("Управляемый клиент не найден", 404)
|
||||
const client = await requiredIxNode(serverId)
|
||||
const namespace = ixNamespace(segment.id)
|
||||
const table = binding.linux.exit ? ixClientRoutingTable(namespace, name) : namespace
|
||||
const fields = ["dst-address", "routing-table", "gateway", "immediate-gw", "active", "blackhole"]
|
||||
const read = async (table: string) => {
|
||||
const result = await client.get<unknown>("/routing/route?" + new URLSearchParams({ ".proplist": fields.join(","), "routing-table": table }))
|
||||
if (!Array.isArray(result) || result.length > 10000) throw new IxConflict("Таблица маршрутов клиента недоступна")
|
||||
return result.filter(row => row && row["routing-table"] === table)
|
||||
}
|
||||
const [clientRoutes, segmentRoutes] = await Promise.all([read(table), table !== namespace ? read(namespace) : []])
|
||||
const routes = clientRoutes.concat(segmentRoutes).filter(row => typeof row["dst-address"] === "string" &&
|
||||
(row["routing-table"] === table && !!binding.linux?.exit || binding.linux?.destinations.some(prefix => inIxNetwork(prefix, row["dst-address"]))))
|
||||
return { table, observedAt: new Date().toISOString(), policy: binding.linux.exit ?? null, routes: routes.slice(0, 100).map(row => ({
|
||||
prefix: row["dst-address"], gateway: isTrue(row.blackhole) || row.blackhole === "" ? "blackhole" : row.gateway ?? "",
|
||||
immediateGateway: row["immediate-gw"] ?? null, active: isTrue(row.active),
|
||||
})) }
|
||||
}
|
||||
|
||||
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false): Promise<IxLinuxAccess> {
|
||||
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
|
||||
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
|
||||
const site = configuration.sites.find(site => site.serverId === serverId)
|
||||
const binding = site?.interfaces.find(entry => entry.name === name)
|
||||
const server = await getServerRowById(serverId)
|
||||
if (!site || !binding || !server?.enabled || server.type !== "ix-node") throw new IxConflict("Подключение IX не найдено", 404)
|
||||
if (binding.peerServerId || binding.linux?.enabled === false) throw new IxConflict("Клиентское подключение отключено или недоступно")
|
||||
if (includeCredential === "wireguard" && binding.kind !== "wireguard") throw new IxConflict("Для скачивания выберите клиента WireGuard", 404)
|
||||
const peer = site.neighbors.find(entry => entry.binding === name && entry.type !== "public-feed")
|
||||
const clientInfo = {
|
||||
revision: segment.appliedRevision,
|
||||
...(peer ? { bgp: { localAs: peer.remoteAs, remoteAs: site.autonomousSystem, neighbor: peer.localAddress, advertisedPrefixes: peer.prefixes } } : {}),
|
||||
}
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
if (binding.kind === "gre-ipsec") {
|
||||
const [interfaces, policies] = await Promise.all([
|
||||
readRows(client, "/interface/gre", [...greColumns, "disabled"]),
|
||||
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns),
|
||||
])
|
||||
if (isTrue(verifyGreBinding(binding, interfaces, policies).disabled)) throw new IxConflict("Интерфейс GRE/IPsec отключён")
|
||||
if (includeCredential && !binding.provisionGre) throw new IxConflict("IX не выдавал этот IKEv2 PSK", 404)
|
||||
const credential = includeCredential && binding.provisionGre
|
||||
? (await privateFingerprinterExisting("ix-gre-client-credential-v1"))(segment.id + ":" + serverId + ":ix-credential:" + binding.provisionGre.credentialId)
|
||||
: undefined
|
||||
if (credential) {
|
||||
const identities = await readRows(client, "/ip/ipsec/identity", ["comment", "secret", "disabled"])
|
||||
const identity = identities.find(row => row.comment === ixNamespace(segment.id) + ":gre-identity-" + binding.name)
|
||||
if (!identity?.secret || isTrue(identity.disabled) || !constantEqual(identity.secret, credential)) {
|
||||
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
|
||||
}
|
||||
}
|
||||
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential) }
|
||||
}
|
||||
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
|
||||
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
|
||||
const iface = wireguard.find(row => row.name === binding.name && row.comment?.startsWith(ixNamespace(segment.id) + ":wg-") && !isTrue(row.disabled))
|
||||
const peers = await readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "comment", "disabled"])
|
||||
if (!peers.some(row => row.interface === name && row["public-key"] === binding.provisionWireguard?.peerPublicKey &&
|
||||
row.comment?.startsWith(ixNamespace(segment.id) + ":wg-peer-") && !isTrue(row.disabled))) {
|
||||
throw new IxConflict("Пир WireGuard из применённой ревизии отсутствует или отключён")
|
||||
}
|
||||
const routes = binding.linux ? [...binding.linux.destinations,
|
||||
...(binding.linux.exit ? [isIP(binding.provisionWireguard!.peerAddress) === 4 ? "0.0.0.0/0" : "::/0"] : [])]
|
||||
: configuration.sites.flatMap(entry => entry.interfaces
|
||||
.filter(connection => connection !== binding && connection.kind !== "uplink").flatMap(connection => connection.prefixes))
|
||||
let privateKey: string | undefined
|
||||
if (includeCredential) {
|
||||
const wg = binding.provisionWireguard
|
||||
if (!binding.linux || !wg?.credentialId) throw new IxConflict("Этот клиент использует собственный ключ WireGuard", 404)
|
||||
const keys = await ixLinuxWireguardKeys(segment.id, serverId, name, wg.credentialId)
|
||||
if (Number(iface?.["listen-port"]) !== wg.listenPort || !constantEqual(keys.publicKey, wg.peerPublicKey) ||
|
||||
(await readIxSegment(segment.id))?.appliedRevision !== segment.appliedRevision) {
|
||||
throw new IxConflict("Действующие параметры WireGuard не совпали с применённой ревизией. Выполните сверку")
|
||||
}
|
||||
privateKey = keys.privateKey
|
||||
}
|
||||
return {
|
||||
...clientInfo,
|
||||
kind: "wireguard",
|
||||
filename: ixLinuxInterfaceName("ixw", serverId, binding) + ".conf",
|
||||
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey),
|
||||
}
|
||||
}
|
||||
|
||||
async function applyNativeTasks(native: IxNativeChange, authorize: () => Promise<void>) {
|
||||
for (const task of native.tasks) {
|
||||
await authorize()
|
||||
const server = await getServerRowById(task.serverId)
|
||||
if (!server?.enabled || fingerprint(server) !== native.before.find(device => device.serverId === task.serverId)?.source) {
|
||||
throw new IxConflict("Изменился источник конфигурации IX")
|
||||
}
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const nativePath = task.rosId ? task.path + "/" + encodeURIComponent(task.rosId) : task.path
|
||||
if (task.before) {
|
||||
const observed = (await readRows(client, task.path, Object.keys(task.before))).find(row => row[".id"] === task.rosId)
|
||||
if (!observed || !matches(observed, task.before)) throw new IxConflict("Объект IX изменился перед записью")
|
||||
} else if (task.fields && (await readRows(client, task.path, [".id", "comment", "name"])).some(row =>
|
||||
task.fields?.comment && row.comment === task.fields.comment || task.fields?.name && row.name === task.fields.name)) {
|
||||
throw new IxConflict("Объект IX был создан после подготовки плана")
|
||||
}
|
||||
if (!task.fields) {
|
||||
await client.delete(nativePath, undefined, authorize)
|
||||
if ((await readRows(client, task.path, [".id"])).some(row => row[".id"] === task.rosId)) throw new IxConflict("Удаление объекта IX не подтверждено")
|
||||
continue
|
||||
}
|
||||
const result = task.rosId
|
||||
? await client.patch<NativeRow>(nativePath, task.fields, undefined, authorize)
|
||||
: await client.put<NativeRow>(nativePath, { ...task.fields, ...(task.placeBefore ? { "place-before": task.placeBefore } : {}) }, undefined, authorize)
|
||||
const returnedId = task.rosId ?? result?.[".id"]
|
||||
if (!returnedId || !routerId.test(returnedId)) throw new IxConflict("RouterOS не подтвердил ID объекта IX")
|
||||
const row = (await readRows(client, task.path, [".id", ...Object.keys(task.fields)])).find(entry => entry[".id"] === returnedId)
|
||||
if (!row || !matches(row, task.fields)) {
|
||||
const fields = row ? Object.keys(task.fields).filter(field => normalize(field, row[field]) !== normalize(field, task.fields![field])) : []
|
||||
throw new IxConflict("Перечитанный объект IX не совпал с планом · " + task.path + (fields.length ? " · " + fields.join(", ") : ""))
|
||||
}
|
||||
const vrfName = task.path === "/ip/vrf" ? task.fields.name : undefined
|
||||
if (vrfName) {
|
||||
const deadline = Date.now() + 3000
|
||||
while (!(await readRows(client, "/interface", ["name"])).some(entry => entry.name === vrfName)) {
|
||||
if (Date.now() >= deadline) throw new IxConflict("RouterOS не создал интерфейс VRF IX")
|
||||
await delay(100)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeIxSegment(id: string, revision: number, expectedDigest: string, actorId: string,
|
||||
authorize = assertVerifiedConfigurationAccess) {
|
||||
return withApplicationMutationLock(async () => {
|
||||
await authorize()
|
||||
const segment = await readIxSegment(id)
|
||||
assertIxRevision(segment, revision)
|
||||
const applied = segment?.appliedRevision ? await readIxRevision(id, segment.appliedRevision) : null
|
||||
return withConfigMutationLock(applied ? ixDeviceIds(applied) : [], async () => {
|
||||
const native = await prepareNative(id, null, applied)
|
||||
if (nativePlanDigest(native) !== expectedDigest) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
|
||||
await applyNativeTasks(native, authorize)
|
||||
await authorize()
|
||||
if (applied && (await prepareNative(id, null, applied)).tasks.length) {
|
||||
throw new IxConflict("Удаление объектов IX не подтверждено")
|
||||
}
|
||||
await authorize()
|
||||
await archiveIxSegment(id, revision, actorId)
|
||||
return { segmentId: id, revision, configurationVerified: true, removedObjects: native.tasks.length }
|
||||
})
|
||||
}, { waitMs: 30_000 })
|
||||
}
|
||||
|
||||
export async function applyIxChange(id: string, change: IxChange, expected: { revision: number; devices: string }, actorId: string,
|
||||
authorize = assertVerifiedConfigurationAccess, web?: { resume: boolean }) {
|
||||
return withApplicationMutationLock(async () => withConfigMutationLock(await ixTarget(change), async () => {
|
||||
await authorize()
|
||||
const current = await readIxSegment(id)
|
||||
assertIxRevision(current, expected.revision)
|
||||
await assertIxName(id, change.configuration.name)
|
||||
await assertIxSites(change.configuration)
|
||||
await assertIxRouterIds(id, change.configuration)
|
||||
const applied = current?.appliedRevision ? await readIxRevision(id, current.appliedRevision) : null
|
||||
const native = await prepareNative(id, change.configuration, applied, web?.resume)
|
||||
if (web?.resume) await assertIxResume(id, change.revision, native)
|
||||
if (nativePlanDigest(native) !== expected.devices) throw new IxConflict("Конфигурация IX изменилась после предпросмотра")
|
||||
if (web) {
|
||||
await authorize()
|
||||
await audit(pool, actorId, "ix.web.apply_started", null, { segmentId: id, revision: change.revision,
|
||||
sources: native.before.map(device => [device.serverId, device.source]) })
|
||||
}
|
||||
await applyNativeTasks(native, authorize)
|
||||
await authorize()
|
||||
for (const device of native.before) {
|
||||
const server = await getServerRowById(device.serverId)
|
||||
if (!server || fingerprint(server) !== device.source) throw new IxConflict("Источник IX изменился во время проверки")
|
||||
const desired = native.objects.filter(object => object.serverId === device.serverId)
|
||||
const after = await readDevice(server, desired)
|
||||
verifyEgressMembers(after, id, desired)
|
||||
if (rowsFor(after, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) throw new IxConflict("Нарушена изоляция bridge отбрасывания IX")
|
||||
const mismatch = desired.find(object => {
|
||||
const row = managedRow(after, object)
|
||||
return !row || isTrue(row.invalid) || !matches(row, object.fields)
|
||||
})
|
||||
if (mismatch) throw new IxConflict("Итоговая конфигурация IX не совпала с планом · узел " + device.serverId + " · " +
|
||||
mismatch.path + " · " + (mismatch.fields.comment ?? mismatch.fields.name))
|
||||
}
|
||||
await authorize()
|
||||
const segment = await writeIxRevision(id, expected.revision, change.configuration, actorId, true)
|
||||
return { segmentId: segment.id, revision: segment.revision, configurationVerified: true, forwardingVerified: false, changedObjects: native.tasks.length }
|
||||
}), { waitMs: 30_000 })
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { ixSegmentConfigurationSchema, type IxConfiguration } from "@mmapp/contracts/internet-exchange"
|
||||
import { compileIxConfiguration, ixClientRoutingTable, ixDiscardInterface, ixEgressList, ixNamespace } from "./internet-exchange-plan.js"
|
||||
|
||||
const id = "aaaaaaaa-1111-4222-8333-123456789abc"
|
||||
const table = ixNamespace(id)
|
||||
const fixture = (): IxConfiguration => ixSegmentConfigurationSchema.parse({
|
||||
name: "compute",
|
||||
sites: [{
|
||||
serverId: 17, autonomousSystem: 64512, routerId: "192.0.2.17",
|
||||
interfaces: [{ name: "wg-eu", kind: "wireguard" }, { name: "wg-arn", kind: "wireguard", peerServerId: 1 },
|
||||
{ name: "uplink", kind: "uplink", natIpv4: true }, { name: "wg-feed", kind: "wireguard" }],
|
||||
groups: [
|
||||
{ id: "eu", gateway: "198.18.0.1", primary: { interface: "wg-eu", nextHop: "10.0.1.2", probe: "192.0.2.101" },
|
||||
backup: { interface: "wg-arn", nextHop: "10.0.2.2", probe: "192.0.2.102" } },
|
||||
{ id: "exit", gateway: "198.18.0.2", primary: { interface: "uplink", nextHop: "10.0.3.2", probe: "192.0.2.103" } },
|
||||
],
|
||||
exits: ["exit"],
|
||||
neighbors: [{ id: "evo", type: "public-feed", binding: "wg-feed", address: "10.0.4.2", localAddress: "10.0.4.1", remoteAs: 64513,
|
||||
rules: [{ community: "65000:120", group: "eu" }] }],
|
||||
}],
|
||||
})
|
||||
|
||||
test("managed clients get their own return path and fail closed if both exit probes are lost", () => {
|
||||
const value = fixture(), site = value.sites[0]
|
||||
site.groups.push({ id: "direct", gateway: "198.18.0.10", onFailure: "block",
|
||||
primary: { interface: "ether1", nextHop: "192.0.2.1", probe: "203.0.113.101", viaMain: true },
|
||||
backup: { interface: "ether2", nextHop: "192.0.2.2", probe: "203.0.113.102", viaMain: true } })
|
||||
site.interfaces.push({ name: "linux-wg", kind: "wireguard", prefixes: [],
|
||||
linux: { name: "vps", enabled: true, exit: "direct", destinations: ["10.80.0.0/16"] },
|
||||
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
|
||||
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
|
||||
const objects = compileIxConfiguration(id, value)
|
||||
const clientTable = ixClientRoutingTable(table, "linux-wg")
|
||||
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
|
||||
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
|
||||
assert.equal(defaults.at(-1)?.fields.blackhole, "yes")
|
||||
assert.ok(objects.some(object => object.path === "/ip/firewall/raw" && object.fields["in-interface"] === "linux-wg" &&
|
||||
object.fields["src-address-list"] === "!" + clientTable + "-src"))
|
||||
assert.ok(objects.some(object => object.fields["routing-table"] === "main" &&
|
||||
object.fields["dst-address"] === "10.254.1.2/32" && object.fields.gateway === "10.254.1.2%linux-wg@" + table))
|
||||
assert.ok(objects.some(object => object.fields["routing-table"] === table &&
|
||||
object.fields["dst-address"] === "10.80.0.0/16" && object.fields.blackhole === "yes"))
|
||||
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
|
||||
})
|
||||
|
||||
test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => {
|
||||
const value = fixture(), site = value.sites[0]
|
||||
site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99,
|
||||
provisionTransit: { localEndpoint: "192.0.2.44", remoteEndpoint: "192.0.2.45", localAddress: "10.253.0.1/30", remoteAddress: "10.253.0.2",
|
||||
localPort: 52000, remotePort: 52001, credentialId: id, remoteWan: { interface: "ether1", nextHop: "192.0.2.1", probe: "192.0.2.1", viaMain: true } } })
|
||||
site.groups.push({ id: "other-ix", gateway: "198.18.0.99", onFailure: "block",
|
||||
primary: { interface: "it-abc", nextHop: "10.253.0.2", probe: "10.253.0.2" } })
|
||||
site.interfaces.push({ name: "linux-gre", kind: "gre-ipsec", endpoint: "192.0.2.90", localEndpoint: "192.0.2.44", prefixes: ["10.73.0.0/16"],
|
||||
linux: { name: "server", enabled: true, exit: "other-ix", destinations: [] },
|
||||
provisionGre: { localAddress: "10.254.2.1/30", peerAddress: "10.254.2.2", credentialId: id } })
|
||||
const objects = compileIxConfiguration(id, value)
|
||||
assert.ok(objects.some(object => object.serverId === 99 && object.path === "/ip/firewall/nat" &&
|
||||
object.fields["out-interface"] === "ether1" && object.fields["src-address-list"]))
|
||||
assert.ok(objects.some(object => object.serverId === 99 && object.fields["routing-table"] === "main" && object.fields["dst-address"] === "10.73.0.0/16"))
|
||||
assert.ok(objects.some(object => object.serverId === 17 && object.path === "/ip/ipsec/identity" && object.fields.secret === "ix-credential:" + id))
|
||||
assert.ok(objects.some(object => object.serverId === 17 && object.fields["ipsec-policy"] === "in,none" && object.fields.action === "drop"))
|
||||
})
|
||||
|
||||
test("forwarding permits the VRF to exit through its own members before isolation drops", () => {
|
||||
const objects = compileIxConfiguration(id, fixture())
|
||||
const egress = ixEgressList(id)
|
||||
const members = objects.filter(object => object.path === "/interface/list/member")
|
||||
assert.deepEqual(members.map(object => [object.fields.list, object.fields.interface]),
|
||||
["wg-eu", "wg-arn", "uplink", "wg-feed"].map(member => [egress, member]))
|
||||
for (const [family, path] of [[4, "/ip/firewall/filter"], [6, "/ipv6/firewall/filter"]] as const) {
|
||||
const forward = objects.filter(object => object.path === path && object.fields.chain === "forward")
|
||||
const boundary = forward.findIndex(object => object.fields.comment === table + ":deny-outside-" + family)
|
||||
assert.deepEqual(forward.slice(0, boundary).map(object => [object.fields["in-interface"], object.fields["out-interface"] ?? object.fields["out-interface-list"]]),
|
||||
[[table, table], [table, egress]])
|
||||
assert.equal(forward[boundary - 1].fields["out-interface-list"], egress)
|
||||
assert.equal(forward[boundary].fields.action, "drop")
|
||||
assert.equal(forward.at(-1)?.fields.action, "drop")
|
||||
assert.equal(forward.at(-1)?.fields["out-interface-list"], egress)
|
||||
}
|
||||
})
|
||||
|
||||
test("a BGP community uses a stable recursive next hop with independent probes and a final discard", () => {
|
||||
const objects = compileIxConfiguration(id, fixture())
|
||||
const policy = objects.find(object => object.fields.comment.endsWith(":bgp-in-evo"))!.fields.rule
|
||||
assert.match(policy, /if \(dst == 0\.0\.0\.0\/0\) \{ reject; \}/)
|
||||
assert.match(policy, /bgp-communities includes 65000:120\) \{ set gw 198\.18\.0\.1; set scope-target 23; accept;/)
|
||||
assert.match(policy, /reject;$/)
|
||||
const group = objects.filter(object => object.fields["dst-address"] === "198.18.0.1/32" && object.fields["routing-table"] === table)
|
||||
assert.deepEqual(group.map(object => object.fields.distance), ["10", "11", "254"])
|
||||
assert.deepEqual(group.slice(0, 2).map(object => object.fields.gateway), ["192.0.2.101@" + table, "192.0.2.102@" + table])
|
||||
assert.ok(group[2].fields.gateway.endsWith("%" + ixDiscardInterface(id) + "@" + table))
|
||||
assert.ok(!ixDiscardInterface(id).startsWith(table))
|
||||
assert.ok(objects.some(object => object.fields["src-port"] === "179" && object.fields["connection-state"] === "established" &&
|
||||
object.fields["src-address"] === "10.0.4.2/32" && object.fields["in-interface"] === table))
|
||||
assert.deepEqual(objects.filter(object => object.fields["routing-table"] === "main").map(object => object.fields), [{
|
||||
"routing-table": "main", "dst-address": "198.18.0.1/32", gateway: "198.18.0.1@" + table, scope: "22", "target-scope": "21", comment: table + ":bgp-resolve-eu",
|
||||
}])
|
||||
assert.ok(objects.some(object => object.path === "/ip/firewall/nat" && object.fields["out-interface"] === "uplink"))
|
||||
})
|
||||
|
||||
test("ordinary exit is used for the prefix only when its group explicitly enables fallback", () => {
|
||||
const value = fixture()
|
||||
value.sites[0].groups[0].onFailure = "segment-exit"
|
||||
const group = compileIxConfiguration(id, value).filter(object => object.fields["dst-address"] === "198.18.0.1/32" && object.fields["routing-table"] === table)
|
||||
assert.equal(group.length, 4)
|
||||
assert.equal(group[2].fields.gateway, "192.0.2.103@" + table)
|
||||
assert.equal(group[3].fields.distance, "254")
|
||||
})
|
||||
|
||||
test("a BGP resolver cannot claim an ordinary address in main", () => {
|
||||
const value = fixture()
|
||||
value.sites[0].groups[0].gateway = "8.8.8.8"
|
||||
assert.throws(() => compileIxConfiguration(id, value), /служебный next hop BGP/)
|
||||
})
|
||||
|
||||
test("a probe cannot silently select another interface or recursively follow its own group", () => {
|
||||
const value = fixture()
|
||||
value.sites[0].groups[0].backup!.probe = value.sites[0].groups[0].primary.probe
|
||||
assert.throws(() => compileIxConfiguration(id, value), /закреплён за несколькими путями/)
|
||||
value.sites[0].groups[0].backup!.probe = value.sites[0].groups[0].gateway
|
||||
assert.throws(() => compileIxConfiguration(id, value), /не может быть целью пробы/)
|
||||
})
|
||||
|
||||
test("private announcements are restricted to their binding and retain a discard route on withdrawal", () => {
|
||||
const value = fixture(), site = value.sites[0]
|
||||
site.interfaces[0].prefixes = ["10.70.0.0/16"]
|
||||
const peer = site.neighbors[0]
|
||||
peer.type = "member"
|
||||
peer.rules = []
|
||||
peer.binding = "wg-eu"
|
||||
peer.group = "eu"
|
||||
peer.prefixes = ["10.70.0.0/16"]
|
||||
assert.ok(compileIxConfiguration(id, value).some(object => object.fields["dst-address"] === "10.70.0.0/16" && object.fields.blackhole === "yes"))
|
||||
peer.prefixes = ["10.71.0.0/16"]
|
||||
assert.throws(() => compileIxConfiguration(id, value), /только диапазоны подключения/)
|
||||
})
|
||||
|
||||
test("GRE/IPsec binds its plaintext drops to the two fixed outer endpoints", () => {
|
||||
const value = fixture()
|
||||
const binding = value.sites[0].interfaces[0]
|
||||
binding.kind = "gre-ipsec"
|
||||
assert.throws(() => compileIxConfiguration(id, value), /фиксированных внешних/)
|
||||
binding.localEndpoint = "192.0.2.44"
|
||||
binding.endpoint = "192.0.2.45"
|
||||
const drop = compileIxConfiguration(id, value).find(object => object.fields["ipsec-policy"] === "in,none")!
|
||||
assert.deepEqual([drop.fields["src-address"], drop.fields["dst-address"]], ["192.0.2.45/32", "192.0.2.44/32"])
|
||||
})
|
||||
@@ -0,0 +1,433 @@
|
||||
import { BlockList, isIP } from "node:net"
|
||||
import { createHash } from "node:crypto"
|
||||
import type { IxConfiguration, IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
import { compileIxTransit, ixTransitSourceObjects } from "./internet-exchange-transit.js"
|
||||
|
||||
export class IxConflict extends Error {
|
||||
constructor(message: string, readonly statusCode = 409) { super(message) }
|
||||
}
|
||||
|
||||
const families = [4, 6] as const
|
||||
type Family = typeof families[number]
|
||||
const familyOf = (address: string) => isIP(address.split("/")[0])
|
||||
const host = (address: string) => canonicalBgpPolicyPrefix(address + (isIP(address) === 4 ? "/32" : "/128"))
|
||||
const routePath = (family: number) => family === 4 ? "/ip/route" : "/ipv6/route"
|
||||
const familyName = (family: number) => family === 4 ? "ip" : "ipv6"
|
||||
const prefixIdentifier = (value: string) => createHash("sha256").update(value).digest("hex").slice(0, 12)
|
||||
const sink = {
|
||||
4: { local: "169.254.255.249/30", neighbor: "169.254.255.250" },
|
||||
6: { local: "fd00:ffff:ffff::1/126", neighbor: "fd00:ffff:ffff::2" },
|
||||
}
|
||||
const defaultRoute = { 4: "0.0.0.0/0", 6: "::/0" }
|
||||
const bgpGatewayRange = { 4: "198.18.0.0/15", 6: "fd00:198:18::/48" }
|
||||
const forbiddenPublic = {
|
||||
4: ["0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "198.18.0.0/15", "224.0.0.0/3"],
|
||||
6: ["::/96", "::ffff:0:0/96", "fc00::/7", "fe80::/10", "ff00::/8"],
|
||||
}
|
||||
|
||||
export function ixNamespace(id: string) { return "ix-" + id.replace(/-/g, "").slice(0, 18) }
|
||||
// RouterOS accepts unambiguous prefixes for interface names before the VRF interface appears.
|
||||
export function ixDiscardInterface(id: string) { return "ix-drop-" + ixNamespace(id).slice(3) }
|
||||
export function ixEgressList(id: string) { return "ix-out-" + ixNamespace(id).slice(3) }
|
||||
export function ixDeviceIds(configuration: IxConfiguration) {
|
||||
return [...new Set(configuration.sites.flatMap(site => [site.serverId, ...site.interfaces.flatMap(binding => binding.peerServerId === undefined ? [] : [binding.peerServerId])]))].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
function requireIx(condition: unknown, message: string): asserts condition {
|
||||
if (!condition) throw new IxConflict(message, 400)
|
||||
}
|
||||
|
||||
function unique(values: string[], label: string) {
|
||||
requireIx(new Set(values).size === values.length, "Повторяется " + label)
|
||||
}
|
||||
|
||||
export function inIxNetwork(cidr: string, value: string) {
|
||||
const [network, length] = cidr.split("/")
|
||||
const [candidate, candidateLength] = value.split("/")
|
||||
const family = isIP(network)
|
||||
if (family !== isIP(candidate) || (candidateLength !== undefined && Number(candidateLength) < Number(length))) return false
|
||||
const familyName = family === 4 ? "ipv4" : "ipv6"
|
||||
const block = new BlockList()
|
||||
block.addSubnet(network, Number(length), familyName)
|
||||
return block.check(candidate, familyName)
|
||||
}
|
||||
|
||||
const inNetwork = inIxNetwork
|
||||
|
||||
function groupPaths(group: IxSite["groups"][number]) {
|
||||
return group.backup ? [group.primary, group.backup] : [group.primary]
|
||||
}
|
||||
|
||||
function checkedIxHop(path: IxSite["groups"][number]["primary"], namespace: string) {
|
||||
if (path.viaMain && path.probe === path.nextHop) {
|
||||
return { gateway: path.nextHop + "%" + path.interface + "@main", "target-scope": "10", "check-gateway": "ping" }
|
||||
}
|
||||
return { gateway: path.probe + "@" + (path.viaMain ? "main" : namespace), "target-scope": "11", "check-gateway": "ping" }
|
||||
}
|
||||
|
||||
export function ixClientRoutingTable(namespace: string, binding: string) {
|
||||
return namespace + "-p-" + createHash("sha256").update(binding).digest("hex").slice(0, 8)
|
||||
}
|
||||
|
||||
function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["interfaces"][number],
|
||||
add: (path: string, key: string, fields: Record<string, string>) => void) {
|
||||
const policy = binding.linux!
|
||||
const tunnel = (binding.provisionWireguard ?? binding.provisionGre)!
|
||||
const family = familyOf(tunnel.localAddress) as Family
|
||||
const ip = "/" + familyName(family)
|
||||
const raw = ip + "/firewall/raw"
|
||||
const filter = ip + "/firewall/filter"
|
||||
const key = "linux-" + binding.name
|
||||
const privateTable = ixClientRoutingTable(namespace, binding.name)
|
||||
const sources = privateTable + "-src"
|
||||
const permitted = privateTable + "-dst"
|
||||
const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])]
|
||||
const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])]
|
||||
const ingress = { chain: "prerouting", "in-interface": binding.name }
|
||||
const exit = site.groups.find(group => group.id === policy.exit)
|
||||
const paths = exit ? groupPaths(exit) : []
|
||||
for (const address of sourcesCidr) add(ip + "/firewall/address-list", key + "-src-" + prefixIdentifier(address), { address, list: sources })
|
||||
for (const address of destinations) add(ip + "/firewall/address-list", key + "-dst-" + prefixIdentifier(address), { address, list: permitted })
|
||||
add(raw, key + "-disabled", { ...ingress, action: "drop", disabled: String(policy.enabled) })
|
||||
add(raw, key + "-spoof", { ...ingress, "src-address-list": "!" + sources, action: "drop" })
|
||||
add(raw, key + "-destinations", { ...ingress, "dst-address-list": "!" + permitted, action: "drop", disabled: String(!!exit) })
|
||||
add("/" + familyName(family === 4 ? 6 : 4) + "/firewall/raw", key + "-other-family", { ...ingress, action: "drop" })
|
||||
if (binding.provisionWireguard) {
|
||||
const transportFamily = familyOf(binding.provisionWireguard.hubEndpoint ?? tunnel.localAddress) as Family
|
||||
add("/" + familyName(transportFamily) + "/firewall/filter", key + "-wg-listen", {
|
||||
chain: "input", protocol: "udp", "dst-port": String(binding.provisionWireguard.listenPort), action: "accept",
|
||||
...(binding.provisionWireguard.hubEndpoint && { "dst-address": host(binding.provisionWireguard.hubEndpoint) }),
|
||||
disabled: String(!policy.enabled),
|
||||
})
|
||||
}
|
||||
if (binding.provisionGre) {
|
||||
const transport = { chain: "input", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!),
|
||||
action: "accept", disabled: String(!policy.enabled) }
|
||||
add(filter, key + "-ike", { ...transport, protocol: "udp", "dst-port": "500,4500" })
|
||||
add(filter, key + "-esp", { ...transport, protocol: "ipsec-esp" })
|
||||
add(filter, key + "-encrypted-gre", { ...transport, protocol: "gre", "ipsec-policy": "in,ipsec" })
|
||||
}
|
||||
const outbound = { chain: "forward", "src-address-list": sources, action: "accept", disabled: String(!policy.enabled) }
|
||||
const inbound = { chain: "forward", "dst-address-list": sources }
|
||||
add(filter, key + "-established", { ...inbound, "connection-state": "established,related", action: "accept", disabled: String(!policy.enabled) })
|
||||
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
|
||||
action: "accept", disabled: String(!policy.enabled) })
|
||||
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
|
||||
if (!exit) return
|
||||
add("/routing/table", key + "-table", { name: privateTable, fib: "true" })
|
||||
for (const [index, path] of paths.entries()) {
|
||||
add(routePath(family), key + "-default-" + index, {
|
||||
"routing-table": privateTable, "dst-address": defaultRoute[family], ...checkedIxHop(path, namespace), distance: String(10 + index),
|
||||
})
|
||||
}
|
||||
add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
|
||||
add(ip + "/firewall/mangle", key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
|
||||
action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) })
|
||||
const mainPaths = paths.filter(path => path.viaMain)
|
||||
for (const [index, path] of mainPaths.entries()) {
|
||||
add(filter, key + "-wan-" + index, { ...outbound, "out-interface": path.interface })
|
||||
if (family === 4) add("/ip/firewall/nat", key + "-nat-" + index, { chain: "srcnat", "src-address-list": sources,
|
||||
"out-interface": path.interface, action: "masquerade", disabled: String(!policy.enabled) })
|
||||
}
|
||||
if (mainPaths.length) for (const prefix of sourcesCidr) {
|
||||
add(routePath(family), key + "-return-" + prefixIdentifier(prefix), {
|
||||
"routing-table": "main", "dst-address": prefix, gateway: tunnel.peerAddress + "%" + binding.name + "@" + namespace,
|
||||
disabled: String(!policy.enabled),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function validateSite(site: IxSite, otherId?: number) {
|
||||
unique(site.interfaces.map(entry => entry.name), "интерфейс IX")
|
||||
unique(site.groups.map(entry => entry.id), "группа шлюзов")
|
||||
unique(site.groups.map(entry => host(entry.gateway)), "служебный next hop")
|
||||
unique(site.neighbors.map(entry => entry.id), "BGP-сосед")
|
||||
unique(site.neighbors.map(entry => host(entry.address)), "адрес BGP-соседа")
|
||||
unique(site.routes.map(entry => canonicalBgpPolicyPrefix(entry.prefix)), "префикс")
|
||||
unique(site.exits, "интернет-выход")
|
||||
const bindings = new Map(site.interfaces.map(binding => [binding.name, binding]))
|
||||
const groups = new Map(site.groups.map(group => [group.id, group]))
|
||||
for (const binding of site.interfaces) {
|
||||
if (binding.kind === "gre-ipsec") {
|
||||
requireIx(binding.endpoint && binding.localEndpoint && isIP(binding.endpoint) === 4 && isIP(binding.localEndpoint) === 4 &&
|
||||
binding.endpoint !== binding.localEndpoint, "GRE/IPsec требует двух разных фиксированных внешних IPv4-адресов")
|
||||
}
|
||||
if (binding.natIpv4) requireIx(binding.kind === "uplink" && !binding.peerServerId, "NAT разрешён только на локальном uplink")
|
||||
const wireguard = binding.provisionWireguard
|
||||
if (wireguard) {
|
||||
requireIx(binding.kind === "wireguard" && inNetwork(wireguard.localAddress, wireguard.peerAddress) &&
|
||||
host(wireguard.localAddress.split("/")[0]) !== host(wireguard.peerAddress), "Неверные адреса WireGuard-подключения")
|
||||
requireIx(!wireguard.endpointPort || binding.endpoint, "Порт WireGuard требует внешнего адреса")
|
||||
requireIx(!binding.endpoint || wireguard.endpointPort, "Внешний адрес WireGuard требует порта")
|
||||
}
|
||||
const gre = binding.provisionGre
|
||||
if (gre) {
|
||||
requireIx(binding.kind === "gre-ipsec" && binding.linux && inNetwork(gre.localAddress, gre.peerAddress) &&
|
||||
host(gre.localAddress.split("/")[0]) !== host(gre.peerAddress), "Неверные адреса управляемого GRE/IPsec")
|
||||
}
|
||||
if (binding.provisionTransit) {
|
||||
const link = binding.provisionTransit
|
||||
requireIx(binding.kind === "wireguard" && binding.peerServerId && !binding.linux && !wireguard &&
|
||||
inNetwork(link.localAddress, link.remoteAddress) && link.remoteAddress !== link.localAddress.split("/")[0] &&
|
||||
link.remoteEndpoint !== link.localEndpoint && link.remoteWan.viaMain &&
|
||||
isIP(link.remoteWan.nextHop) === isIP(link.remoteAddress),
|
||||
"Неверные параметры управляемого транзита IX")
|
||||
}
|
||||
if (binding.linux) {
|
||||
const tunnel = wireguard ?? gre
|
||||
requireIx(tunnel && !binding.peerServerId, "Linux-клиенту нужен управляемый туннель")
|
||||
const family = familyOf(tunnel.localAddress)
|
||||
requireIx([...binding.linux.destinations, ...binding.prefixes].every(prefix => familyOf(prefix) === family &&
|
||||
Number(prefix.split("/")[1]) > 0), "Префиксы Linux должны совпадать с семейством туннеля и не могут быть default")
|
||||
const group = binding.linux.exit && groups.get(binding.linux.exit)
|
||||
requireIx(!binding.linux.exit || group && familyOf(group.gateway) === family && group.onFailure === "block",
|
||||
"Для Linux нужен выход того же семейства без неявного переключения на общий шлюз")
|
||||
requireIx(!group || groupPaths(group).every(path => path.interface !== binding.name), "Клиентский туннель не может быть своим выходом")
|
||||
}
|
||||
}
|
||||
const probes = new Map<string, string>()
|
||||
const ownedNetworks = site.interfaces.flatMap(binding => [
|
||||
...binding.prefixes, ...(binding.provisionTransit ? [binding.provisionTransit.localAddress] : []),
|
||||
...(binding.linux ? [host((binding.provisionWireguard ?? binding.provisionGre)!.peerAddress),
|
||||
host((binding.provisionWireguard ?? binding.provisionGre)!.localAddress.split("/")[0])] : []),
|
||||
].map(prefix => ({ binding, prefix })))
|
||||
for (const [index, first] of ownedNetworks.entries()) {
|
||||
requireIx(Number(first.prefix.split("/")[1]) > 0, "Префикс подключения не может быть default route")
|
||||
for (const second of ownedNetworks.slice(0, index)) {
|
||||
if (first.binding === second.binding) continue
|
||||
requireIx(!inNetwork(first.prefix, second.prefix) && !inNetwork(second.prefix, first.prefix), "Префиксы разных подключений пересекаются")
|
||||
}
|
||||
}
|
||||
for (const group of site.groups) {
|
||||
const family = familyOf(group.gateway) as Family
|
||||
requireIx(!ownedNetworks.some(entry => inNetwork(entry.prefix, group.gateway)), "Служебный next hop пересекает сеть подключения")
|
||||
requireIx(!inNetwork(sink[family].local, group.gateway), "Служебный next hop пересекает сеть отбрасывания")
|
||||
if (group.backup) requireIx(group.primary.interface !== group.backup.interface, "Резерв требует другого интерфейса")
|
||||
for (const candidate of groupPaths(group)) {
|
||||
requireIx(candidate.viaMain ? !bindings.has(candidate.interface) : bindings.has(candidate.interface), "Шлюз использует интерфейс вне своей таблицы")
|
||||
requireIx([candidate.nextHop, candidate.probe].every(address => isIP(address) === family), "Семейства адресов шлюза не совпадают")
|
||||
requireIx(!site.groups.some(entry => host(entry.gateway) === host(candidate.probe) || host(entry.gateway) === host(candidate.nextHop)), "Рекурсивный шлюз не может быть целью пробы или соседом")
|
||||
requireIx(!inNetwork(sink[family].local, candidate.probe) && !inNetwork(sink[family].local, candidate.nextHop), "Путь использует служебную сеть отбрасывания")
|
||||
const probe = host(candidate.probe), path = host(candidate.nextHop) + "%" + candidate.interface
|
||||
requireIx(!probes.has(probe) || probes.get(probe) === path, "Контрольный адрес закреплён за несколькими путями")
|
||||
probes.set(probe, path)
|
||||
}
|
||||
}
|
||||
const exits = site.exits.map(id => groups.get(id))
|
||||
requireIx(exits.every(Boolean), "Неизвестная группа обычного выхода")
|
||||
for (const exit of exits) {
|
||||
requireIx(exit!.onFailure === "block", "Обычный выход не может ссылаться сам на себя")
|
||||
}
|
||||
for (const group of site.groups) {
|
||||
if (group.onFailure === "segment-exit") requireIx(exits.some(exit => familyOf(exit!.gateway) === familyOf(group.gateway)), "Для fallback нужен выход того же семейства")
|
||||
}
|
||||
for (const route of site.routes) {
|
||||
const group = groups.get(route.group)
|
||||
requireIx(group && familyOf(route.prefix) === familyOf(group.gateway), "Маршрут использует неизвестную группу или другое семейство")
|
||||
requireIx(Number(route.prefix.split("/")[1]) > 0, "Default route задаётся в разделе выходов")
|
||||
requireIx(!site.groups.some(entry => canonicalBgpPolicyPrefix(route.prefix) === host(entry.gateway)) && !probes.has(canonicalBgpPolicyPrefix(route.prefix)), "Префикс совпадает со служебным маршрутом")
|
||||
}
|
||||
for (const network of site.discardNetworks) {
|
||||
requireIx(Number(network.split("/")[1]) > 0, "Маршрут защиты не может быть default route")
|
||||
}
|
||||
for (const peer of site.neighbors) {
|
||||
const binding = bindings.get(peer.binding)
|
||||
const family = familyOf(peer.address)
|
||||
requireIx(binding && familyOf(peer.localAddress) === family, "BGP-сосед использует необъявленный интерфейс или другое семейство")
|
||||
requireIx(peer.remoteAs !== site.autonomousSystem, "IX принимает только явно настроенных eBGP-соседей")
|
||||
unique(peer.rules.map(rule => rule.community), "community у BGP-соседа")
|
||||
const groupIds = peer.type === "public-feed" ? peer.rules.map(rule => rule.group) : [peer.group]
|
||||
requireIx(groupIds.length && groupIds.every(id => id && groups.has(id) && familyOf(groups.get(id)!.gateway) === family), "У BGP-соседа нет подходящей группы шлюзов")
|
||||
requireIx(peer.prefixes.concat(peer.exportPrefixes).every(prefix => familyOf(prefix) === family && Number(prefix.split("/")[1]) > 0), "Неверный диапазон BGP-соседа")
|
||||
if (peer.type === "public-feed") {
|
||||
requireIx(!peer.group && !peer.exportPrefixes.length, "Публичный фид не принимает экспорт IX")
|
||||
continue
|
||||
}
|
||||
requireIx(peer.prefixes.length && !peer.rules.length, "Частный сосед должен объявлять согласованный диапазон")
|
||||
requireIx(groups.get(peer.group!)?.onFailure === "block", "Частный префикс нельзя отправлять в обычный выход")
|
||||
requireIx(peer.prefixes.every(prefix => binding.prefixes.some(allowed => inNetwork(allowed, prefix))), "BGP импортирует только диапазоны подключения")
|
||||
if (peer.type === "exchange") requireIx(otherId && binding.peerServerId === otherId && binding.kind === "wireguard", "Межплощадочный BGP требует WireGuard до второй площадки")
|
||||
requireIx(peer.exportPrefixes.every(prefix => ownedNetworks.some(entry => entry.binding !== binding && inNetwork(entry.prefix, prefix))), "Экспорт разрешён только из согласованных сетей других подключений")
|
||||
}
|
||||
}
|
||||
|
||||
export function compileIxConfiguration(id: string, configuration: IxConfiguration): IxRouterObject[] {
|
||||
const namespace = ixNamespace(id)
|
||||
const result: IxRouterObject[] = []
|
||||
unique(configuration.sites.map(site => String(site.serverId)), "площадка IX")
|
||||
const remoteExit = (site: IxSite, remoteId: number) => site.groups.filter(group => site.exits.includes(group.id))
|
||||
.flatMap(groupPaths).some(path => site.interfaces.some(binding => binding.name === path.interface && binding.peerServerId === remoteId))
|
||||
if (configuration.sites.length === 2) {
|
||||
const [a, b] = configuration.sites
|
||||
requireIx(!remoteExit(a, b.serverId) || !remoteExit(b, a.serverId), "Основные и резервные выходы образуют цикл между IX")
|
||||
}
|
||||
for (const site of configuration.sites) {
|
||||
const otherId = configuration.sites.find(candidate => candidate.serverId !== site.serverId)?.serverId
|
||||
validateSite(site, otherId)
|
||||
const add = (path: string, key: string, fields: Record<string, string>) => {
|
||||
const nameOnly = ["/ip/ipsec/profile", "/ip/ipsec/proposal", "/ip/ipsec/peer", "/routing/table"].includes(path)
|
||||
result.push({ serverId: site.serverId, path, fields: nameOnly ? fields : { ...fields, comment: namespace + ":" + key } })
|
||||
}
|
||||
const protectGre = (binding: IxSite["interfaces"][number], key: string) => {
|
||||
add("/ip/firewall/filter", "gre-in-" + key, { chain: "input", protocol: "gre", "src-address": host(binding.endpoint!), "dst-address": host(binding.localEndpoint!), "ipsec-policy": "in,none", action: "drop" })
|
||||
add("/ip/firewall/filter", "gre-out-" + key, { chain: "output", protocol: "gre", "src-address": host(binding.localEndpoint!), "dst-address": host(binding.endpoint!), "ipsec-policy": "out,none", action: "drop" })
|
||||
}
|
||||
const dropInterface = ixDiscardInterface(id)
|
||||
for (const [index, binding] of site.interfaces.entries()) {
|
||||
const wireguard = binding.provisionWireguard
|
||||
const key = binding.linux ? binding.name : String(index)
|
||||
if (binding.provisionTransit) compileIxTransit(namespace, site, binding, object => result.push(object))
|
||||
if (wireguard) add("/interface/wireguard", "wg-" + key, { name: binding.name, "listen-port": String(wireguard.listenPort),
|
||||
...(binding.linux && { disabled: String(!binding.linux.enabled) }) })
|
||||
const gre = binding.provisionGre
|
||||
if (gre) {
|
||||
const transport = namespace + "-" + key
|
||||
protectGre(binding, key)
|
||||
add("/ip/ipsec/profile", key, { name: transport, "enc-algorithm": "aes-256", "hash-algorithm": "sha256", "dh-group": "modp2048" })
|
||||
add("/ip/ipsec/proposal", key, { name: transport, "enc-algorithms": "aes-256-cbc", "auth-algorithms": "sha256", "pfs-group": "modp2048" })
|
||||
add("/ip/ipsec/peer", key, { name: transport, address: host(binding.endpoint!), "local-address": binding.localEndpoint!,
|
||||
profile: transport, "exchange-mode": "ike2", passive: "true" })
|
||||
add("/ip/ipsec/identity", "gre-identity-" + key, { peer: transport, "auth-method": "pre-shared-key",
|
||||
secret: "ix-credential:" + gre.credentialId, disabled: String(!binding.linux!.enabled) })
|
||||
add("/ip/ipsec/policy", "gre-policy-" + key, { peer: transport, "src-address": host(binding.localEndpoint!),
|
||||
"dst-address": host(binding.endpoint!), protocol: "gre", action: "encrypt", level: "require", tunnel: "false", proposal: transport })
|
||||
add("/interface/gre", "gre-" + key, { name: binding.name, "local-address": binding.localEndpoint!,
|
||||
"remote-address": binding.endpoint!, "allow-fast-path": "false", disabled: String(!binding.linux!.enabled) })
|
||||
}
|
||||
}
|
||||
add("/interface/bridge", "drop-bridge", { name: dropInterface, "protocol-mode": "none" })
|
||||
add("/ip/vrf", "vrf", { name: namespace, interfaces: [dropInterface, ...site.interfaces.map(binding => binding.name)].join(",") })
|
||||
for (const binding of site.interfaces.filter(binding => binding.linux)) {
|
||||
compileLinuxPolicy(namespace, site, binding, add)
|
||||
}
|
||||
if (site.interfaces.length) {
|
||||
const egress = ixEgressList(id)
|
||||
add("/interface/list", "egress-list", { name: egress })
|
||||
for (const binding of site.interfaces) {
|
||||
add("/interface/list/member", "egress-member-" + binding.name, { list: egress, interface: binding.name })
|
||||
}
|
||||
for (const family of families) {
|
||||
const filter = family === 4 ? "/ip/firewall/filter" : "/ipv6/firewall/filter"
|
||||
for (const peer of site.neighbors.filter(peer => familyOf(peer.address) === family)) {
|
||||
const control = { chain: "input", "in-interface": namespace, protocol: "tcp", "src-address": host(peer.address), action: "accept" }
|
||||
add(filter, "allow-bgp-" + peer.id, { ...control, "dst-port": "179" })
|
||||
add(filter, "bgp-reply-" + peer.id, { ...control, "src-port": "179", "connection-state": "established" })
|
||||
}
|
||||
add(filter, "allow-control-" + family, { chain: "input", "in-interface": namespace, protocol: family === 4 ? "icmp" : "icmpv6", action: "accept" })
|
||||
add(filter, "deny-input-" + family, { chain: "input", "in-interface": namespace, action: "drop" })
|
||||
add(filter, "allow-segment-" + family, { chain: "forward", "in-interface": namespace, "out-interface": namespace, action: "accept" })
|
||||
add(filter, "egress-allow-" + family, { chain: "forward", "in-interface": namespace, "out-interface-list": egress, action: "accept" })
|
||||
add(filter, "deny-outside-" + family, { chain: "forward", "in-interface": namespace, action: "drop" })
|
||||
add(filter, "deny-inside-" + family, { chain: "forward", "out-interface": namespace, action: "drop" })
|
||||
add(filter, "egress-deny-" + family, { chain: "forward", "out-interface-list": egress, action: "drop" })
|
||||
}
|
||||
for (const [index, binding] of site.interfaces.entries()) {
|
||||
const key = binding.linux ? binding.name : String(index)
|
||||
if (binding.natIpv4) add("/ip/firewall/nat", "nat-" + index, { chain: "srcnat", action: "masquerade", "out-interface": binding.name })
|
||||
if (binding.kind === "gre-ipsec" && !binding.provisionGre) protectGre(binding, key)
|
||||
}
|
||||
}
|
||||
for (const [index, binding] of site.interfaces.entries()) {
|
||||
const wireguard = binding.provisionWireguard
|
||||
const tunnel = wireguard ?? binding.provisionGre
|
||||
if (binding.provisionTransit) result.push(...ixTransitSourceObjects(namespace, site, binding))
|
||||
if (!tunnel) continue
|
||||
const key = binding.linux ? binding.name : String(index)
|
||||
const family = familyOf(tunnel.localAddress)
|
||||
add(family === 4 ? "/ip/address" : "/ipv6/address", (binding.linux ? "client-address-" : "wg-address-") + key, {
|
||||
address: tunnel.localAddress, interface: binding.name, ...(family === 6 ? { advertise: "no" } : {}),
|
||||
})
|
||||
if (wireguard) add("/interface/wireguard/peers", "wg-peer-" + key, {
|
||||
interface: binding.name, "public-key": wireguard.peerPublicKey,
|
||||
"allowed-address": [...new Set([host(wireguard.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])].join(","),
|
||||
...(binding.endpoint ? { "endpoint-address": binding.endpoint, "endpoint-port": String(wireguard.endpointPort) } : {}),
|
||||
})
|
||||
for (const prefix of binding.linux ? binding.prefixes : []) {
|
||||
add(routePath(family), "client-network-" + key + "-" + prefixIdentifier(prefix), {
|
||||
"routing-table": namespace, "dst-address": canonicalBgpPolicyPrefix(prefix),
|
||||
gateway: tunnel.peerAddress + "%" + binding.name + "@" + namespace,
|
||||
})
|
||||
}
|
||||
}
|
||||
const groups = new Map(site.groups.map(group => [group.id, group]))
|
||||
const bgpGroups = new Set(site.neighbors.flatMap(peer => peer.type === "public-feed" ? peer.rules.map(rule => rule.group) : [peer.group]))
|
||||
const knownProbes = new Set<string>()
|
||||
const privateNetworks = [...new Set(site.discardNetworks.concat(site.neighbors.filter(peer => peer.type !== "public-feed").flatMap(peer => peer.prefixes),
|
||||
site.interfaces.flatMap(binding => binding.linux?.destinations ?? [])).map(canonicalBgpPolicyPrefix))]
|
||||
for (const family of families) {
|
||||
if (!site.groups.some(group => familyOf(group.gateway) === family) && !privateNetworks.some(prefix => familyOf(prefix) === family)) continue
|
||||
const path = routePath(family)
|
||||
const addressPath = family === 4 ? "/ip/address" : "/ipv6/address"
|
||||
add(addressPath, "drop-address-" + family, { address: sink[family].local, interface: dropInterface, ...(family === 6 ? { advertise: "no" } : {}) })
|
||||
const localRoute = (key: string, fields: Record<string, string>) => add(path, key, { "routing-table": namespace, ...fields })
|
||||
const familyExits = site.exits.map(id => groups.get(id)!).filter(group => familyOf(group.gateway) === family)
|
||||
const via = (address: string) => address + "@" + namespace
|
||||
for (const group of site.groups.filter(group => familyOf(group.gateway) === family)) {
|
||||
if (bgpGroups.has(group.id)) requireIx(inNetwork(bgpGatewayRange[family], group.gateway), "Используйте служебный next hop BGP из " + bgpGatewayRange[family])
|
||||
const paths = groupPaths(group).concat(group.onFailure === "segment-exit" ? familyExits.flatMap(groupPaths) : [])
|
||||
const distinctPaths = [...new Map(paths.map(candidate => [host(candidate.probe), candidate])).values()]
|
||||
for (const [index, candidate] of distinctPaths.entries()) {
|
||||
const probe = host(candidate.probe)
|
||||
if (!knownProbes.has(probe)) {
|
||||
const fields = { "dst-address": probe, gateway: candidate.nextHop + "%" + candidate.interface + "@" + (candidate.viaMain ? "main" : namespace),
|
||||
scope: "10", "target-scope": "10" }
|
||||
if (candidate.viaMain && candidate.probe !== candidate.nextHop) {
|
||||
add(path, "probe-main-" + knownProbes.size, { ...fields, "routing-table": "main" })
|
||||
} else localRoute("probe-" + knownProbes.size, fields)
|
||||
knownProbes.add(probe)
|
||||
}
|
||||
localRoute("gw-" + group.id + "-" + index, { "dst-address": host(group.gateway), ...checkedIxHop(candidate, namespace), scope: "20", distance: String(10 + index) })
|
||||
}
|
||||
localRoute("gw-" + group.id + "-discard", { "dst-address": host(group.gateway), gateway: sink[family].neighbor + "%" + dropInterface + "@" + namespace, scope: "20", "target-scope": "10", distance: "254" })
|
||||
// RouterOS 7.24 resolves addresses rewritten by a BGP input filter in main.
|
||||
if (bgpGroups.has(group.id)) add(path, "bgp-resolve-" + group.id, {
|
||||
"routing-table": "main", "dst-address": host(group.gateway), gateway: via(group.gateway), scope: "22", "target-scope": "21",
|
||||
})
|
||||
}
|
||||
for (const [index, route] of site.routes.entries()) {
|
||||
if (familyOf(route.prefix) === family) localRoute("static-" + index, { "dst-address": canonicalBgpPolicyPrefix(route.prefix), gateway: via(groups.get(route.group)!.gateway), "target-scope": "21" })
|
||||
}
|
||||
for (const [index, prefix] of privateNetworks.entries()) {
|
||||
if (familyOf(prefix) === family) localRoute("guard-" + index, { "dst-address": prefix, blackhole: "yes", distance: "254" })
|
||||
}
|
||||
// Compare exit path health directly: a group's final discard next hop must never win as an ordinary exit.
|
||||
for (const [index, candidate] of familyExits.flatMap(groupPaths).entries()) {
|
||||
localRoute("exit-" + family + "-" + index, { "dst-address": defaultRoute[family], ...checkedIxHop(candidate, namespace), distance: String(10 + index) })
|
||||
}
|
||||
localRoute("default-discard-" + family, { "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
|
||||
}
|
||||
if (!site.neighbors.length) continue
|
||||
add("/routing/bgp/instance", "bgp-instance", { name: namespace, as: String(site.autonomousSystem), "router-id": site.routerId, vrf: namespace, "routing-table": namespace })
|
||||
for (const peer of site.neighbors) {
|
||||
const family = familyOf(peer.address) as Family
|
||||
const input = namespace + "-" + peer.id + "-in"
|
||||
const output = namespace + "-" + peer.id + "-out"
|
||||
const subnetCondition = (prefix: string) => "dst in " + canonicalBgpPolicyPrefix(prefix)
|
||||
const setGateway = (groupId: string) => "set gw " + groups.get(groupId)!.gateway + "; set scope-target 23; accept;"
|
||||
const lines = ["if (dst == " + defaultRoute[family] + ") { reject; }"]
|
||||
if (peer.type === "public-feed") {
|
||||
const protectedNetworks = [...forbiddenPublic[family], ...privateNetworks.filter(prefix => familyOf(prefix) === family), ...site.groups.filter(group => familyOf(group.gateway) === family).map(group => host(group.gateway)), ...knownProbes].filter(prefix => familyOf(prefix) === family)
|
||||
lines.push("if (" + protectedNetworks.map(subnetCondition).join(" || ") + ") { reject; }")
|
||||
const restriction = peer.prefixes.length ? " && (" + peer.prefixes.map(subnetCondition).join(" || ") + ")" : ""
|
||||
for (const rule of peer.rules) lines.push("if (bgp-communities includes " + rule.community + restriction + ") { " + setGateway(rule.group) + " }")
|
||||
} else {
|
||||
lines.push("if (" + peer.prefixes.map(subnetCondition).join(" || ") + ") { " + setGateway(peer.group!) + " }")
|
||||
}
|
||||
const exportRules = peer.exportPrefixes.length ? "if (" + peer.exportPrefixes.map(subnetCondition).join(" || ") + ") { accept; } reject;" : "reject;"
|
||||
add("/routing/filter/rule", "bgp-in-" + peer.id, { chain: input, rule: lines.concat("reject;").join("\n") })
|
||||
add("/routing/filter/rule", "bgp-out-" + peer.id, { chain: output, rule: exportRules })
|
||||
add("/routing/bgp/connection", "neighbor-" + peer.id, {
|
||||
name: namespace + "-" + peer.id, instance: namespace, afi: familyName(family),
|
||||
"local.role": "ebgp", "local.address": peer.localAddress, "remote.address": host(peer.address), "remote.as": String(peer.remoteAs),
|
||||
"routing-table": namespace, vrf: namespace, "input.filter": input, "output.filter-chain": output,
|
||||
["input.limit-process-routes-ipv" + family]: String(peer.limit),
|
||||
...(peer.type === "exchange" ? { multihop: "yes", "output.redistribute": "static" } : {}),
|
||||
})
|
||||
}
|
||||
}
|
||||
unique(result.filter(object => object.fields["routing-table"] === "main" && object.fields["dst-address"])
|
||||
.map(object => object.serverId + ":" + object.fields["dst-address"]), "служебный или обратный маршрут IX в main")
|
||||
requireIx(result.length <= 500, "План IX превышает 500 объектов; разделите конфигурацию")
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { PoolClient } from "pg"
|
||||
import { isIPv4 } from "node:net"
|
||||
import { ixSegmentConfigurationSchema, type IxConfiguration, type IxSegment } from "@mmapp/contracts/internet-exchange"
|
||||
import { pool } from "../db/index.js"
|
||||
import { audit } from "../modules/mcp/store.js"
|
||||
import { IxConflict, ixDeviceIds } from "./internet-exchange-plan.js"
|
||||
import { admitPartitionWriter } from "./partition-write-transaction.js"
|
||||
|
||||
interface SegmentRow {
|
||||
id: string
|
||||
revision: number
|
||||
applied_revision: number | null
|
||||
configuration: unknown
|
||||
updated_at: Date
|
||||
}
|
||||
|
||||
const columns = "id,revision,applied_revision,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,
|
||||
configuration: ixSegmentConfigurationSchema.parse(row.configuration), updatedAt: row.updated_at.toISOString() }
|
||||
}
|
||||
|
||||
export async function listIxSegments(limit: number, offset: number, allowedIds?: readonly number[]) {
|
||||
const { rows } = await pool.query<SegmentRow>(
|
||||
`SELECT ${columns} FROM ix_segments s
|
||||
WHERE ${visible} AND ($1::bigint[] IS NULL OR NOT EXISTS (
|
||||
SELECT 1 FROM ix_segment_devices d WHERE d.segment_id=s.id AND NOT (d.server_id=ANY($1::bigint[]))
|
||||
))
|
||||
ORDER BY name,id LIMIT $2 OFFSET $3`, [allowedIds ?? null, limit, offset])
|
||||
return rows.map(segment)
|
||||
}
|
||||
|
||||
export async function readIxSegment(id: string, sql: Pick<PoolClient, "query"> = pool) {
|
||||
const { rows: [row] } = await sql.query<SegmentRow>(`SELECT ${columns} FROM ix_segments WHERE id=$1 AND ${visible}`, [id])
|
||||
return row ? segment(row) : null
|
||||
}
|
||||
|
||||
export async function isIxSegmentArchived(id: string, revision: number) {
|
||||
const { rowCount } = await pool.query("SELECT 1 FROM ix_segments WHERE id=$1 AND revision=$2 AND configuration->>'deleted'='true'", [id, revision])
|
||||
return rowCount === 1
|
||||
}
|
||||
|
||||
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)
|
||||
return ixSegmentConfigurationSchema.parse(row.configuration)
|
||||
}
|
||||
|
||||
export async function assertIxName(id: string, name: string) {
|
||||
const { rows } = await pool.query("SELECT 1 FROM ix_segments WHERE name=$1 AND id<>$2", [name, id])
|
||||
if (rows.length) throw new IxConflict("Имя IX уже занято")
|
||||
}
|
||||
|
||||
export async function assertIxSites(configuration: IxConfiguration, sql: Pick<PoolClient, "query"> = pool) {
|
||||
const ids = ixDeviceIds(configuration)
|
||||
const { rows } = await sql.query<{ id: number; type: string; enabled: boolean }>(
|
||||
"SELECT id,type,enabled FROM servers WHERE id=ANY($1::bigint[])", [ids])
|
||||
if (ids.length !== rows.length || rows.some(row => !row.enabled) || configuration.sites.some(site => rows.find(row => row.id === site.serverId)?.type !== "ix-node")) {
|
||||
throw new IxConflict("Площадки должны привязываться к включённым серверам типа IX Node, а все соседние устройства должны быть доступны")
|
||||
}
|
||||
}
|
||||
|
||||
export function assertIxRevision(current: IxSegment | null, expected: number) {
|
||||
if ((current?.revision ?? 0) !== expected) throw new IxConflict("Ревизия IX изменилась. Обновите данные и подготовьте новый план")
|
||||
}
|
||||
|
||||
export async function ixReservedRouterIds(id?: string, sql: Pick<PoolClient, "query"> = pool) {
|
||||
const { rows } = await sql.query<{ router_id: string }>(`
|
||||
SELECT site->>'routerId' AS router_id
|
||||
FROM ix_segments s
|
||||
LEFT JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
|
||||
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(s.configuration->'sites','[]'::jsonb) ||
|
||||
COALESCE(r.configuration->'sites','[]'::jsonb)) site
|
||||
WHERE (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
AND ($1::uuid IS NULL OR s.id<>$1)
|
||||
`, [id ?? null])
|
||||
return new Set(rows.map(row => row.router_id))
|
||||
}
|
||||
|
||||
export async function ixReservedTunnelBindings(serverId: number) {
|
||||
const { rows } = await pool.query<{ configuration: unknown }>(`
|
||||
SELECT s.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
|
||||
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
UNION ALL
|
||||
SELECT r.configuration FROM ix_segments s JOIN ix_segment_devices d ON d.segment_id=s.id
|
||||
JOIN ix_segment_revisions r ON r.segment_id=s.id AND r.revision=s.applied_revision
|
||||
WHERE d.server_id=$1 AND (s.configuration->>'deleted') IS DISTINCT FROM 'true'
|
||||
`, [serverId])
|
||||
return rows.flatMap(({ configuration }) => ixSegmentConfigurationSchema.parse(configuration).sites
|
||||
.flatMap(site => site.interfaces.filter(binding => site.serverId === serverId || binding.peerServerId === serverId)))
|
||||
}
|
||||
|
||||
export function nextIxRouterId(used: ReadonlySet<string>) {
|
||||
const [address, mask] = (process.env.MMAPP_IX_ROUTER_ID_POOL ?? "10.255.0.0/16").split("/")
|
||||
const length = Number(mask)
|
||||
if (!isIPv4(address) || !Number.isInteger(length) || length < 16 || length > 30) {
|
||||
throw new IxConflict("Пул Router ID должен быть IPv4-сетью с маской от /16 до /30")
|
||||
}
|
||||
const size = 2 ** (32 - length)
|
||||
const base = address.split(".").reduce((value, part) => value * 256 + Number(part), 0)
|
||||
if (base % size !== 0) throw new IxConflict("Для пула Router ID укажите адрес сети")
|
||||
for (let index = 1; index < size - 1; index++) {
|
||||
const value = base + index
|
||||
const candidate = [value >>> 24, (value >>> 16) & 255, (value >>> 8) & 255, value & 255].join(".")
|
||||
if (!used.has(candidate)) return candidate
|
||||
}
|
||||
throw new IxConflict("Пул Router ID IX исчерпан")
|
||||
}
|
||||
|
||||
export async function assertIxRouterIds(id: string, configuration: IxConfiguration, sql: Pick<PoolClient, "query"> = pool) {
|
||||
const used = await ixReservedRouterIds(id, sql)
|
||||
const existing = await readIxSegment(id, sql)
|
||||
const local = new Set<string>()
|
||||
for (const site of configuration.sites) {
|
||||
const unchanged = existing?.configuration.sites.some(old => old.serverId === site.serverId && old.routerId === site.routerId)
|
||||
if (local.has(site.routerId) || site.routerId === "0.0.0.0" || (site.autoRouterId && !unchanged && used.has(site.routerId))) {
|
||||
throw new IxConflict("Router ID " + site.routerId + " уже используется")
|
||||
}
|
||||
local.add(site.routerId)
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeIxRevision(id: string, expected: number, configuration: IxConfiguration, actor: string, applied: boolean) {
|
||||
const client = await pool.connect()
|
||||
try {
|
||||
await client.query("BEGIN")
|
||||
await admitPartitionWriter(client)
|
||||
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('ix-router-id',0))")
|
||||
await assertIxSites(configuration, client)
|
||||
await assertIxRouterIds(id, configuration, client)
|
||||
const revision = expected + 1
|
||||
const { rows: [row] } = expected === 0
|
||||
? await client.query<SegmentRow>(`INSERT INTO ix_segments(id,name,revision,configuration,applied_revision)
|
||||
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,
|
||||
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])
|
||||
if (!row) throw new IxConflict("Имя IX уже занято или ревизия сменилась")
|
||||
// Keep references to the applied topology while it can still hold live resources.
|
||||
const appliedConfiguration = !applied && row.applied_revision !== null
|
||||
? (await client.query("SELECT configuration FROM ix_segment_revisions WHERE segment_id=$1 AND revision=$2", [id, row.applied_revision])).rows[0]?.configuration
|
||||
: null
|
||||
const ids = [...new Set(ixDeviceIds(configuration).concat(appliedConfiguration ? ixDeviceIds(ixSegmentConfigurationSchema.parse(appliedConfiguration)) : []))]
|
||||
await client.query("DELETE FROM ix_segment_devices WHERE segment_id=$1", [id])
|
||||
await client.query("INSERT INTO ix_segment_devices(segment_id,server_id) SELECT $1, unnest($2::bigint[])", [id, ids])
|
||||
await client.query("INSERT INTO ix_segment_revisions(segment_id,revision,configuration,actor_id) VALUES ($1,$2,$3::jsonb,$4)",
|
||||
[id, revision, JSON.stringify(configuration), actor])
|
||||
await client.query("COMMIT")
|
||||
return segment(row)
|
||||
} catch (error) {
|
||||
await client.query("ROLLBACK").catch(() => {})
|
||||
if (error && typeof error === "object" && "code" in error && error.code === "23505") throw new IxConflict("Имя IX уже занято")
|
||||
throw error
|
||||
} finally { client.release() }
|
||||
}
|
||||
|
||||
export async function archiveIxSegment(id: string, revision: number, actorId: string) {
|
||||
const client = await pool.connect()
|
||||
try {
|
||||
await client.query("BEGIN")
|
||||
await admitPartitionWriter(client)
|
||||
// Keep the revision journal and free the name and device references using the existing writer grants.
|
||||
const { rowCount } = await client.query(`UPDATE ix_segments
|
||||
SET name='deleted:' || id::text, configuration=configuration || '{"deleted":true}'::jsonb, updated_at=now()
|
||||
WHERE id=$1 AND revision=$2 AND ${visible}`, [id, revision])
|
||||
if (rowCount !== 1) throw new IxConflict("Ревизия IX изменилась. Обновите данные и подготовьте новый план")
|
||||
await client.query("DELETE FROM ix_segment_devices WHERE segment_id=$1", [id])
|
||||
await audit(client, actorId, "ix.segment.deleted", null, { segmentId: id, revision })
|
||||
await client.query("COMMIT")
|
||||
} catch (error) {
|
||||
await client.query("ROLLBACK").catch(() => {})
|
||||
throw error
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import type { IxRouterObject, IxSite } from "@mmapp/contracts/internet-exchange"
|
||||
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
||||
|
||||
type Binding = IxSite["interfaces"][number]
|
||||
|
||||
export function ixTransitRemoteInterface(namespace: string, name: string) {
|
||||
return namespace.slice(0, 16) + "-" + name.slice(-12)
|
||||
}
|
||||
|
||||
export function compileIxTransit(namespace: string, site: IxSite, binding: Binding, add: (object: IxRouterObject) => void) {
|
||||
const transit = binding.provisionTransit!
|
||||
const serverId = binding.peerServerId!
|
||||
const remote = ixTransitRemoteInterface(namespace, binding.name)
|
||||
const remoteVrf = remote + "-v"
|
||||
const ipv6 = transit.remoteAddress.includes(":")
|
||||
const ip = ipv6 ? "/ipv6" : "/ip"
|
||||
const hostMask = ipv6 ? "/128" : "/32"
|
||||
const defaultPrefix = ipv6 ? "::/0" : "0.0.0.0/0"
|
||||
const clients = site.interfaces.filter(item => {
|
||||
const group = site.groups.find(group => group.id === item.linux?.exit)
|
||||
return item.linux?.enabled && group && [group.primary.interface, group.backup?.interface].includes(binding.name)
|
||||
})
|
||||
const sources = [...new Set(clients.flatMap(client => [
|
||||
(client.provisionWireguard ?? client.provisionGre)!.peerAddress + hostMask, ...client.prefixes,
|
||||
]).map(canonicalBgpPolicyPrefix))].sort()
|
||||
const hub = transit.localAddress.split("/")[0]
|
||||
const mask = transit.localAddress.split("/")[1]
|
||||
const key = (role: string, kind: "private" | "public") => `ix-transit:${kind}:${transit.credentialId}:${role}`
|
||||
const emit = (node: number, path: string, suffix: string, fields: Record<string, string>) => add({
|
||||
serverId: node, path, fields: { ...fields, comment: namespace + ":transit-" + binding.name + "-" + suffix },
|
||||
})
|
||||
const emitRemote = (path: string, suffix: string, fields: Record<string, string>) => emit(serverId, path, suffix, fields)
|
||||
emitRemote("/interface/wireguard", "wg", {
|
||||
name: remote, "listen-port": String(transit.remotePort), "private-key": key("b", "private"),
|
||||
})
|
||||
emitRemote("/ip/vrf", "vrf", { name: remoteVrf, interfaces: remote })
|
||||
emitRemote(ip + "/address", "address", { interface: remote, address: transit.remoteAddress + "/" + mask,
|
||||
...(ipv6 && { advertise: "no" }) })
|
||||
emitRemote("/interface/wireguard/peers", "peer", {
|
||||
interface: remote, "public-key": key("a", "public"), "allowed-address": [hub + hostMask, ...sources].join(","),
|
||||
"endpoint-address": transit.localEndpoint, "endpoint-port": String(transit.localPort), "persistent-keepalive": "25s",
|
||||
})
|
||||
emitRemote(ip + "/route", "default", { "routing-table": remoteVrf, "dst-address": defaultPrefix,
|
||||
gateway: transit.remoteWan.nextHop + "%" + transit.remoteWan.interface + "@main",
|
||||
})
|
||||
emitRemote(ip + "/route", "default-drop", { "routing-table": remoteVrf, "dst-address": defaultPrefix, blackhole: "yes", distance: "254" })
|
||||
const filter = ip + "/firewall/filter"
|
||||
const srcList = remote + "-src"
|
||||
emitRemote("/ip/firewall/filter", "listen", { chain: "input", protocol: "udp", "src-address": transit.localEndpoint + "/32",
|
||||
"dst-address": transit.remoteEndpoint + "/32", "dst-port": String(transit.remotePort), action: "accept" })
|
||||
emitRemote(filter, "ping", { chain: "input", "in-interface": remoteVrf, protocol: ipv6 ? "icmpv6" : "icmp", "src-address": hub + hostMask, action: "accept" })
|
||||
emitRemote(filter, "deny-management", { chain: "input", "in-interface": remoteVrf, action: "drop" })
|
||||
emitRemote(filter, "out", { chain: "forward", "in-interface": remoteVrf, "out-interface": transit.remoteWan.interface,
|
||||
"src-address-list": srcList, action: "accept" })
|
||||
emitRemote(filter, "return-filter", {
|
||||
chain: "forward", "dst-address-list": srcList, "connection-state": "established,related", action: "accept",
|
||||
})
|
||||
emitRemote(filter, "deny-forward", { chain: "forward", "in-interface": remoteVrf, action: "drop" })
|
||||
emitRemote(filter, "deny-inbound", { chain: "forward", "dst-address-list": srcList, action: "drop" })
|
||||
if (!ipv6) emitRemote("/ip/firewall/nat", "nat", { chain: "srcnat", "out-interface": transit.remoteWan.interface,
|
||||
"src-address-list": srcList, action: "masquerade" })
|
||||
for (const address of [hub + hostMask, ...sources]) {
|
||||
const identity = createHash("sha256").update(address).digest("hex").slice(0, 12)
|
||||
emitRemote(ip + "/firewall/address-list", "client-" + identity, { address, list: srcList })
|
||||
for (const table of address === hub + hostMask ? ["main"] : [remoteVrf, "main"]) emitRemote(ip + "/route", "return-" + table + "-" + identity, {
|
||||
"routing-table": table, "dst-address": address, gateway: hub + "%" + remote + "@" + remoteVrf,
|
||||
})
|
||||
}
|
||||
emit(site.serverId, "/interface/wireguard", "source-wg", {
|
||||
name: binding.name, "listen-port": String(transit.localPort), "private-key": key("a", "private"),
|
||||
})
|
||||
// Source peer/address depend on the local VRF assignment and are emitted by the caller.
|
||||
}
|
||||
|
||||
export function ixTransitSourceObjects(namespace: string, site: IxSite, binding: Binding): IxRouterObject[] {
|
||||
const transit = binding.provisionTransit!
|
||||
const ipv6 = transit.remoteAddress.includes(":")
|
||||
return [
|
||||
{ serverId: site.serverId, path: ipv6 ? "/ipv6/address" : "/ip/address", fields: { address: transit.localAddress, interface: binding.name,
|
||||
...(ipv6 && { advertise: "no" }),
|
||||
comment: namespace + ":transit-" + binding.name + "-source-address" } },
|
||||
{ serverId: site.serverId, path: "/interface/wireguard/peers", fields: {
|
||||
interface: binding.name, "public-key": `ix-transit:public:${transit.credentialId}:b`, "allowed-address": ipv6 ? "::/0" : "0.0.0.0/0",
|
||||
"endpoint-address": transit.remoteEndpoint, "endpoint-port": String(transit.remotePort), "persistent-keepalive": "25s",
|
||||
comment: namespace + ":transit-" + binding.name + "-source-peer",
|
||||
} },
|
||||
{ serverId: site.serverId, path: "/ip/firewall/filter", fields: {
|
||||
chain: "input", action: "accept", protocol: "udp", "src-address": transit.remoteEndpoint + "/32",
|
||||
"dst-address": transit.localEndpoint + "/32", "dst-port": String(transit.localPort),
|
||||
comment: namespace + ":transit-" + binding.name + "-source-listen",
|
||||
} },
|
||||
]
|
||||
}
|
||||
@@ -114,7 +114,7 @@ test("empty/global0 and full128 ledgers use complete exact global/owner counters
|
||||
const empty = fixture([]); await empty.run(); assert.deepEqual(empty.counts(), { factories: 0, charges: 0 })
|
||||
const f = fixture(Array.from({ length: 128 }, (_, n) => full(n + 1, "owner-" + Math.floor(n / 8))))
|
||||
await f.run(); assert.deepEqual(f.batches, [128, 0]); assert.deepEqual(f.counts(), { factories: 0, charges: 0 })
|
||||
assert.equal(Number(f.usage.find(row => row.scope === "global")!.reserved_bytes), policy.globalBytes)
|
||||
assert.equal(Number(f.usage.find(row => row.scope === "global")!.reserved_bytes), 128 * (policy.attemptBytes + policy.admissionBytes))
|
||||
})
|
||||
|
||||
test("compact336 plus full reservations and multiowner usage paginate in128-row bounded metadata batches", async () => {
|
||||
@@ -197,14 +197,13 @@ test("archive/admission identity, binding, context, timestamps and retention met
|
||||
}
|
||||
})
|
||||
|
||||
test("full heavy-count global129 and owner9 refuse even if usage counters claim conservation", async () => {
|
||||
await refused(fixture(Array.from({ length: 129 }, (_, n) => full(n + 1, "owner-" + Math.floor(n / 8)))).run())
|
||||
await refused(fixture(Array.from({ length: 9 }, (_, n) => full(n + 1, "one-owner"))).run())
|
||||
test("130 full reservations for one owner pass exact accounting", async () => {
|
||||
await fixture(Array.from({ length: 130 }, (_, n) => full(n + 1, "one-owner"))).run()
|
||||
})
|
||||
|
||||
test("compacted rows still pay retained bytes and cannot share an already fully charged owner", async () => {
|
||||
test("compacted rows and full reservations share the same exact owner accounting", async () => {
|
||||
const f = fixture([...Array.from({ length: 8 }, (_, n) => full(n + 1, "owner")), await compact(100, "owner")])
|
||||
await refused(f.run())
|
||||
await f.run()
|
||||
})
|
||||
|
||||
test("nonadjacent duplicate receipt IDs cannot count twice even when cardinality/owner counters agree", async () => {
|
||||
@@ -218,12 +217,12 @@ test("compacted timestamp must be an actual finite SQL timestamp", async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("retained archive bytes can exhaust global budget before heavy-count or row-count limits", async () => {
|
||||
test("paid archive bytes above the former global budget retain exact accounting", async () => {
|
||||
const compacts = await Promise.all(Array.from({ length: 336 }, (_, n) => compact(1000 + n, "archive-owner-" + n)))
|
||||
const f = fixture([...Array.from({ length: 127 }, (_, n) => full(n + 1, "full-owner-" + Math.floor(n / 8))), ...compacts])
|
||||
const global = f.usage.find(row => row.scope === "global")!
|
||||
assert.equal(global.admissions, 127); assert(Number(global.reserved_rows) < policy.globalRows); assert(Number(global.reserved_bytes) > policy.globalBytes)
|
||||
await refused(f.run())
|
||||
assert.equal(global.admissions, 127); assert(Number(global.reserved_bytes) > 128 * (policy.attemptBytes + policy.admissionBytes))
|
||||
await f.run()
|
||||
})
|
||||
|
||||
test("invalid numeric counters cannot hide through coercion or extra scopes", async () => {
|
||||
|
||||
@@ -6,7 +6,6 @@ import { createServerPollArchiveChargeVerifier, type verifyServerPollArchiveChar
|
||||
import type { createServerPollRetiredArchiveChargeVerifier } from "./server-poll-retired-archive.js"
|
||||
|
||||
const BATCH = 128
|
||||
const MAX_ENTRIES = Math.floor(policy.globalBytes / policy.admissionBytes)
|
||||
const fail: () => never = () => { throw new PollStorageRefused() }
|
||||
const uuid = /^[a-f\d]{8}-[a-f\d]{4}-[1-8][a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12}$/i
|
||||
function integer(value: unknown): number {
|
||||
@@ -40,8 +39,7 @@ const QUERY = `SELECT a.receipt_id AS admission_receipt_id,a.identity_kind,a.exe
|
||||
async function verify(sql: ProbeStorageSql, factory: () => Promise<typeof verifyServerPollArchiveCharge>,
|
||||
retiredFactory: typeof createServerPollRetiredArchiveChargeVerifier) {
|
||||
const global = zero(), owners = new Map<string, Total>()
|
||||
const seenReceipts = new Set<string>()
|
||||
let cursor: string | null = null, count = 0, charge: typeof verifyServerPollArchiveCharge | undefined
|
||||
let cursor: string | null = null, charge: typeof verifyServerPollArchiveCharge | undefined
|
||||
let retiredCharge: Awaited<ReturnType<typeof retiredFactory>> | undefined
|
||||
// All queries are fixed. Only metadata, hashes and actual lengths cross the
|
||||
// driver boundary; even a full global history never becomes a JS blob.
|
||||
@@ -50,11 +48,10 @@ async function verify(sql: ProbeStorageSql, factory: () => Promise<typeof verify
|
||||
if (!Array.isArray(rows) || rows.length > BATCH) fail()
|
||||
for (const raw of rows) {
|
||||
const row: Record<string, unknown> = structuredClone(raw)
|
||||
if (++count > MAX_ENTRIES || typeof row.admission_receipt_id !== "string" || !uuid.test(row.admission_receipt_id) ||
|
||||
seenReceipts.has(row.admission_receipt_id) || typeof row.admission_owner_id !== "string" || !row.admission_owner_id.length ||
|
||||
if (typeof row.admission_receipt_id !== "string" || !uuid.test(row.admission_receipt_id) ||
|
||||
cursor !== null && row.admission_receipt_id <= cursor || typeof row.admission_owner_id !== "string" || !row.admission_owner_id.length ||
|
||||
row.admission_owner_id.length > 200 || row.admission_owner_id.trim() !== row.admission_owner_id || /[\x00-\x1f\x7f]/.test(row.admission_owner_id)) fail()
|
||||
cursor = row.admission_receipt_id
|
||||
seenReceipts.add(cursor)
|
||||
let addition: Total
|
||||
if (row.storage_state === "full") {
|
||||
if (row.receipt_id !== null || row.compact_at !== null || row.admission_archive_bytes !== null || row.admission_activity_at !== null) fail()
|
||||
@@ -78,22 +75,20 @@ async function verify(sql: ProbeStorageSql, factory: () => Promise<typeof verify
|
||||
} else return fail()
|
||||
const owned = owners.get(row.admission_owner_id) ?? zero()
|
||||
owners.set(row.admission_owner_id, owned)
|
||||
for (const total of [global, owned]) for (const key of Object.keys(total) as (keyof Total)[]) total[key] += addition[key]
|
||||
if (global.heavy > policy.globalAttempts || global.bytes > policy.globalBytes || global.rows > policy.globalRows ||
|
||||
owned.heavy > policy.ownerAttempts || owned.bytes > policy.ownerBytes || owned.rows > policy.ownerRows) fail()
|
||||
for (const total of [global, owned]) for (const key of Object.keys(total) as (keyof Total)[]) total[key] = integer(total[key] + addition[key])
|
||||
}
|
||||
if (rows.length < BATCH) break
|
||||
}
|
||||
// Orphan archives cannot disappear from the allocation scan and manufacture
|
||||
// credit. Admission identity is retained until the original retention GC.
|
||||
if ((await sql.query("SELECT r.receipt_id FROM server_poll_archives r LEFT JOIN server_poll_storage_admissions a USING(receipt_id) WHERE a.receipt_id IS NULL LIMIT 1")).rows.length) fail()
|
||||
let scopeCursor: string | null = null, seenGlobal = false, usageCount = 0
|
||||
let scopeCursor: string | null = null, seenGlobal = false
|
||||
const seenOwners = new Set<string>()
|
||||
for (;;) {
|
||||
const rows: Record<string, unknown>[] = (await sql.query("SELECT scope,admissions,compacted_admissions,archive_bytes,reserved_rows,reserved_bytes FROM server_poll_storage_usage WHERE ($1::text IS NULL OR scope>$1) ORDER BY scope LIMIT 128 FOR SHARE", [scopeCursor])).rows
|
||||
if (!Array.isArray(rows) || rows.length > BATCH) fail()
|
||||
for (const row of rows) {
|
||||
if (++usageCount > MAX_ENTRIES + 1 || typeof row.scope !== "string" || row.scope === scopeCursor) fail()
|
||||
if (typeof row.scope !== "string" || row.scope === scopeCursor) fail()
|
||||
scopeCursor = row.scope
|
||||
let expected: Total
|
||||
if (row.scope === "global") { if (seenGlobal) fail(); seenGlobal = true; expected = global }
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { readServerPollCapacity, type ServerPollCapacitySql } from "./server-poll-capacity.js"
|
||||
import { readServerPollUsage, type ServerPollCapacitySql } from "./server-poll-capacity.js"
|
||||
import { SERVER_POLL_STORAGE_POLICY as policy } from "./server-poll-storage-model.js"
|
||||
import { mcpPollStorageCapacitySchema } from "@mmapp/contracts/mcp"
|
||||
import { mcpPollStorageUsageSchema } from "@mmapp/contracts/mcp"
|
||||
|
||||
const row = (owner: number | null = 2, global = 10) => ({ retention_days: 30,
|
||||
global_compacted_admissions:"0",global_archive_bytes:"0",owner_compacted_admissions:owner===null?null:"0",owner_archive_bytes:owner===null?null:"0",
|
||||
@@ -16,8 +16,8 @@ function fixture(rows: Record<string, unknown>[] = [row()]) {
|
||||
|
||||
test("one parameterized bounded snapshot reads only settings and exact owner/global usage without maintenance or locks", async () => {
|
||||
const f = fixture(), owner = "operator' OR true--"
|
||||
const result = await readServerPollCapacity(f.sql, owner, true)
|
||||
assert.deepEqual(result, { status: "observed", owner: { used: 2, limit: 8, remaining: 6 }, global: { exhausted: false, usage: { used: 10, limit: 128, remaining: 118 } }, retentionDays: 30 })
|
||||
const result = await readServerPollUsage(f.sql, owner, true)
|
||||
assert.deepEqual(result, { status: "observed", ownerFull: 2, globalFull: 10, retentionDays: 30 })
|
||||
assert.equal(f.calls.length, 1); const { text, values } = f.calls[0]
|
||||
assert.deepEqual(values, ["owner:" + owner]); assert(!text.includes(owner)); assert.match(text, /^SELECT\b/)
|
||||
assert.match(text, /FROM public\.mcp_settings\b/); assert.equal((text.match(/LEFT JOIN public\.server_poll_storage_usage\b/g) ?? []).length, 2)
|
||||
@@ -26,44 +26,44 @@ test("one parameterized bounded snapshot reads only settings and exact owner/glo
|
||||
assert(!text.includes("server_poll_storage_admissions"))
|
||||
})
|
||||
|
||||
test("non-admin hides all global counts while reporting exhaustion; admin alone receives numbers", async () => {
|
||||
for (const used of [0, 127, 128]) {
|
||||
const f = fixture([row(0, used)]), result = await readServerPollCapacity(f.sql, "one-owner", false)
|
||||
assert.deepEqual(result, { status: "observed", owner: { used: 0, limit: 8, remaining: 8 }, global: { exhausted: used === 128, usage: null }, retentionDays: 30 })
|
||||
test("non-admin hides all global counts", async () => {
|
||||
for (const used of [0, 128, 2000]) {
|
||||
const f = fixture([row(0, used)]), result = await readServerPollUsage(f.sql, "one-owner", false)
|
||||
assert.deepEqual(result, { status: "observed", ownerFull: 0, globalFull: null, retentionDays: 30 })
|
||||
assert(!JSON.stringify(result).includes("one-owner")); assert(!JSON.stringify(result).includes('"ready"'))
|
||||
}
|
||||
})
|
||||
|
||||
test("owner eight/full global128 expose zero remaining and only entirely null missing owner is zero", async () => {
|
||||
const full = await readServerPollCapacity(fixture([row(8, 128)]).sql, "owner", true)
|
||||
assert.deepEqual(full, { status: "observed", owner: { used: 8, limit: 8, remaining: 0 }, global: { exhausted: true, usage: { used: 128, limit: 128, remaining: 0 } }, retentionDays: 30 })
|
||||
assert.deepEqual(await readServerPollCapacity(fixture([row(null, 0)]).sql, "new-owner", false), { status: "observed", owner: { used: 0, limit: 8, remaining: 8 }, global: { exhausted: false, usage: null }, retentionDays: 30 })
|
||||
test("observes twenty owner journals and more than 128 global journals", async () => {
|
||||
const full = await readServerPollUsage(fixture([row(20, 130)]).sql, "owner", true)
|
||||
assert.deepEqual(full, { status: "observed", ownerFull: 20, globalFull: 130, retentionDays: 30 })
|
||||
assert.deepEqual(await readServerPollUsage(fixture([row(null, 0)]).sql, "new-owner", false), { status: "observed", ownerFull: 0, globalFull: null, retentionDays: 30 })
|
||||
})
|
||||
|
||||
test("SQL failure/missing relation or settings/global accounting is unavailable and never zero", async () => {
|
||||
for (const code of ["42P01", "08006", "57014"]) {
|
||||
let calls = 0
|
||||
assert.deepEqual(await readServerPollCapacity({ async query() { calls++; throw Object.assign(Error("private SQL failure"), { code }) } }, "owner", true), { status: "unavailable" })
|
||||
assert.deepEqual(await readServerPollUsage({ async query() { calls++; throw Object.assign(Error("private SQL failure"), { code }) } }, "owner", true), { status: "unavailable" })
|
||||
assert.equal(calls, 1)
|
||||
}
|
||||
for (const rows of [[], [row(), row()], [{}], [{ ...row(), global_admissions: null, global_reserved_rows: null, global_reserved_bytes: null }], [{ ...row(), retention_days: undefined }]])
|
||||
assert.deepEqual(await readServerPollCapacity(fixture(rows).sql, "owner", true), { status: "unavailable" })
|
||||
assert.deepEqual(await readServerPollUsage(fixture(rows).sql, "owner", true), { status: "unavailable" })
|
||||
})
|
||||
|
||||
test("invalid owner/admin values refuse before query; trimmed Unicode identity remains exact", async () => {
|
||||
for (const owner of ["", " ", " owner", "owner ", "a\nb", "a\0b", "a\x7fb", "a\x85b", "a".repeat(201), undefined, 42]) {
|
||||
const f = fixture(); assert.deepEqual(await readServerPollCapacity(f.sql, owner as string, false), { status: "unavailable" }); assert.equal(f.calls.length, 0)
|
||||
const f = fixture(); assert.deepEqual(await readServerPollUsage(f.sql, owner as string, false), { status: "unavailable" }); assert.equal(f.calls.length, 0)
|
||||
}
|
||||
const invalid = fixture(); assert.deepEqual(await readServerPollCapacity(invalid.sql, "owner", "true" as unknown as boolean), { status: "unavailable" }); assert.equal(invalid.calls.length, 0)
|
||||
const unicode = fixture(); assert.equal((await readServerPollCapacity(unicode.sql, "Оператор😀", false)).status, "observed"); assert.deepEqual(unicode.calls[0].values, ["owner:Оператор😀"])
|
||||
const invalid = fixture(); assert.deepEqual(await readServerPollUsage(invalid.sql, "owner", "true" as unknown as boolean), { status: "unavailable" }); assert.equal(invalid.calls.length, 0)
|
||||
const unicode = fixture(); assert.equal((await readServerPollUsage(unicode.sql, "Оператор😀", false)).status, "observed"); assert.deepEqual(unicode.calls[0].values, ["owner:Оператор😀"])
|
||||
})
|
||||
|
||||
test("counter triples reject malformed canonical bigint values, partial NULL, mismatch, excessive limits and owner greater than global", async () => {
|
||||
test("counter triples reject malformed canonical bigint values, partial NULL, mismatch and owner greater than global", async () => {
|
||||
const invalid = [undefined, null, true, false, {}, [], 1n, NaN, Infinity, -1, -0, 1.5, Number.MAX_SAFE_INTEGER + 1, "", " 0", "0 ", "00", "01", "+1", "-0", "1.0", "1e0", "0x1", "9007199254740992"]
|
||||
for (const field of ["global_admissions", "global_reserved_rows", "global_reserved_bytes", "owner_admissions", "owner_reserved_rows", "owner_reserved_bytes","global_compacted_admissions","global_archive_bytes","owner_compacted_admissions","owner_archive_bytes"])
|
||||
for (const value of invalid) assert.deepEqual(await readServerPollCapacity(fixture([{ ...row(), [field]: value }]).sql, "owner", true), { status: "unavailable" }, field + ":" + String(value))
|
||||
for (const candidate of [row(9, 10), row(8, 7), row(0, 129), { ...row(), owner_reserved_rows: "0" }, { ...row(), global_reserved_bytes: "0" }, { ...row(null), owner_reserved_bytes: "0" }])
|
||||
assert.deepEqual(await readServerPollCapacity(fixture([candidate]).sql, "owner", true), { status: "unavailable" })
|
||||
for (const value of invalid) assert.deepEqual(await readServerPollUsage(fixture([{ ...row(), [field]: value }]).sql, "owner", true), { status: "unavailable" }, field + ":" + String(value))
|
||||
for (const candidate of [row(8, 7), { ...row(), owner_reserved_rows: "0" }, { ...row(), global_reserved_bytes: "0" }, { ...row(null), owner_reserved_bytes: "0" }])
|
||||
assert.deepEqual(await readServerPollUsage(fixture([candidate]).sql, "owner", true), { status: "unavailable" })
|
||||
})
|
||||
|
||||
function compactRow(ownerHeavy:number,ownerCompact:number,globalHeavy=ownerHeavy,globalCompact=ownerCompact,encoded=59075){
|
||||
@@ -73,27 +73,10 @@ function compactRow(ownerHeavy:number,ownerCompact:number,globalHeavy=ownerHeavy
|
||||
global_reserved_rows:String(globalHeavy*4019+globalCompact*2),global_reserved_bytes:String(globalHeavy*8421376+globalCompact*(32768+encoded))}
|
||||
}
|
||||
|
||||
test("336 retained histories remain paid while DTO used counts heavy slots and remaining obeys all caps",async()=>{
|
||||
const result=await readServerPollCapacity(fixture([compactRow(1,336)]).sql,"owner",true)
|
||||
assert.deepEqual(result,{status:"observed",owner:{used:1,limit:8,remaining:3},global:{exhausted:false,usage:{used:1,limit:128,remaining:123}},retentionDays:30})
|
||||
})
|
||||
|
||||
test("largest permitted archives still allow one new poll after336 histories; shared contract accepts the byte-limited remainder",async()=>{
|
||||
const before=await readServerPollCapacity(fixture([compactRow(0,336,0,336,131072)]).sql,"owner",true)
|
||||
assert(before.status==="observed");assert.equal(before.owner.remaining,1)
|
||||
assert.deepEqual(mcpPollStorageCapacitySchema.parse(before),before)
|
||||
const occupied=await readServerPollCapacity(fixture([compactRow(1,336,1,336,131072)]).sql,"owner",true)
|
||||
assert(occupied.status==="observed");assert.equal(occupied.owner.used,1);assert.equal(occupied.owner.remaining,0)
|
||||
assert.deepEqual(mcpPollStorageCapacitySchema.parse(occupied),occupied)
|
||||
assert.equal(mcpPollStorageCapacitySchema.safeParse({...occupied,owner:{used:8,limit:8,remaining:1}}).success,false)
|
||||
})
|
||||
|
||||
test("byte-full retained history cannot report available admission despite unused heavy slots",async()=>{
|
||||
const ownerFull=await readServerPollCapacity(fixture([compactRow(0,2000,0,2000,40)]).sql,"owner",false)
|
||||
assert(ownerFull.status==="observed");assert.equal(ownerFull.owner.used,0);assert.equal(ownerFull.owner.remaining,0)
|
||||
assert.equal(ownerFull.global.exhausted,false);assert.equal(ownerFull.global.usage,null)
|
||||
const globalFull=await readServerPollCapacity(fixture([compactRow(0,0,0,32600,40)]).sql,"owner",false)
|
||||
assert(globalFull.status==="observed");assert.equal(globalFull.global.exhausted,true);assert.equal(globalFull.global.usage,null)
|
||||
test("retained archive accounting does not impose a cumulative quota", async () => {
|
||||
const result = await readServerPollUsage(fixture([compactRow(20, 2000, 130, 32600, 131072)]).sql, "owner", true)
|
||||
assert.deepEqual(result, {status:"observed", ownerFull:20, globalFull:130, retentionDays:30})
|
||||
assert.deepEqual(mcpPollStorageUsageSchema.parse(result), result)
|
||||
})
|
||||
|
||||
test("missing 0041 fields, malformed archive accounting and owner/global mismatch fail unavailable",async()=>{
|
||||
@@ -101,24 +84,24 @@ test("missing 0041 fields, malformed archive accounting and owner/global mismatc
|
||||
for(const value of [legacy,{...row(),owner_compacted_admissions:null},{...row(),global_archive_bytes:"1"},
|
||||
compactRow(0,1,0,1,39),compactRow(0,1,0,1,131073),compactRow(0,2,0,1),
|
||||
{...compactRow(0,1),owner_reserved_rows:"0"},{...compactRow(0,1),global_reserved_bytes:"0"}])
|
||||
assert.deepEqual(await readServerPollCapacity(fixture([value]).sql,"owner",true),{status:"unavailable"})
|
||||
assert.deepEqual(await readServerPollUsage(fixture([value]).sql,"owner",true),{status:"unavailable"})
|
||||
})
|
||||
|
||||
test("canonical PostgreSQL bigint strings and safe integer numbers are accepted; retention current1..365 only", async () => {
|
||||
const numeric = Object.fromEntries(Object.entries(row()).map(([key, value]) => [key, Number(value)]))
|
||||
assert.equal((await readServerPollCapacity(fixture([numeric]).sql, "owner", true)).status, "observed")
|
||||
assert.equal((await readServerPollUsage(fixture([numeric]).sql, "owner", true)).status, "observed")
|
||||
for (const days of [1, "1", 365, "365"]) {
|
||||
const result = await readServerPollCapacity(fixture([{ ...row(), retention_days: days }]).sql, "owner", false)
|
||||
const result = await readServerPollUsage(fixture([{ ...row(), retention_days: days }]).sql, "owner", false)
|
||||
assert(result.status === "observed"); assert.equal(result.retentionDays, Number(days))
|
||||
}
|
||||
for (const days of [0, 366, -1, 1.5, "01", null, undefined]) assert.deepEqual(await readServerPollCapacity(fixture([{ ...row(), retention_days: days }]).sql, "owner", false), { status: "unavailable" })
|
||||
for (const days of [0, 366, -1, 1.5, "01", null, undefined]) assert.deepEqual(await readServerPollUsage(fixture([{ ...row(), retention_days: days }]).sql, "owner", false), { status: "unavailable" })
|
||||
})
|
||||
|
||||
test("returned DTO is deeply frozen and independent of later SQL row/result mutations", async () => {
|
||||
const original = row(), rows = [original], f = fixture(rows), result = await readServerPollCapacity(f.sql, "owner", true)
|
||||
const original = row(), rows = [original], f = fixture(rows), result = await readServerPollUsage(f.sql, "owner", true)
|
||||
assert(result.status === "observed"); const expected = structuredClone(result)
|
||||
Object.assign(original, row(8, 128), { retention_days: 365 }); rows.splice(0)
|
||||
assert.deepEqual(result, expected); assert(Object.isFrozen(result)); assert(Object.isFrozen(result.owner)); assert(Object.isFrozen(result.global)); assert(Object.isFrozen(result.global.usage))
|
||||
assert.throws(() => { (result.owner as { used: number }).used = 7 })
|
||||
assert(Object.isFrozen(await readServerPollCapacity(fixture([]).sql, "owner", false)))
|
||||
assert.deepEqual(result, expected); assert(Object.isFrozen(result))
|
||||
assert.throws(() => { (result as { ownerFull: number }).ownerFull = 7 })
|
||||
assert(Object.isFrozen(await readServerPollUsage(fixture([]).sql, "owner", false)))
|
||||
})
|
||||
@@ -1,10 +1,6 @@
|
||||
import { pollStorageUsageRemaining, type PollStorageUsage } from "./server-poll-storage-model.js"
|
||||
import type { McpPollStorageUsage } from "@mmapp/contracts/mcp"
|
||||
import { validatePollStorageUsage } from "./server-poll-storage-model.js"
|
||||
|
||||
export type ServerPollCapacity =
|
||||
| Readonly<{ status: "unavailable" }>
|
||||
| Readonly<{ status: "observed"; owner: Readonly<{ used: number; limit: 8; remaining: number }>;
|
||||
global: Readonly<{ exhausted: boolean; usage: Readonly<{ used: number; limit: 128; remaining: number }> | null }>;
|
||||
retentionDays: number }>
|
||||
export interface ServerPollCapacitySql { query(text: string, values: unknown[]): Promise<{ rows: Record<string, unknown>[] }> }
|
||||
|
||||
// A single bounded MVCC snapshot. No admission enumeration, maintenance, locks
|
||||
@@ -16,28 +12,22 @@ FROM public.mcp_settings s
|
||||
LEFT JOIN public.server_poll_storage_usage g ON g.scope='global'
|
||||
LEFT JOIN public.server_poll_storage_usage o ON o.scope=$1
|
||||
WHERE s.id=1 LIMIT 2`
|
||||
const unavailable: ServerPollCapacity = Object.freeze({ status: "unavailable" })
|
||||
const unavailable: McpPollStorageUsage = Object.freeze({ status: "unavailable" })
|
||||
function integer(value: unknown): number | undefined {
|
||||
if (typeof value === "number") return Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0) ? value : undefined
|
||||
if (typeof value !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(value) || value.length > 16) return undefined
|
||||
const parsed = Number(value)
|
||||
return Number.isSafeInteger(parsed) ? parsed : undefined
|
||||
}
|
||||
function usage(admissions: unknown, rows: unknown, bytes: unknown, compacted:unknown, archive:unknown, scope:"global"|"owner") {
|
||||
function usage(admissions: unknown, rows: unknown, bytes: unknown, compacted:unknown, archive:unknown) {
|
||||
const used=integer(admissions),reservedRows=integer(rows),reservedBytes=integer(bytes),compactedAttempts=integer(compacted),archiveBytes=integer(archive)
|
||||
if(used===undefined||reservedRows===undefined||reservedBytes===undefined||compactedAttempts===undefined||archiveBytes===undefined)return undefined
|
||||
const value:PollStorageUsage={attempts:used,rows:reservedRows,bytes:reservedBytes,compactedAttempts,archiveBytes}
|
||||
const remaining=pollStorageUsageRemaining(value,scope)
|
||||
return remaining===undefined?undefined:{value,remaining}
|
||||
return validatePollStorageUsage({attempts:used,rows:reservedRows,bytes:reservedBytes,compactedAttempts,archiveBytes})
|
||||
}
|
||||
|
||||
/** Read-only heavy reservation availability with paid retained history. Used
|
||||
* counts heavy slots; remaining also accounts for archive bytes/rows. This
|
||||
* observation does not verify archive MACs and is never an admission promise.
|
||||
* Missing or
|
||||
* inconsistent accounting is unavailable rather than a fabricated free slot.
|
||||
/** Read-only count of full journals. Missing or inconsistent accounting is unavailable.
|
||||
* Non-admin callers receive no global usage numbers or other owner identities. */
|
||||
export async function readServerPollCapacity(sql: ServerPollCapacitySql, ownerId: string, admin: boolean): Promise<ServerPollCapacity> {
|
||||
export async function readServerPollUsage(sql: ServerPollCapacitySql, ownerId: string, admin: boolean): Promise<McpPollStorageUsage> {
|
||||
if (typeof ownerId !== "string" || ownerId.trim() !== ownerId || !ownerId.length || [...ownerId].length > 200
|
||||
|| /[\u0000-\u001f\u007f-\u009f]/.test(ownerId) || typeof admin !== "boolean") return unavailable
|
||||
try {
|
||||
@@ -48,16 +38,14 @@ export async function readServerPollCapacity(sql: ServerPollCapacitySql, ownerId
|
||||
// Capture primitive fields synchronously. DTOs never alias mutable driver
|
||||
// rows and are frozen independently of the SQL adapter's result lifetime.
|
||||
const retentionDays = integer(row.retention_days)
|
||||
const globalUsed=usage(row.global_admissions,row.global_reserved_rows,row.global_reserved_bytes,row.global_compacted_admissions,row.global_archive_bytes,"global")
|
||||
const globalUsed=usage(row.global_admissions,row.global_reserved_rows,row.global_reserved_bytes,row.global_compacted_admissions,row.global_archive_bytes)
|
||||
const ownerFields=[row.owner_admissions,row.owner_reserved_rows,row.owner_reserved_bytes,row.owner_compacted_admissions,row.owner_archive_bytes]
|
||||
const ownerUsed=ownerFields.every(value=>value===null)?usage(0,0,0,0,0,"owner"):usage(...ownerFields as [unknown,unknown,unknown,unknown,unknown],"owner")
|
||||
const ownerUsed=ownerFields.every(value=>value===null)?usage(0,0,0,0,0):usage(...ownerFields as [unknown,unknown,unknown,unknown,unknown])
|
||||
if(retentionDays===undefined||retentionDays<1||retentionDays>365||!globalUsed||!ownerUsed)return unavailable
|
||||
for(const field of ["attempts","rows","bytes","compactedAttempts","archiveBytes"] as const)
|
||||
if(ownerUsed.value[field]! > globalUsed.value[field]!)return unavailable
|
||||
const otherCount=globalUsed.value.compactedAttempts!-ownerUsed.value.compactedAttempts!,otherBytes=globalUsed.value.archiveBytes!-ownerUsed.value.archiveBytes!
|
||||
if(ownerUsed[field] > globalUsed[field])return unavailable
|
||||
const otherCount=globalUsed.compactedAttempts-ownerUsed.compactedAttempts,otherBytes=globalUsed.archiveBytes-ownerUsed.archiveBytes
|
||||
if(otherBytes<otherCount*40||otherBytes>otherCount*131072)return unavailable
|
||||
return Object.freeze({status:"observed",owner:Object.freeze({used:ownerUsed.value.attempts,limit:8,remaining:ownerUsed.remaining}),
|
||||
global:Object.freeze({exhausted:globalUsed.remaining===0,
|
||||
usage:admin?Object.freeze({used:globalUsed.value.attempts,limit:128,remaining:globalUsed.remaining}):null}),retentionDays})
|
||||
return Object.freeze({status:"observed",ownerFull:ownerUsed.attempts,globalFull:admin?globalUsed.attempts:null,retentionDays})
|
||||
} catch { return unavailable }
|
||||
}
|
||||
@@ -22,7 +22,7 @@ const { PARTITION_WRITER_ADVISORY_KEY } = await import("./partition-write-transa
|
||||
const { collectExpiredServerPollStorage,collectExpiredServerPollStorageForTests } = await import("./server-poll-storage-retention.js")
|
||||
const { connectProbeStorage } = await import("./server-probe-storage-connection.js")
|
||||
const { createServerPollStorage,PollStorageRefused,PollStorageUnknown } = await import("./server-poll-storage.js")
|
||||
const { readServerPollCapacity } = await import("./server-poll-capacity.js")
|
||||
const { readServerPollUsage } = await import("./server-poll-capacity.js")
|
||||
const { tickMcpWorkers } = await import("../modules/mcp/workers.js")
|
||||
const { Client } = await import("pg")
|
||||
const proof=(domain:string,value:unknown)=>privateSecretFingerprint(fingerprint(value),domain)
|
||||
@@ -380,8 +380,8 @@ try{
|
||||
const before = await usage()
|
||||
assert.equal(Number(before.compacted_admissions), 336)
|
||||
assert.equal(Number(before.admissions), 0)
|
||||
const capacity = await readServerPollCapacity(pool, first.ownerId, true)
|
||||
assert(capacity.status === "observed" && capacity.owner.remaining >= 1)
|
||||
const capacity = await readServerPollUsage(pool, first.ownerId, true)
|
||||
assert(capacity.status === "observed" && capacity.ownerFull >= 0)
|
||||
const now = Date.now()
|
||||
const scope = { receiptId: randomUUID(), executionId: randomUUID(), kind: "mcp" as const, ownerId: first.ownerId,
|
||||
issuedAt: now - 1000, expiresAt: now + 300000, bindingProof: "a".repeat(64), contextProof: "b".repeat(64) }
|
||||
|
||||
@@ -18,6 +18,7 @@ export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: tr
|
||||
const { executeDurableServerPollRest } = await import("./server-poll-rest.js")
|
||||
const ownerId = "owned-rest-authority-" + randomUUID(), name = "owned-rest-authority"
|
||||
let serverId: number | undefined, requests = 0, checkedAdmissions = 0, dispatchFailure = false
|
||||
const batchIds: number[] = []
|
||||
let app: Awaited<ReturnType<typeof import("../index.js")["buildApp"]>> | undefined
|
||||
let httpOrigin = ""
|
||||
const paths: string[] = []
|
||||
@@ -25,15 +26,17 @@ export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: tr
|
||||
requests++; paths.push(request.url ?? "")
|
||||
try {
|
||||
assert.equal(request.method, "GET")
|
||||
const rows = (await pool.query(`SELECT a.receipt_id,a.claim_token,a.claim_attempted_at,a.used_rows,
|
||||
if (!batchIds.length) {
|
||||
const rows = (await pool.query(`SELECT a.receipt_id,a.claim_token,a.claim_attempted_at,a.used_rows,
|
||||
u.admissions,u.reserved_rows,u.reserved_bytes::text FROM server_poll_storage_admissions a
|
||||
JOIN server_poll_storage_usage u ON u.scope='owner:'||a.owner_id
|
||||
JOIN server_poll_executions e USING(receipt_id)
|
||||
WHERE a.owner_id=$1 AND a.identity_kind='rest' AND e.context_proof=a.context_proof`, [ownerId])).rows
|
||||
assert.equal(rows.length, 1); assert.equal(rows[0].claim_token, null)
|
||||
assert(rows[0].claim_attempted_at); assert(Number(rows[0].used_rows) >= 1)
|
||||
assert.equal(Number(rows[0].admissions), 1); assert.equal(Number(rows[0].reserved_rows), 4019)
|
||||
assert.equal(rows[0].reserved_bytes, "8421376"); checkedAdmissions++
|
||||
assert.equal(rows.length, 1); assert.equal(rows[0].claim_token, null)
|
||||
assert(rows[0].claim_attempted_at); assert(Number(rows[0].used_rows) >= 1)
|
||||
assert.equal(Number(rows[0].admissions), 1); assert.equal(Number(rows[0].reserved_rows), 4019)
|
||||
assert.equal(rows[0].reserved_bytes, "8421376"); checkedAdmissions++
|
||||
}
|
||||
const result = request.url === "/rest/system/identity" ? { name }
|
||||
: request.url === "/rest/system/resource" ? { version: "7.synthetic", "board-name": "owned", uptime: "1h", "cpu-load": "2", "free-memory": "1024", "total-memory": "2048" }
|
||||
: request.url === "/rest/interface" ? [{ type: "ether", name: "owned-interface" }]
|
||||
@@ -107,6 +110,26 @@ export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: tr
|
||||
assert.equal(typeof reply.body.latencyMs, "number"); assert(Number(reply.body.latencyMs) >= 0)
|
||||
const serialized = JSON.stringify(reply.body)
|
||||
for (const secret of ["SYNTHETIC-USER", "SYNTHETIC-PRIVATE-PASSWORD", "rawInterfaces", "rawIpAddresses", "192.0.2.1", "owned-interface"]) assert.equal(serialized.includes(secret), false)
|
||||
if (options.httpRoute) {
|
||||
const { rows } = await pool.query(`INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl)
|
||||
SELECT $1||'-'||n,'127.0.0.1',$2,true,'SYNTHETIC-USER','SYNTHETIC-PRIVATE-PASSWORD',false,true
|
||||
FROM generate_series(1,20) AS n RETURNING id`, [ownerId, port])
|
||||
batchIds.push(...rows.map(row => Number(row.id)))
|
||||
const { rows: [mcpBefore] } = await pool.query("SELECT count(*)::int AS n FROM mcp_requests")
|
||||
for (const id of batchIds) {
|
||||
// The WebUI queues one full poll at a time.
|
||||
const result = await call(String(id), context())
|
||||
assert.equal(result.statusCode, 200, JSON.stringify(result.body))
|
||||
assert.equal(result.body.serverId, id)
|
||||
assert.equal(result.body.status, "online")
|
||||
}
|
||||
assert.equal(requests, 4 * (1 + batchIds.length))
|
||||
assert.equal(dispatchFailure, false)
|
||||
const { rows: [usage] } = await pool.query("SELECT admissions::int AS n FROM server_poll_storage_usage WHERE scope=$1", ["owner:" + ownerId])
|
||||
assert.equal(usage.n, 1 + batchIds.length)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_requests")).rows[0].n, mcpBefore.n)
|
||||
console.log("Owned WebUI HTTP poll batch:", JSON.stringify({ successfulServers: batchIds.length, ownerJournals: usage.n, mcpRequestsAdded: 0 }))
|
||||
}
|
||||
const result = { statusCode: reply.statusCode, elapsedMs, nativeGets: requests, dispatchesAfterConsumedAdmission: checkedAdmissions,
|
||||
actualRestAuthorityFactory: true, actualProductionSession: true, actualRegisteredHttpRoute: options.httpRoute === true, actualSignedJwt: options.httpRoute === true, httpAppSchedulerStarted: false, negativeStatuses: negative.map(value => value.statusCode),
|
||||
exactLegacySnapshotShape: true, privateFieldsAbsent: true, automaticReplay: false }
|
||||
@@ -114,6 +137,6 @@ export async function acceptServerPollRestAuthoritySql(options: { httpRoute?: tr
|
||||
} finally {
|
||||
await app?.close()
|
||||
listener.closeAllConnections(); if (listener.listening) await new Promise<void>(yes => listener.close(() => yes()))
|
||||
if (serverId !== undefined) await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [serverId])
|
||||
if (serverId !== undefined) await pool.query("UPDATE servers SET enabled=false WHERE id=ANY($1::bigint[])", [[serverId, ...batchIds]])
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,31 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { writeFile } from "node:fs/promises"
|
||||
import { mkdir, writeFile } from "node:fs/promises"
|
||||
import { resolve } from "node:path"
|
||||
/** Owned normal/historical SQL profiles only; fixed global quota evidence. */
|
||||
export async function acceptPollStorageGlobalCapSql(){
|
||||
/** Owned normal/historical SQL profiles only; acceptance across the former quotas. */
|
||||
export async function acceptPollStorageScaleSql(){
|
||||
assert([process.env.MMAPP_OWN_SERVER_POLL_STORAGE,process.env.MMAPP_OWN_SERVER_POLL_STORAGE_FRESH].includes("true"))
|
||||
const {pool}=await import("../db/index.js")
|
||||
const {createServerPollStorage}=await import("./server-poll-storage.js")
|
||||
const globalBefore=Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions)
|
||||
const fill=await Promise.allSettled(Array.from({length:130-globalBefore},async()=>{
|
||||
const scope={receiptId:randomUUID(),kind:"rest" as const,executionId:randomUUID(),ownerId:"owned-fill-"+randomUUID(),bindingProof:"a".repeat(64),contextProof:"b".repeat(64),issuedAt:Date.now()-1000,expiresAt:Date.now()+180000}
|
||||
const ownerId="owned-fill-"+randomUUID()
|
||||
const claim = async () => {
|
||||
const scope={receiptId:randomUUID(),kind:"rest" as const,executionId:randomUUID(),ownerId,bindingProof:"a".repeat(64),contextProof:"b".repeat(64),issuedAt:Date.now()-1000,expiresAt:Date.now()+180000}
|
||||
return createServerPollStorage({scope,connectionId:null,maxStages:8,authorize:async()=>{}}).claim({deadlineAt:Date.now()+60000},async sql=>{
|
||||
await sql.query("INSERT INTO server_poll_executions(receipt_id,identity_kind,execution_id,binding_proof,context_ciphertext,context_proof) VALUES($1,'rest',$2,$3,'SYNTHETIC',$4)",[scope.receiptId,scope.executionId,scope.bindingProof,scope.contextProof])
|
||||
})
|
||||
}))
|
||||
assert.equal(fill.filter(row=>row.status==="fulfilled").length,128-globalBefore)
|
||||
assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions),128)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n,128)
|
||||
}
|
||||
const additional = 130
|
||||
for (let index = 0; index < additional; index += 5) {
|
||||
await Promise.all(Array.from({ length: 5 }, claim))
|
||||
}
|
||||
assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope=$1",["owner:"+ownerId])).rows[0].admissions),additional)
|
||||
assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions),globalBefore + additional)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n,globalBefore + additional)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_usage WHERE scope<>'global' AND admissions=0")).rows[0].n,0)
|
||||
const evidence=await(await import("./server-poll-storage-restore-evidence.sql-helper.js")).pollStorageRestoreEvidence(pool)
|
||||
await writeFile(resolve(process.env.MCP_STATE_DIR!,"poll-storage-owned-restore-evidence.json"),JSON.stringify(evidence),{flag:"wx",mode:0o600})
|
||||
return {globalAdmissions:128,actualAdmissions:128,concurrentIndependentOwners:true,attemptsRefused:2,zeroOrphanCounters:true}
|
||||
const stateDir = resolve(process.env.MCP_STATE_DIR!)
|
||||
await mkdir(stateDir, { recursive: true, mode: 0o700 })
|
||||
await writeFile(resolve(stateDir,"poll-storage-owned-restore-evidence.json"),JSON.stringify(evidence),{flag:"wx",mode:0o600})
|
||||
return {globalAdmissions:globalBefore + additional,ownerAdmissions:additional,concurrentAdmissions:true,zeroOrphanCounters:true}
|
||||
}
|
||||
@@ -16,6 +16,13 @@ try{
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM schema_migrations")).rows[0].n,MIGRATION_MANIFEST.length)
|
||||
assert.deepEqual((await pool.query("SELECT * FROM server_poll_storage_usage")).rows,[{scope:"global",admissions:0,reserved_rows:0,reserved_bytes:0,compacted_admissions:0,archive_bytes:0}])
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_admissions")).rows[0].n,0)
|
||||
const { FIXED60_ROLE_TEMPLATE } = await import("../../scripts/writer-profile/fixed60-build-definition.js")
|
||||
const constraints = (await pool.query(`SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint
|
||||
WHERE conrelid='public.server_poll_storage_usage'::regclass AND contype='c' ORDER BY conname`)).rows
|
||||
assert.deepEqual(constraints, FIXED60_ROLE_TEMPLATE.constraints.filter(row => row.relname === "server_poll_storage_usage" && row.contype === "c")
|
||||
.map(({ conname, definition }) => ({ conname, definition })).sort((a,b) => String(a.conname).localeCompare(String(b.conname))))
|
||||
const guard = await pool.query("SELECT pg_get_functiondef('public.server_poll_storage_admission_guard()'::regprocedure) AS definition")
|
||||
assert.equal(guard.rows[0].definition, FIXED60_ROLE_TEMPLATE.functions.find(row => row.proname === "server_poll_storage_admission_guard")?.definition)
|
||||
const migration=await readFile(new URL("../../drizzle/0039_server_poll_storage.sql",import.meta.url),"utf8")
|
||||
const name="owned_poll_enroll_"+randomUUID().replaceAll("-","")
|
||||
await pool.query(`CREATE DATABASE "${name}" TEMPLATE template0`)
|
||||
@@ -68,7 +75,9 @@ try{
|
||||
await pool.query("DELETE FROM mcp_artifacts WHERE id=$1", [freshArtifactId])
|
||||
await pool.query("DELETE FROM mcp_connections WHERE id=$1", [artifactConnectionId])
|
||||
console.log("Owned fresh poll storage:",JSON.stringify({normalStartupTwice:true,migrations:MIGRATION_MANIFEST.length,globalZeroSeed:true,legacyPrefix:38,nonemptyJournalRefusedBeforeDdl:true,oldRowsPreserved:true,noForgedMarker:true,actualWorkerTickWithMcpDisabled:true,boundedRequestAuditAndArtifactRetention:true}))
|
||||
if (process.env.MMAPP_OWN_SERVER_POLL_SETTINGS_EPOCH === "true") {
|
||||
if (process.env.MMAPP_OWN_SERVER_POLL_SCALE_ONLY === "true") {
|
||||
console.log("Owned fresh poll scale:", JSON.stringify(await (await import("./server-poll-storage-fill.sql-helper.js")).acceptPollStorageScaleSql()))
|
||||
} else if (process.env.MMAPP_OWN_SERVER_POLL_SETTINGS_EPOCH === "true") {
|
||||
await (await import("../db/server-poll-settings-epoch.owned-helper.js")).acceptServerPollSettingsEpochMigrationSql(pool)
|
||||
} else if (process.env.MMAPP_OWN_SERVER_POLL_ATOMIC_MAINTENANCE === "true") {
|
||||
await (await import("./server-poll-atomic-owned-helper.js")).acceptAtomicServerPollOwned()
|
||||
@@ -89,6 +98,6 @@ try{
|
||||
if(!publicOnly&&process.env.MMAPP_OWN_SERVER_POLL_AUTHORITY_ONLY!=="true")await(await import("./server-poll-storage-execution.sql-helper.js")).acceptServerPollStorageExecutionSql()
|
||||
if(!publicOnly)await(await import("./server-poll-rest-authority.sql-helper.js")).acceptServerPollRestAuthoritySql()
|
||||
if(process.env.MMAPP_OWN_SERVER_POLL_AUTHORITY_ONLY!=="true")await(await import("../modules/mcp/server-poll-http.sql-helper.js")).acceptServerPollPublicRuntimeSql()
|
||||
console.log("Owned fresh poll quota:",JSON.stringify(await(await import("./server-poll-storage-fill.sql-helper.js")).acceptPollStorageGlobalCapSql()))
|
||||
console.log("Owned fresh poll scale:",JSON.stringify(await(await import("./server-poll-storage-fill.sql-helper.js")).acceptPollStorageScaleSql()))
|
||||
}
|
||||
}finally{await closePool()}
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { SERVER_POLL_STORAGE_POLICY as policy, PollStorageRefused, pollStoragePolicy, pollStorageScope,
|
||||
pollStorageQuotaFit, pollStorageUsageRemaining, pollStorageGcEligible, type PollStorageScope, type PollStorageGcCandidate } from "./server-poll-storage-model.js"
|
||||
validatePollStorageUsage, pollStorageGcEligible, type PollStorageScope, type PollStorageGcCandidate } from "./server-poll-storage-model.js"
|
||||
|
||||
const DAY = 86400000
|
||||
const scope: PollStorageScope = { receiptId: "5f4aaf7b-cc19-4b36-b693-5ce092a03852", executionId: "b332191d-bf58-4196-a629-f30367a48ef7",
|
||||
@@ -18,13 +18,10 @@ test("reservations cover all journal rows and metadata independently, with immut
|
||||
assert.equal(policy.attemptRows, 1 + 2008 + 2008 + 1 + 1)
|
||||
assert.equal(policy.attemptBytes, 8 * 1024 * 1024)
|
||||
assert.equal(policy.admissionBytes, 32768)
|
||||
assert.equal(policy.globalAttempts, 128); assert.equal(policy.ownerAttempts, 8)
|
||||
assert.equal(policy.globalRows, 128 * 4019); assert.equal(policy.ownerRows, 8 * 4019)
|
||||
assert.equal(policy.globalBytes, 128 * (8388608 + 32768)); assert.equal(policy.ownerBytes, 8 * (8388608 + 32768))
|
||||
const input = { ...policy, retentionDays: 30 }, cloned = pollStoragePolicy(input)
|
||||
input.retentionDays = 1
|
||||
assert.equal(cloned.retentionDays, 30); assert.equal(Object.isFrozen(cloned), true)
|
||||
for (const patch of [{ globalAttempts: 129 }, { attemptRows: 4018 }, { ownerBytes: policy.ownerBytes + 1 }, { retentionDays: 0 },
|
||||
for (const patch of [{ attemptRows: 4018 }, { attemptBytes: policy.attemptBytes + 1 }, { retentionDays: 0 },
|
||||
{ retentionDays: 366 }, { safetyWindowMs: 59999 }, { safetyWindowMs: DAY + 1 }, { retentionDays: 1.5 }]) {
|
||||
assert.throws(() => pollStoragePolicy({ ...policy, ...patch }), PollStorageRefused)
|
||||
}
|
||||
@@ -47,34 +44,16 @@ test("scope validates original identity, clones and freezes, and never invents a
|
||||
assert.equal(pollStorageScope(scope, { now: 2000, allowExpired: true }).expiresAt, 2000)
|
||||
})
|
||||
|
||||
test("quota checks exact capacity and cannot refund admission allowance to fit an extra attempt", () => {
|
||||
assert.equal(pollStorageQuotaFit(usage(127), usage(7)), true)
|
||||
assert.equal(pollStorageQuotaFit(usage(128), empty), false)
|
||||
assert.equal(pollStorageQuotaFit(usage(8), usage(8)), false)
|
||||
for (const dimension of ["bytes", "rows", "attempts"] as const) {
|
||||
assert.equal(pollStorageQuotaFit({ ...usage(127), [dimension]: usage(127)[dimension] + 1 }, empty), false)
|
||||
assert.equal(pollStorageQuotaFit(usage(127), { ...usage(7), [dimension]: usage(7)[dimension] + 1 }), false)
|
||||
for (const bad of [-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, "0", undefined]) {
|
||||
assert.equal(pollStorageQuotaFit({ ...empty, [dimension]: bad } as typeof empty, empty), false)
|
||||
test("exact accounting accepts past quotas and rejects forged totals", () => {
|
||||
for (const attempts of [0, 8, 20, 130, 1000]) {
|
||||
const value = usage(attempts)
|
||||
assert.equal(validatePollStorageUsage(value).attempts, attempts)
|
||||
for (const dimension of ["bytes", "rows", "attempts"] as const) {
|
||||
for (const invalid of [-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, "0", undefined, value[dimension] + 1])
|
||||
assert.throws(() => validatePollStorageUsage({ ...value, [dimension]: invalid }), PollStorageRefused)
|
||||
}
|
||||
}
|
||||
assert.equal(pollStorageQuotaFit({ ...usage(127), bytes: policy.globalBytes - policy.attemptBytes }, empty), false)
|
||||
assert.equal(pollStorageQuotaFit(empty, usage(1)), false)
|
||||
assert.equal(pollStorageQuotaFit({ ...empty, bytes: Number.MAX_SAFE_INTEGER }, empty), false)
|
||||
})
|
||||
|
||||
test("quota refuses partial, undercharged and mismatched reservation counters", () => {
|
||||
const malformed = [{ attempts: 1 }, { bytes: policy.attemptBytes, rows: policy.attemptRows },
|
||||
{ ...usage(1), bytes: policy.attemptBytes }, { ...usage(1), bytes: usage(1).bytes - 1 },
|
||||
{ ...usage(1), rows: policy.attemptRows - 1 }, { ...usage(1), rows: policy.attemptRows + 1 },
|
||||
{ ...usage(1), attempts: 2 }, { ...empty, bytes: 1 }, { ...empty, rows: 1 },
|
||||
{ ...usage(1), bytes: usage(1).bytes + 1 }, { ...usage(1), extra: true }]
|
||||
for (const value of malformed) {
|
||||
assert.equal(pollStorageQuotaFit(value as typeof empty, empty), false)
|
||||
assert.equal(pollStorageQuotaFit(usage(7), value as typeof empty), false)
|
||||
}
|
||||
assert.equal(pollStorageQuotaFit(usage(7), usage(7)), true)
|
||||
assert.equal(pollStorageQuotaFit(empty, empty), true)
|
||||
assert.throws(() => validatePollStorageUsage({ ...empty, extra: true } as typeof empty), PollStorageRefused)
|
||||
})
|
||||
|
||||
test("GC is strictly after expiry plus retention/safety and persisted gcNotBefore", () => {
|
||||
@@ -86,38 +65,17 @@ test("GC is strictly after expiry plus retention/safety and persisted gcNotBefor
|
||||
assert.equal(pollStorageGcEligible(candidate({ scope: { ...scope, kind: "mcp" }, mcpTerminal: true }), policy, boundary + 1), true)
|
||||
})
|
||||
|
||||
test("336 paid hourly histories and one heavy poll fit unchanged owner bytes and rows",()=>{
|
||||
const retained=compactUsage(1,336)
|
||||
assert(retained.bytes<policy.ownerBytes);assert(retained.rows<policy.ownerRows)
|
||||
assert.equal(pollStorageQuotaFit(retained,retained),true)
|
||||
assert.equal(pollStorageUsageRemaining(retained,"owner"),3)
|
||||
assert.equal(pollStorageUsageRemaining(usage(8),"owner"),0,"Unresolved full reservations are not compacted or refunded by arithmetic")
|
||||
assert.equal(pollStorageQuotaFit(usage(128),retained),false,"Owner history cannot exceed the global compacted ledger")
|
||||
})
|
||||
|
||||
test("compacted accounting validates the exact optional pair, encoded bounds and opaque extras",()=>{
|
||||
const good=compactUsage(0,1,40)
|
||||
assert.equal(pollStorageQuotaFit(good,good),true)
|
||||
assert.equal(pollStorageQuotaFit(compactUsage(0,1,131072),compactUsage(0,1,131072)),true)
|
||||
assert.deepEqual(validatePollStorageUsage(good),good)
|
||||
assert.deepEqual(validatePollStorageUsage(compactUsage(20,336,131072)),compactUsage(20,336,131072))
|
||||
const {archiveBytes:_bytes,...missingArchive}=good,{compactedAttempts:_count,...missingCount}=good
|
||||
for(const value of [missingArchive,missingCount,{...good,archiveBytes:undefined},{...good,compactedAttempts:undefined},
|
||||
compactUsage(0,1,39),compactUsage(0,1,131073),{...good,bytes:good.bytes-1},{...good,rows:good.rows+1},
|
||||
{...good,compactedAttempts:-0},{...good,archiveBytes:NaN},{...good,opaque:true},
|
||||
{...usage(0),compactedAttempts:0,archiveBytes:1},compactUsage(0,Number.MAX_SAFE_INTEGER,40)]){
|
||||
assert.equal(pollStorageQuotaFit(value as typeof good,value as typeof good),false)
|
||||
assert.equal(pollStorageUsageRemaining(value as typeof good,"owner"),undefined)
|
||||
assert.throws(() => validatePollStorageUsage(value as typeof good), PollStorageRefused)
|
||||
}
|
||||
assert.equal(pollStorageQuotaFit({...empty,compactedAttempts:0,archiveBytes:0},empty),true)
|
||||
assert.equal(pollStorageQuotaFit(compactUsage(0,1,41),compactUsage(0,1,40)),false,"No other compact admission can own the unexplained byte")
|
||||
})
|
||||
|
||||
test("free heavy slots do not imply another full byte/row reservation fits",()=>{
|
||||
const owner=compactUsage(0,2000,40),global=compactUsage(0,32600,40)
|
||||
assert(owner.bytes<=policy.ownerBytes);assert(global.bytes<=policy.globalBytes)
|
||||
assert.equal(pollStorageUsageRemaining(owner,"owner"),0)
|
||||
assert.equal(pollStorageUsageRemaining(global,"global"),0)
|
||||
assert.equal(pollStorageQuotaFit(global,owner),false)
|
||||
assert.equal(pollStorageUsageRemaining(compactUsage(0,2056,40),"owner"),undefined)
|
||||
})
|
||||
|
||||
test("retention increases, persisted retention/safety, recent stages and long original authority all delay GC", () => {
|
||||
|
||||
@@ -11,20 +11,11 @@ export interface PollStoragePolicy {
|
||||
attemptBytes: number
|
||||
admissionBytes: number
|
||||
attemptRows: number
|
||||
globalAttempts: number
|
||||
ownerAttempts: number
|
||||
globalBytes: number
|
||||
ownerBytes: number
|
||||
globalRows: number
|
||||
ownerRows: number
|
||||
retentionDays: number
|
||||
safetyWindowMs: number
|
||||
}
|
||||
export const SERVER_POLL_STORAGE_POLICY: Readonly<PollStoragePolicy> = Object.freeze({
|
||||
attemptBytes: ATTEMPT_BYTES, admissionBytes: ADMISSION_BYTES, attemptRows: ATTEMPT_ROWS,
|
||||
globalAttempts: 128, ownerAttempts: 8,
|
||||
globalBytes: 128 * (ATTEMPT_BYTES + ADMISSION_BYTES), ownerBytes: 8 * (ATTEMPT_BYTES + ADMISSION_BYTES),
|
||||
globalRows: 128 * ATTEMPT_ROWS, ownerRows: 8 * ATTEMPT_ROWS,
|
||||
retentionDays: 14, safetyWindowMs: 60000,
|
||||
})
|
||||
|
||||
@@ -40,7 +31,7 @@ const days = (value: unknown): value is number => integer(value) && value >= 1 &
|
||||
const uuid = (value: unknown): value is string => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
|
||||
const hash = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{64}$/.test(value)
|
||||
|
||||
/** Trusted composition only. Fixed reservations/caps cannot be weakened by a
|
||||
/** Trusted composition only. Per-poll charges cannot be changed by a
|
||||
* caller; only retention and its safety window are configurable. */
|
||||
export function pollStoragePolicy(raw: unknown = SERVER_POLL_STORAGE_POLICY): Readonly<PollStoragePolicy> {
|
||||
if (!record(raw) || Object.keys(raw).some(key => !Object.hasOwn(SERVER_POLL_STORAGE_POLICY, key))) refuse()
|
||||
@@ -74,7 +65,7 @@ export function pollStorageScope(raw: unknown, options: { now: number; allowExpi
|
||||
}
|
||||
|
||||
export interface PollStorageUsage { attempts: number; bytes: number; rows: number; compactedAttempts?: number; archiveBytes?: number }
|
||||
function usage(raw: PollStorageUsage) {
|
||||
export function validatePollStorageUsage(raw: PollStorageUsage) {
|
||||
if (!record(raw)) refuse()
|
||||
const compact = Object.hasOwn(raw,"compactedAttempts"), archive = Object.hasOwn(raw,"archiveBytes")
|
||||
const keys = Object.keys(raw).sort().join(",")
|
||||
@@ -87,33 +78,6 @@ function usage(raw: PollStorageUsage) {
|
||||
if (!integer(expectedRows) || !integer(expectedBytes) || raw.rows !== expectedRows || raw.bytes !== expectedBytes) refuse()
|
||||
return { ...raw, compactedAttempts:count, archiveBytes:encoded }
|
||||
}
|
||||
/** Available NEW full reservations under every unchanged cap. SQL aggregate
|
||||
* equality and all retained charge MACs must be checked by the admission owner;
|
||||
* these arithmetic checks cannot authenticate compaction or free UNKNOWN. */
|
||||
export function pollStorageUsageRemaining(raw: PollStorageUsage, scope: "global"|"owner", rawPolicy:PollStoragePolicy=SERVER_POLL_STORAGE_POLICY):number|undefined {
|
||||
try {
|
||||
const policy=pollStoragePolicy(rawPolicy), value=usage(raw)
|
||||
if(scope!=="global"&&scope!=="owner")refuse()
|
||||
const attempts=scope==="global"?policy.globalAttempts:policy.ownerAttempts
|
||||
const bytes=scope==="global"?policy.globalBytes:policy.ownerBytes, rows=scope==="global"?policy.globalRows:policy.ownerRows
|
||||
if(value.attempts>attempts||value.bytes>bytes||value.rows>rows)refuse()
|
||||
return Math.min(attempts-value.attempts,Math.floor((bytes-value.bytes)/(policy.attemptBytes+policy.admissionBytes)),Math.floor((rows-value.rows)/policy.attemptRows))
|
||||
}catch{return undefined}
|
||||
}
|
||||
/** Exact counters, including full reservations and paid retained archives. */
|
||||
export function pollStorageQuotaFit(globalUsage: PollStorageUsage, ownerUsage: PollStorageUsage,
|
||||
rawPolicy: PollStoragePolicy = SERVER_POLL_STORAGE_POLICY): boolean {
|
||||
try {
|
||||
const policy = pollStoragePolicy(rawPolicy)
|
||||
const global=usage(globalUsage),owner=usage(ownerUsage)
|
||||
return (pollStorageUsageRemaining(global,"global",policy)??0)>0 && (pollStorageUsageRemaining(owner,"owner",policy)??0)>0
|
||||
&& owner.attempts<=global.attempts && owner.bytes<=global.bytes && owner.rows<=global.rows
|
||||
&& owner.compactedAttempts<=global.compactedAttempts && owner.archiveBytes<=global.archiveBytes
|
||||
&& global.archiveBytes-owner.archiveBytes >= (global.compactedAttempts-owner.compactedAttempts)*40
|
||||
&& global.archiveBytes-owner.archiveBytes <= (global.compactedAttempts-owner.compactedAttempts)*131072
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
export interface PollStorageGcCandidate {
|
||||
scope: PollStorageScope
|
||||
lastActivityAt: number
|
||||
|
||||
@@ -15,10 +15,16 @@ try{
|
||||
const actual=await pollStorageRestoreEvidence(pool)
|
||||
assert.deepEqual(actual,expected,"Every poll admission/token/ciphertext/stage/quarantine/counter must survive actual terminal restore byte-for-byte in canonical data form")
|
||||
const counts=(await pool.query("SELECT(SELECT count(*) FROM server_poll_storage_admissions)::int AS actual,admissions::int AS heavy,compacted_admissions::int AS compacted,(admissions+compacted_admissions)::int AS charged FROM server_poll_storage_usage WHERE scope='global'")).rows[0]
|
||||
assert.equal(counts.actual,counts.charged);assert.equal(counts.heavy,128)
|
||||
assert.equal(counts.actual,counts.charged);assert(counts.heavy>=130)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_usage u WHERE u.scope<>'global' AND (u.admissions<>(SELECT count(*) FROM server_poll_storage_admissions a WHERE u.scope='owner:'||a.owner_id AND a.storage_state='full') OR u.compacted_admissions<>(SELECT count(*) FROM server_poll_storage_admissions a WHERE u.scope='owner:'||a.owner_id AND a.storage_state='compacted'))")).rows[0].n,0)
|
||||
const fresh={receiptId:randomUUID(),kind:"rest" as const,executionId:randomUUID(),ownerId:"owned-after-restore-"+randomUUID(),bindingProof:"a".repeat(64),contextProof:"b".repeat(64),issuedAt:Date.now()-1000,expiresAt:Date.now()+60000}
|
||||
await assert.rejects(createServerPollStorage({scope:fresh,connectionId:null,maxStages:8,authorize:async()=>{}}).claim({deadlineAt:Date.now()+10000},async()=>assert.fail("Restored global quota must prevent any new anchor")),PollStorageRefused)
|
||||
assert.deepEqual(await pollStorageRestoreEvidence(pool),expected,"Refused fresh admission must not alter restored counters or spend an extra token")
|
||||
console.log("Owned poll storage AFTER terminal restore:",JSON.stringify({tablesCompared:Object.keys(POLL_STORAGE_TABLE_KEYS).length,exactClaimTokensAndCiphertextHashes:true,microsecondsPreserved:true,actualAdmissions:counts.actual,chargedAdmissions:counts.charged,heavyAdmissions:counts.heavy,compactedAdmissions:counts.compacted,allOwnerCountersReconciled:true,restoredGlobalQuotaStillEnforced:true,refusedAttemptChangesNoRows:true,newNativeDispatches:0,productionDatabaseTouched:false}))
|
||||
const binding = {scope:fresh,connectionId:null,maxStages:8,authorize:async()=>{}}
|
||||
await createServerPollStorage(binding).claim({deadlineAt:Date.now()+10000}, async sql => {
|
||||
await sql.query("INSERT INTO server_poll_executions(receipt_id,identity_kind,execution_id,binding_proof,context_ciphertext,context_proof) VALUES($1,'rest',$2,$3,'SYNTHETIC',$4)", [fresh.receiptId,fresh.executionId,fresh.bindingProof,fresh.contextProof])
|
||||
})
|
||||
const afterAdmission = await pollStorageRestoreEvidence(pool)
|
||||
assert.equal(afterAdmission.tables.server_poll_storage_admissions.rows, counts.actual + 1)
|
||||
await assert.rejects(createServerPollStorage(binding).claim({deadlineAt:Date.now()+10000},async()=>assert.fail("Spent admission cannot create another anchor")),PollStorageRefused)
|
||||
assert.deepEqual(await pollStorageRestoreEvidence(pool),afterAdmission,"Rejected replay cannot change restored counters")
|
||||
console.log("Owned poll storage AFTER terminal restore:",JSON.stringify({tablesCompared:Object.keys(POLL_STORAGE_TABLE_KEYS).length,exactClaimTokensAndCiphertextHashes:true,microsecondsPreserved:true,actualAdmissions:counts.actual,chargedAdmissions:counts.charged,heavyAdmissions:counts.heavy,compactedAdmissions:counts.compacted,allOwnerCountersReconciled:true,freshAdmissionAfterRestore:true,refusedReplayChangesNoRows:true,newNativeDispatches:0,productionDatabaseTouched:false}))
|
||||
}finally{await closePool()}
|
||||
@@ -106,10 +106,10 @@ try{
|
||||
await assert.rejects(store.write(options(),sql=>sql.query("INSERT INTO server_poll_intents(receipt_id,stage,before_proof,effect_proof,intent_proof) VALUES($1,'native.resource',$2,$2,$2)",[value.receiptId,proof])),PollStorageRefused)
|
||||
cases.push("two-phase claim, exact reservation, durable spent identity, normalized activity, plan stage cap and idempotent quarantine actual-row metering")
|
||||
|
||||
const owner="concurrent-"+randomUUID(),claims=await Promise.allSettled(Array.from({length:10},async()=>{const s=scope(owner);return createServerPollStorage(binding(s)).claim(options(),sql=>anchor(sql,s))}))
|
||||
assert.equal(claims.filter(row=>row.status==="fulfilled").length,8)
|
||||
assert.deepEqual(await usage(owner),{admissions:8,reserved_rows:8*4019,reserved_bytes:String(8*8421376)})
|
||||
cases.push("ten concurrent independent factories atomically admit eight owner attempts, refuse two, never partially charge counters")
|
||||
const owner="concurrent-"+randomUUID(),claims=await Promise.allSettled(Array.from({length:20},async()=>{const s=scope(owner);return createServerPollStorage(binding(s)).claim(options(),sql=>anchor(sql,s))}))
|
||||
assert.equal(claims.filter(row=>row.status==="fulfilled").length,20)
|
||||
assert.deepEqual(await usage(owner),{admissions:20,reserved_rows:20*4019,reserved_bytes:String(20*8421376)})
|
||||
cases.push("twenty concurrent attempts for one owner retain exact charges")
|
||||
|
||||
const uncertain=scope(),b=binding(uncertain);let loss=true,callbacks=0
|
||||
const lost=createServerPollStorageForTests(b,{now:Date.now,async connect(opts){const c=await connectProbeStorage(opts);return {release:v=>c.release(v),async query(text,values,queryOptions){const result=await c.query(text,values,queryOptions);if(text==="COMMIT"&&loss){loss=false;throw Error("SYNTHETIC lost admission commit acknowledgement")};return result}}}})
|
||||
@@ -181,41 +181,31 @@ try{
|
||||
cases.push("actual existing worker tick collects an eligible original terminal poll admission and refunds quota while MCP is disabled")
|
||||
await (await import("./server-poll-storage-execution.sql-helper.js")).acceptServerPollStorageExecutionSql()
|
||||
cases.push("actual quota-bound full production poll: all four native GETs observe committed consumed admission, every maintenance publication/ACK metered, known replay no new native or quota")
|
||||
const globalBefore=Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions)
|
||||
const fill=await Promise.allSettled(Array.from({length:130-globalBefore},async()=>{const s=scope();return createServerPollStorage(binding(s)).claim({deadlineAt:Date.now()+60000},sql=>anchor(sql,s))}))
|
||||
assert.equal(fill.filter(row=>row.status==="fulfilled").length,128-globalBefore)
|
||||
assert.equal(Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions),128)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM server_poll_storage_usage WHERE scope<>'global' AND admissions=0")).rows[0].n,0,"Refused owner reservations leave no zero counter rows")
|
||||
cases.push("global 128-attempt cap holds across independent owners and concurrent actual commits; failed admissions leave no orphan counters")
|
||||
{
|
||||
const {readServerPollCapacity}=await import("./server-poll-capacity.js")
|
||||
const fullOwner=(await pool.query("SELECT scope FROM server_poll_storage_usage WHERE scope<>'global' AND admissions=8 LIMIT 1")).rows[0]
|
||||
assert(fullOwner)
|
||||
const ownerId=String(fullOwner.scope).slice("owner:".length)
|
||||
const before=(await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows
|
||||
const readOnly=await pool.connect()
|
||||
try{
|
||||
await readOnly.query("BEGIN READ ONLY")
|
||||
const capacity=await readServerPollCapacity(readOnly,ownerId,true)
|
||||
assert.equal(capacity.status,"observed")
|
||||
if(capacity.status!=="observed")assert.fail("Expected actual full retained capacity")
|
||||
assert.deepEqual(capacity.owner,{used:8,limit:8,remaining:0})
|
||||
assert.deepEqual(capacity.global,{exhausted:true,usage:{used:128,limit:128,remaining:0}})
|
||||
const privateCapacity=await readServerPollCapacity(readOnly,ownerId,false)
|
||||
assert.equal(privateCapacity.status,"observed")
|
||||
if(privateCapacity.status!=="observed")assert.fail("Expected scoped private capacity")
|
||||
assert.deepEqual(privateCapacity.global,{exhausted:true,usage:null})
|
||||
assert.equal(JSON.stringify(privateCapacity).includes(ownerId),false)
|
||||
const emptyOwner=await readServerPollCapacity(readOnly,"unallocated-"+randomUUID(),false)
|
||||
assert.equal(emptyOwner.status,"observed")
|
||||
if(emptyOwner.status!=="observed")assert.fail("Expected unallocated owner capacity")
|
||||
assert.deepEqual(emptyOwner.owner,{used:0,limit:8,remaining:8})
|
||||
assert.equal(emptyOwner.global.exhausted,true)
|
||||
await readOnly.query("COMMIT")
|
||||
}finally{readOnly.release()}
|
||||
assert.deepEqual((await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows,before)
|
||||
cases.push("portal retained capacity uses real READ ONLY snapshot of owner8/global128, hides non-admin global numbers, never claims unallocated owner bypasses full global cap, and changes no quota row")
|
||||
const globalBefore = Number((await pool.query("SELECT admissions FROM server_poll_storage_usage WHERE scope='global'")).rows[0].admissions)
|
||||
const ownerId = "scale-" + randomUUID()
|
||||
for (let n = globalBefore; n < 130; n += 1) {
|
||||
const attempt = scope(ownerId)
|
||||
await createServerPollStorage(binding(attempt)).claim(options(), sql => anchor(sql, attempt))
|
||||
}
|
||||
const { readServerPollUsage } = await import("./server-poll-capacity.js")
|
||||
const before = (await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows
|
||||
const readOnly = await pool.connect()
|
||||
try {
|
||||
await readOnly.query("BEGIN READ ONLY")
|
||||
const usage = await readServerPollUsage(readOnly, ownerId, true)
|
||||
assert.equal(usage.status, "observed")
|
||||
if (usage.status !== "observed") assert.fail("Expected observed journal usage")
|
||||
assert.equal(usage.ownerFull, 130 - globalBefore)
|
||||
assert.equal(usage.globalFull, 130)
|
||||
const privateUsage = await readServerPollUsage(readOnly, ownerId, false)
|
||||
assert.deepEqual(privateUsage, { ...usage, globalFull: null })
|
||||
assert.equal(JSON.stringify(privateUsage).includes(ownerId), false)
|
||||
const emptyOwner = await readServerPollUsage(readOnly, "unallocated-" + randomUUID(), false)
|
||||
assert.deepEqual(emptyOwner, { ...privateUsage, ownerFull: 0 })
|
||||
await readOnly.query("COMMIT")
|
||||
} finally { readOnly.release() }
|
||||
assert.deepEqual((await pool.query("SELECT * FROM server_poll_storage_usage ORDER BY scope")).rows, before)
|
||||
cases.push("historical journals coexist with over 128 full admissions and read-only usage counts")
|
||||
const evidence=await(await import("./server-poll-storage-restore-evidence.sql-helper.js")).pollStorageRestoreEvidence(pool)
|
||||
await writeFile(resolve(process.env.MCP_STATE_DIR!,"poll-storage-owned-restore-evidence.json"),JSON.stringify(evidence),{flag:"wx",mode:0o600})
|
||||
console.log("Owned poll storage SQL:",JSON.stringify({cases:cases.length,names:cases,historicalPrefix39:39,currentMigrations:MIGRATION_MANIFEST.length,actualMigrationFileStagedForOwnedHistoricalFixtures:true,allFileStatementsAndRealTerminalMarker:true,historicalRowsAndHashesPreserved:true,realPgTransactions:true,realQuotaTriggers:true,historicalFixtureBeforeGuards:true,providerOrClockOverrides:false,simulatedCommitAckLossAfterRealCommit:true,publicRoutesRegistered:false,journalAdapterIntegrated:true,productionDatabaseTouched:false,externalNetwork:false}))
|
||||
|
||||
@@ -38,6 +38,19 @@ else {
|
||||
try {
|
||||
await initDatabase();await app.listen({host:"127.0.0.1",port:0})
|
||||
serverId=Number((await pool.query("INSERT INTO servers(name,host,port,use_ssl,enabled,username,password,updated_at) VALUES($1,'127.0.0.1',$2,false,true,'fixture','fixture',$3) RETURNING id",[prefix+"server",address.port,new Date(Date.now()-3_600_000).toISOString()])).rows[0].id)
|
||||
const sampleUrl = `/traffic/servers/${serverId}/live?once=1`
|
||||
const beforeSample = nativeRequests
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1,ether2")).statusCode, 400)
|
||||
assert.equal(nativeRequests, beforeSample)
|
||||
const sample = await app.inject(sampleUrl + "&iface=ether1")
|
||||
assert.equal(sample.statusCode, 200)
|
||||
assert.equal(sample.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(sample.json(), { rxMbps: 0, txMbps: 0, at: sample.json().at, timestampKind: "backend-receipt" })
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
mode = "malformed"
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1")).statusCode, 503)
|
||||
mode = "zero"
|
||||
cases += 3
|
||||
let stream=await open(),event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);assert.equal(event?.data.timestampKind,"backend-receipt");stream.close();cases++
|
||||
for(const kind of ["empty","malformed","partial"]){mode=kind;two=kind==="partial";stream=await open();event=await stream.next();assert.equal(event?.event,"error");stream.close();cases++}
|
||||
mode="fallback";two=true;stream=await open();event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);stream.close();cases++
|
||||
|
||||
@@ -48,12 +48,14 @@ const TYPE_LABELS: Record<ServerType, string> = {
|
||||
"jump-host": "JumpHost",
|
||||
"exit-node": "Exit Node",
|
||||
"home-router": "Home Router",
|
||||
"ix-node": "IX Node",
|
||||
}
|
||||
|
||||
const TYPE_VARIANTS: Record<ServerType, BadgeProps["variant"]> = {
|
||||
"jump-host": "primary-light",
|
||||
"exit-node": "info-light",
|
||||
"home-router": "success-light",
|
||||
"ix-node": "info-light",
|
||||
}
|
||||
|
||||
function rosVer(os: string): number {
|
||||
|
||||
@@ -46,7 +46,7 @@ export interface UptimeResourceRow {
|
||||
temp?: number
|
||||
}
|
||||
|
||||
function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" }) {
|
||||
function TypeChip({ type }: { type: import("@mmapp/contracts/servers").ServerType }) {
|
||||
return (
|
||||
<span className={cn(
|
||||
"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold border shrink-0",
|
||||
@@ -56,7 +56,7 @@ function TypeChip({ type }: { type: "jump-host" | "exit-node" | "home-router" })
|
||||
? "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20"
|
||||
: "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20",
|
||||
)}>
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : "EN"}
|
||||
{type === "jump-host" ? "JH" : type === "home-router" ? "HR" : type === "ix-node" ? "IX" : "EN"}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import { PageHeader } from "@/components/page-header"
|
||||
import { DatabaseRestore } from "./database-restore"
|
||||
import { PlanReview } from "./plan-review"
|
||||
import { ArtifactDownloads } from "./artifact-downloads"
|
||||
import { PollStorageCapacity } from "./poll-storage-capacity"
|
||||
import { PollStorageUsage } from "./poll-storage-capacity"
|
||||
import { BridgeVlanWorkflow } from "./bridge-vlan-workflow"
|
||||
import { ObjectPermissionPreview, PolicyPreviewDecision } from "./object-permission-preview"
|
||||
import { Frame, FrameHeader, FrameTitle, FrameDescription, FramePanel } from "@/components/reui/frame"
|
||||
@@ -499,7 +499,7 @@ function RoutingProfiles({ api }: { api: McpApi }) {
|
||||
}
|
||||
function Overview({ api }: { api: McpApi }) {
|
||||
const query = useQuery(useCallback(signal => api.overview(signal), [api]))
|
||||
return <Panel title="Управление AI-доступом" description={query.data ? "Последнее обновление: " + date(query.data.observedAt) : "Загрузка состояния"} actions={can("mm:mcp:pause") && <Button variant="outline" onClick={() => { if (window.confirm("Остановить новые обращения MCP и все профили Route AI? Начатые записи будут завершены или сверены.")) void api.stopAutomation().then(query.refresh, error => toast.error(errorText(error))) }}><StopCircleIcon />Остановить автоматические изменения</Button>}><ErrorMessage message={query.error} /><div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">{Object.entries({ connections: "Подключения", calls: "Вызовы за 24 часа", errors: "Ошибки и отказы", approvals: "Ожидают подтверждения", running: "Выполняются" }).map(([key, title]) => <div key={key} className="rounded-lg border p-4"><p className="text-sm text-muted-foreground">{title}</p><p className="mt-2 text-2xl font-semibold tabular-nums">{query.data ? query.data[key as "calls"] : "—"}</p></div>)}</div><Badge variant={query.data?.enabled ? "success-light" : "warning-light"}>{query.data?.enabled ? "MCP включён" : "MCP выключен"}</Badge><p className="text-sm text-muted-foreground">Выключатель прекращает новые вызовы. Выключатель также останавливает новые решения Route AI. Отдельный профиль можно остановить на вкладке Route AI.</p><PollStorageCapacity capacity={query.error ? {status:"unavailable"} : query.data?.pollStorageCapacity} loading={!query.data && !query.error} refresh={query.refresh} /></Panel>
|
||||
return <Panel title="Управление AI-доступом" description={query.data ? "Последнее обновление: " + date(query.data.observedAt) : "Загрузка состояния"} actions={can("mm:mcp:pause") && <Button variant="outline" onClick={() => { if (window.confirm("Остановить новые обращения MCP и все профили Route AI? Начатые записи будут завершены или сверены.")) void api.stopAutomation().then(query.refresh, error => toast.error(errorText(error))) }}><StopCircleIcon />Остановить автоматические изменения</Button>}><ErrorMessage message={query.error} /><div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">{Object.entries({ connections: "Подключения", calls: "Вызовы за 24 часа", errors: "Ошибки и отказы", approvals: "Ожидают подтверждения", running: "Выполняются" }).map(([key, title]) => <div key={key} className="rounded-lg border p-4"><p className="text-sm text-muted-foreground">{title}</p><p className="mt-2 text-2xl font-semibold tabular-nums">{query.data ? query.data[key as "calls"] : "—"}</p></div>)}</div><Badge variant={query.data?.enabled ? "success-light" : "warning-light"}>{query.data?.enabled ? "MCP включён" : "MCP выключен"}</Badge><p className="text-sm text-muted-foreground">Выключатель прекращает новые вызовы. Выключатель также останавливает новые решения Route AI. Отдельный профиль можно остановить на вкладке Route AI.</p><PollStorageUsage usage={query.error ? {status:"unavailable"} : query.data?.pollStorageUsage} loading={!query.data && !query.error} refresh={query.refresh} /></Panel>
|
||||
}
|
||||
const recordQueryFilters = {
|
||||
requests: ["tool", "status", "connectionId", "serverId", "userId", "from", "to"],
|
||||
@@ -826,7 +826,7 @@ function Settings({ api }: { api: McpApi }) {
|
||||
}
|
||||
function RestCoverage({ api }: { api: McpApi }) {
|
||||
const query = useQuery(useCallback(signal => api.coverage(signal), [api])), routes = query.data?.routes ?? []
|
||||
return <Panel title="Покрытие REST через MCP" description="Сервисные сценарии проверяются отдельно от количества инструментов. Новые endpoints отслеживает автоматическая проверка реестра."><ErrorMessage message={query.error} /><div className="flex flex-wrap gap-2"><Badge variant="success-light">Сценариев с MCP: {routes.filter(route => route.status === "mediated").length}</Badge><Badge variant="info-light">Транспорт и управление доступом: {routes.filter(route => route.status === "excluded").length}</Badge><Badge variant="warning-light">Ожидают реализации: {routes.filter(route => route.status === "pending").length}</Badge></div><Grid items={routes.filter(route => route.status === "pending")} columns={[{ accessorKey: "method", header: "Метод", size: 90 }, { accessorKey: "path", header: "Незавершённый сценарий", size: 310 }, { accessorKey: "reason", header: "Что осталось", size: 400 }]} loading={!query.data && !query.error} /></Panel>
|
||||
return <Panel title="Покрытие REST через MCP" description="Сервисные сценарии проверяются отдельно от количества инструментов. Новые endpoints отслеживает автоматическая проверка реестра."><ErrorMessage message={query.error} /><div className="flex flex-wrap gap-2"><Badge variant="success-light">Сценариев с MCP: {routes.filter(route => route.status === "mediated").length}</Badge><Badge variant="info-light">Служебные маршруты: {routes.filter(route => route.status === "excluded").length}</Badge><Badge variant="warning-light">Ожидают реализации: {routes.filter(route => route.status === "pending").length}</Badge></div><Grid items={routes.filter(route => route.status === "pending")} columns={[{ accessorKey: "method", header: "Метод", size: 90 }, { accessorKey: "path", header: "Незавершённый сценарий", size: 310 }, { accessorKey: "reason", header: "Что осталось", size: 400 }]} loading={!query.data && !query.error} /></Panel>
|
||||
}
|
||||
function Consent({ api, id }: { api: McpApi; id: string }) {
|
||||
const request = useQuery(useCallback(signal => api.consentRequest(id, signal), [api, id])), connections = useQuery(useCallback(signal => api.connections(signal), [api]))
|
||||
|
||||
@@ -1,25 +1,20 @@
|
||||
import type {McpPollStorageCapacity} from "@mmapp/contracts/mcp"
|
||||
import {Badge} from "@/components/reui/badge"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import type { McpPollStorageUsage } from "@mmapp/contracts/mcp"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
export function PollStorageCapacity({capacity,loading,refresh}:{capacity?:McpPollStorageCapacity;loading:boolean;refresh:()=>void}){
|
||||
const observed=capacity?.status==="observed"?capacity:undefined
|
||||
const ownerFull=observed?.owner.remaining===0,globalFull=observed?.global.exhausted===true
|
||||
const full=ownerFull||globalFull
|
||||
export function PollStorageUsage({ usage, loading, refresh }: {
|
||||
usage?: McpPollStorageUsage; loading: boolean; refresh: () => void
|
||||
}) {
|
||||
return <section aria-label="Журнал полных опросов" className="flex flex-col gap-3 rounded-lg border p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h3 className="font-medium">Журнал полных опросов</h3>
|
||||
<div className="flex items-center gap-2"><Badge variant={!observed?"info-light":full?"warning-light":"success-light"}>{loading?"Загрузка":!observed?"Нет данных":full?"Квота заполнена":"Квота не заполнена"}</Badge><Button size="sm" variant="outline" onClick={refresh}>Обновить статус</Button></div>
|
||||
<Button size="sm" variant="outline" onClick={refresh}>Обновить статус</Button>
|
||||
</div>
|
||||
{observed?<>
|
||||
{usage?.status === "observed" ? <>
|
||||
<dl className="grid gap-3 text-sm sm:grid-cols-2">
|
||||
<div><dt className="text-muted-foreground">Ваши полные журналы</dt><dd className="font-medium tabular-nums">{observed.owner.used} / {observed.owner.limit}<span className="ml-2 font-normal text-muted-foreground">Осталось: {observed.owner.remaining}</span></dd></div>
|
||||
<div><dt className="text-muted-foreground">Полные журналы приложения</dt><dd className="font-medium tabular-nums">{observed.global.usage?<>{observed.global.usage.used} / {observed.global.usage.limit}<span className="ml-2 font-normal text-muted-foreground">Осталось: {observed.global.usage.remaining}</span></>:globalFull?"Заполнена":"Не заполнена"}</dd></div>
|
||||
<div><dt className="text-muted-foreground">Ваши полные журналы</dt><dd className="font-medium tabular-nums">{usage.ownerFull}</dd></div>
|
||||
{usage.globalFull !== null && <div><dt className="text-muted-foreground">Полные журналы приложения</dt><dd className="font-medium tabular-nums">{usage.globalFull}</dd></div>}
|
||||
</dl>
|
||||
{full&&<p role="alert" className="text-sm">{ownerFull&&globalFull?"Личная и общая квоты журнала заполнены.":ownerFull?"Личная квота журнала заполнена.":"Общая квота журнала заполнена."} Новый полный опрос не получит место. После безопасного архивирования или очистки по сроку хранения место может освободиться. Неизвестный результат сохраняет резерв; повторные попытки его не освобождают.</p>}
|
||||
<p className="text-sm text-muted-foreground">Счётчик учитывает резерв под выполнение и журналы, ожидающие архивирования. Архив сохраняет все исходные записи и продолжает занимать место. Поэтому остаток зависит и от объёма сохранённой истории.</p>
|
||||
<p className="text-sm text-muted-foreground">Срок хранения новых записей: {observed.retentionDays} дн. Существующие записи могут храниться дольше. Архивирование сохраняет исходный срок; очистка учитывает завершение операции, истечение допуска и защитный интервал.</p>
|
||||
<p className="text-xs text-muted-foreground">Состояние показано на момент обновления. Окончательный допуск проверяется при запуске.</p>
|
||||
</>:<p role="status" className="text-sm text-muted-foreground">{loading?"Проверяем заполнение журнала…":"Заполнение журнала сейчас недоступно. Свободное место не подтверждено; обновите статус позже."}</p>}
|
||||
<p className="text-sm text-muted-foreground">Срок хранения новых записей: {usage.retentionDays} дн.</p>
|
||||
</> : <p role="status" className="text-sm text-muted-foreground">{loading ? "Загружаем данные журнала…" : "Данные журнала сейчас недоступны."}</p>}
|
||||
</section>
|
||||
}
|
||||
@@ -22,7 +22,7 @@ export function NetworkMapLegend() {
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="font-medium text-muted-foreground">Тип узла</p>
|
||||
{[["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["HR", "Home Router", "var(--chart-2)"]].map(([label, name, color]) => (
|
||||
{[["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["HR", "Home Router", "var(--chart-2)"], ["IX", "IX Node", "var(--chart-4)"]].map(([label, name, color]) => (
|
||||
<span key={label} className="flex items-center gap-2"><Badge variant="secondary" style={{ color }} className="min-w-8 justify-center text-[10px]">{label}</Badge><span>{name}</span></span>
|
||||
))}
|
||||
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded-full border border-current" />WAN · аплинк</span>
|
||||
|
||||
@@ -65,6 +65,7 @@ function typeBadgeVariant(
|
||||
function typeBadgeLabel(type: ServerType): string {
|
||||
if (type === "jump-host") return "JH"
|
||||
if (type === "home-router") return "HR"
|
||||
if (type === "ix-node") return "IX"
|
||||
return "EN"
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
# IX как транзитный узел
|
||||
|
||||
**План для согласования · 23 ноября 2026 · GPT-6.2 Astra**
|
||||
|
||||
Оператор открывает IX-узел, подключает Linux-сервер, выдаёт ему конфигурацию и выбирает выход. В той же карточке он видит, подключился ли клиент, какие сети ему разрешены, каким путём действительно идёт трафик и что произойдёт при отказе. Основная единица работы с пользователем — клиентское подключение. Сегмент сохраняет роль изолированного маршрутизируемого домена.
|
||||
|
||||
## Как подключить VPS с адресом 123.123.123.123
|
||||
|
||||
Ниже показан **предлагаемый** сценарий. `123.123.123.123` — внешний адрес VPS из примера. Внутренние адреса туннеля и имена клиента иллюстративны.
|
||||
|
||||
1. Открыть **Точки обмена трафиком → pl-ix01 → Клиенты → Подключить Linux**. Ввести имя `vps-01` и внешний адрес `123.123.123.123`. Для WireGuard с переменным адресом клиента поле можно оставить пустым. Для GRE/IPsec нужны фиксированные доступные внешние адреса обеих сторон.
|
||||
2. Оставить **WireGuard** и вставить публичный ключ Linux. Альтернатива — выбрать **GRE/IPsec** и выдачу индивидуального IKEv2 PSK. Мастер подставит сегмент, публичный endpoint IX, свободные адреса туннеля и порт. В случае нескольких вариантов оператор выберет нужный. Для нового узла тот же экран предложит создать первый сегмент.
|
||||
3. Выбрать **Доступ → Интернет через этот IX**. Для ограниченного доступа выбрать **Только указанные сети** и указать назначения. Поле **Сети за клиентом** отдельно описывает, какие источники и объявления вправе использовать VPS. BGP, доступ к другим клиентам и управление RouterOS требуют отдельных разрешений. Обычному VPS достаточно адреса внутри туннеля.
|
||||
4. Нажать **Выдать доступ**. Перед кнопкой уже видны клиент, разрешения, устройства, основной и резервный выходы, а также ожидаемое влияние. Backend сохранит намерение, применит конфигурацию и перечитает её с CHR. После этого доступны пакет **Скачать для Linux** и инструкция для установки. Приватный ключ WireGuard остаётся на VPS.
|
||||
5. После установки открыть строку клиента. В ней отображаются handshake WireGuard или IKE/ESP SA, время наблюдения, RX/TX и фактический выход. **Проверить путь** показывает отдельный результат для IPv4 и IPv6. Для подтверждения пути от самого VPS мастер даёт клиентскую проверку доступности и наблюдаемого адреса выхода. Одной пробы с CHR для этого недостаточно.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
v["Linux VPS<br/>123.123.123.123"] -->|"WireGuard или GRE/IPsec"| a["pl-ix01<br/>клиент и его права"]
|
||||
a --> p{"Политика выхода"}
|
||||
p -->|"Локально"| aw["WAN первого IX"]
|
||||
p -->|"Через другой IX"| b["Второй IX"]
|
||||
p -->|"Через ExitNode"| e["arn-gw01"]
|
||||
aw --> inet["Интернет"]
|
||||
b -->|"Его WAN"| inet
|
||||
e -->|"Его WAN"| inet
|
||||
p -->|"Только внутренние сети"| private["Разрешённые префиксы"]
|
||||
```
|
||||
|
||||
Для внешнего сайта с маршрутом по умолчанию оператор видит `vps-01 → pl-ix01 → arn-gw01 → Интернет`. Для более специфичного BGP-префикса в той же карточке может быть другой путь. Второй IX на схеме — пример будущего узла.
|
||||
|
||||
## Что сейчас происходит в продукте
|
||||
|
||||
| Наблюдение | Следствие для оператора |
|
||||
| --- | --- |
|
||||
| Форма “Подключения” принимает имя интерфейса текстом. Списки путей и BGP строятся только из `site.interfaces` текущего черновика. `GET /ix/nodes` возвращает серверы из PostgreSQL. | Даже исправная CHR с `ether1` не наполняет этот список. Успешный полный опрос сам по себе форму не исправит. |
|
||||
| Новый сайт получает пустой `routerId`. Адрес `192.0.2.10` показан как placeholder. | Форма требует вручную придумать обязательный IPv4-идентификатор. |
|
||||
| Вкладка “Linux-клиенты” перечисляет внешние привязки из применённой ревизии. WireGuard уже умеет создать интерфейс и пир. Linux-шаблон использует локальный приватный ключ и `Table = off`. GRE предполагает предварительно созданные GRE и политику IPsec. | Клиента сегодня можно представить через **Конфигурация → Подключения → Внешний сервер**, сохранить, применить и скачать шаблон. Назначить одному VPS понятный профиль прав и выход из его карточки пока нельзя. |
|
||||
| Компилятор создаёт VRF, рекурсивные группы, BGP-фильтры и общие `exits` площадки. Между интерфейсами одного сегмента есть общее разрешение пересылки. `peerServerId` обозначает связь, а объекты компилируются для `site.serverId`. | Одна ссылка на ExitNode ещё не настраивает удалённый конец, обратный маршрут и NAT. Нужны двусторонний план и явная изоляция клиентов. |
|
||||
| REST уже предлагает `plan` и `apply` с проверкой ревизии, оператора и digest. MCP использует общий механизм применения. | Новый мастер может скрыть технические шаги за одной кнопкой. Обязательное подключение MCP в WebUI избыточно. |
|
||||
|
||||
В инвентаре MikrotikManager на 23 ноября, 04:48 UTC, были три JumpHost, один ExitNode `arn-gw01` и один IX `pl-ix01` (ID 5). Home Router на момент чтения отсутствовал. У IX отсутствовала отметка полного опроса, при этом каталог интерфейсов вернул `ether1`, а источник телеметрии показал его в текущей выборке и ряд прежних объектов со статусом `unknown`. Само присутствие `ether1` не доказывает, что это выделенный WAN или что его можно переместить в VRF. Примеры ниже используют этот снимок только для выбора ролей.
|
||||
|
||||
Основание в проекте — [редактор площадки](../app/(main)/ix/ix-site-editor.tsx), [форма узла](../app/(main)/ix/ix-view.tsx), [REST IX](../backend/src/routes/internet-exchange.ts), [компилятор](../backend/src/services/internet-exchange-plan.ts), [выдача Linux-конфигураций](../backend/src/services/internet-exchange-client.ts), [применение и наблюдение](../backend/src/services/internet-exchange-execution.ts).
|
||||
|
||||
## Рабочее место оператора
|
||||
|
||||
```text
|
||||
Точки обмена трафиком pl-ix01 / ix-eu [Подключить Linux]
|
||||
─────────────────────── ──────────────────────────────────────────────────
|
||||
pl-ix01 Клиенты Выходы и резерв Маршруты и BGP Узел
|
||||
Имя Туннель Доступ Выход Состояние
|
||||
vps-01 WG Интернет arn-gw01 Handshake …
|
||||
|
||||
При выборе клиента
|
||||
vps-01 · 123.123.123.123 · адрес в туннеле
|
||||
Права и сети Основной и резервный путь
|
||||
[Изменить доступ] [Сменить выход]
|
||||
[Конфиг Linux] [Проверить путь] [Отозвать…]
|
||||
```
|
||||
|
||||
На широком экране слева тот же выбор серверов, что в “Рекурсивных маршрутах”, “Фильтрах” и “Firewall”. На телефоне — штатный мобильный выбор узла. В карточку ведут и список серверов, и `/ix`. Для прямой ссылки сохраняются выбранные узел, сегмент и клиент. Существующие ссылки на сегменты продолжают открывать нужный контекст. [ServerRailLayout](../components/server-rail-layout.tsx), [рабочее место маршрутов](../app/(main)/recursive-routes/page.tsx).
|
||||
|
||||
| Раздел | Действие с экрана |
|
||||
| --- | --- |
|
||||
| **Клиенты** | Добавить, выдать конфигурацию, сменить права/выход, проверить путь, приостановить, возобновить или отозвать. Фильтр по состоянию и типу туннеля. Видны объём, время последнего обмена, применённая и ожидающая ревизии. |
|
||||
| **Выходы и резерв** | Добавить локальный WAN, другой IX или ExitNode. На карточке выхода видны транспорт, конечный WAN, IPv4/IPv6, возвращаемые клиентские сети, проба, активный путь и клиенты, которых затронет переключение. |
|
||||
| **Маршруты и BGP** | Выбрать клиента/профиль, ввести IP назначения и увидеть совпавший префикс, источник, группу и фактический next hop. Назначить правило “community или разрешённый префикс → группа шлюзов”, посмотреть принятые и отклонённые объявления с причиной. |
|
||||
| **Узел** | Инвентарь CHR с временем чтения, принадлежность интерфейсов, ASN, предложенный Router ID, сегменты, расширенные настройки и история изменений. |
|
||||
|
||||
Быстрые действия с готовым профилем — **Обновить интерфейсы**, **Проверить путь**, **Скачать публичный шаблон**. Выбор готового выхода завершается одной кнопкой **Применить** в том же окне. Для нового выхода с изменениями на двух узлах перед применением показать оба конца и затронутые подключения. Отзыв называет конкретного клиента и подтверждается явно. Повторный клик и повтор HTTP-запроса возвращают состояние той же операции.
|
||||
|
||||
Использовать установленные компоненты проекта. Список клиентов — ReUI Data Grid, подробности — боковая панель по образцу проекта, компактный выбор режима — Button Group. Зелёный статус показывать только с названием подтверждённого факта, например “Handshake 12 с назад”. Истёкшая проба, устаревший снимок и недоступный роутер имеют разные состояния. [Предпросмотр Data Grid](https://reui.io/components/data-grid?ref=mcp), [Button Group](https://reui.io/components/button-group).
|
||||
|
||||
## Что означает “выдать права”
|
||||
|
||||
У подключения есть постоянный ID, владелец сегмента, площадка, имя, транспорт, состояние и ссылка на профиль маршрутизации. При выдаче фиксируются разрешённые источники, назначения и семейства адресов, разрешение выхода в Интернет, доступ к другим клиентам и, если включён, список разрешённых BGP-анонсов. Принятые объявления, разрешённые назначения клиента и `AllowedIPs` на разных концах WG — три разных настройки. Компилятор выводит их из намерения оператора и показывает итог перед применением.
|
||||
|
||||
* **Только сети.** До перечисленных префиксов разрешена пересылка, остальной трафик отбрасывается. Подмена источника, чужие клиенты и управление CHR закрыты по умолчанию. Ограничения действуют на стороне IX, в том числе если клиент вручную изменит Linux-конфиг.
|
||||
* **Интернет.** Разрешён маршрут по умолчанию для выбранного семейства, исключаются служебные диапазоны IX и чужие сети. Доступ между конкретными клиентами или от Home Router/JH добавляется парой разрешений и обратных маршрутов.
|
||||
* **BGP-клиент.** Сессия привязана к его туннелю, ASN и адресному семейству. Импорт ограничен согласованными принадлежащими клиенту префиксами и максимальным количеством, экспорт — договорённым набором. Публичный фид и частный клиент используют разные политики.
|
||||
* **Приостановить, возобновить, отозвать.** Приостановка блокирует проход и анонсы, сохраняя профиль. После отзыва старый ключ/PSK, туннельный доступ и маршруты теряют силу. Ротация выдаёт новую версию, а аудит связывает действие, ревизию и оператора. Второй клиент со своим ключом продолжает работу.
|
||||
|
||||
Права оператора приложения проверяются отдельно. Просмотр сети использует `mm:network:read`, модификации — `mm:network:write` плюс проверку доступа к затронутым узлам. Закрытую часть конфигурации получает только оператор с правом выдачи для клиента либо сам клиент по одноразовому ограниченному по времени получению. Список клиентов, обычное чтение MCP, логи, план RouterOS и журнал ревизий возвращают только публичные поля. Для PSK хранить ссылку на защищённый секрет и его версию, исключить секрет из URL, аудита и HTTP-кэша. Утрата секрета решается ротацией.
|
||||
|
||||
**WireGuard.** Мастер резервирует адреса и подбирает порт с учётом занятых на узле. Публичный ключ VPS задаёт оператор, свой ключ генерирует IX. Пакет содержит `wg-quick` и применимые маршруты. Для полного туннеля обеспечить underlay-путь до endpoint и явно обозначенный способ сохранения управления VPS. Для выборочного режима добавить только разрешённые сети. Проверить доступ после перезагрузки Linux.
|
||||
|
||||
**GRE/IPsec.** Мастер создаёт либо принимает проверенные параметры GRE, IKEv2 в транспортном режиме, соответствующие политики и защиту от открытого GRE. Linux получает согласованный strongSwan-профиль, внутренние адреса, команды или unit для туннеля и маршруты. Проверить обе стороны при потере SA и смене PSK. Внешний IPv4, NAT и разрешения провайдера выявляются на предварительной проверке, а мастер предлагает WireGuard при неподходящих условиях.
|
||||
|
||||
## Выбор выхода и маршрутов
|
||||
|
||||
| Выбор | Прямой путь | Что делает план для обратного направления |
|
||||
| --- | --- | --- |
|
||||
| **Интернет с этого IX** | Клиент → IX → выбранный WAN | Для частного IPv4 включить целевой SNAT на фактическом WAN. Для маршрутизируемого публичного префикса или IPv6 проверить делегирование, обратный маршрут и межсетевой экран. Без подготовки IPv6 пометить его недоступным. |
|
||||
| **Через другой IX** | Клиент → IX A → согласованный транзитный туннель → IX B → его выход | На B подготовить маршрут к сети клиента через A, фильтр и выбранный внешний выход. NAT, если требуется, выполняется только на последнем выходе. Возврат и отсутствие циклов проверить на обеих сторонах. |
|
||||
| **Через ExitNode** | Клиент → IX → транзитный туннель → ExitNode → его WAN | На ExitNode явно создать или проверить peer, форвардинг, обратный маршрут и правила внешнего выхода. В действующие политики JH/других пользователей добавлять только согласованные объекты текущего подключения. |
|
||||
| **Изолированный сегмент** | Клиент → IX → разрешённая внутренняя сеть или другой разрешённый клиент | На обеих сторонах задать маршруты возврата и согласованные ACL. Отсутствие выхода означает отбрасывание внешнего трафика. Подключение Home Router/JH моделируется как доверенная связь с ограниченным импортом и экспортом. |
|
||||
|
||||
Сохранить существующую VRF сегмента и его профиль по умолчанию. Для клиентов с разными выходами требуется самостоятельный контекст выбора маршрута. Первый вариант для стенда — отдельная VRF на **отличающийся профиль маршрутизации** с выделенными логическими туннелями или VLAN на границах. Несколько клиентов могут разделять такой профиль с отдельными ACL и защитой от подмены источника. Массовая смена профиля показывает количество и имена затронутых клиентов. Операция “Сменить выход” для одного клиента переводит только его в выбранный профиль.
|
||||
|
||||
Особый случай — одноинтерфейсный CHR, где `ether1` одновременно WAN и управление. Для выхода с него предложить проверяемый обмен маршрутами между IX VRF и WAN-контекстом с разрешением только трафика профиля, обратным путём и фильтрацией. Назначение общего физического WAN целиком в IX VRF может оборвать доступ к CHR. Подтвердить вариант для RouterOS 7.24.5 отдельным тестом управления, пересылки, SNAT и обратного пути. Пока это не доказано, мастер показывает точную причину и предлагает поддерживаемый выделенный логический uplink. Выделенный интерфейс можно присоединять после проверки владельца, bridge, VRF и зависимых маршрутов. [Документация MikroTik по VRF](https://help.mikrotik.com/docs/spaces/ROS/pages/328206/Virtual%2BRouting%2Band%2BForwarding%2B-%2BVRF).
|
||||
|
||||
**Порядок выбора.** Для авторизованного источника IX выбирает его контекст, проверяет разрешённые назначения и ищет активный маршрут по наиболее длинному префиксу. Специфичный маршрут из BGP или статики направляет пакет в назначенную группу, общий маршрут — на разрешённый выход. Для частного префикса установить защитный маршрут отбрасывания, чтобы при отзыве анонса он не ушёл по публичному default. В UI выводить отдельно намерение, выбранный маршрут RIB/FIB, фактический интерфейс `immediate-gw` и время проверки.
|
||||
|
||||
**Резервирование.** Для каждой группы и семейства использовать уже имеющиеся основной и резервный next hop, закреплённые за своим интерфейсом независимые пробы и рекурсивное разрешение RouterOS. Проверять адрес за проверяемым участком, а не только ближний конец туннеля. Установить защиту от ухода самой пробы через резерв. При отказе обоих путей для частного трафика действует блокировка. Для интернет-профиля оператор может явно выбрать другой разрешённый выход. Проверять весь граф основных и резервных выходов на циклы перед применением. Переключение происходит на CHR при недоступном менеджере. После смены публичного SNAT-адреса существующие TCP-сессии могут оборваться, отдельной проверкой подтвердить новые соединения.
|
||||
|
||||
**Пример BGP.** Для демонстрационного `203.0.113.0/24` и community `65000:120` оператор выбирает группу “Через ARN”. Принятый префикс появляется в таблице нужного профиля, активный next hop переключается вместе с группой. Полученные NLRI не экспортируются другим клиентам автоматически. Существующий компилятор RouterOS уже поддерживает `set gw` на служебный адрес и ограниченную запись для разрешения этого адреса в `main`. Такой служебный маршрут показывать явно и проверять на коллизии. [Компилятор IX](../backend/src/services/internet-exchange-plan.ts), [текущие стендовые сценарии](ix.md).
|
||||
|
||||
## Инвентарь CHR и автоматический Router ID
|
||||
|
||||
* При открытии **Узел** или выборе площадки запросить инвентарь именно этой CHR через IX REST. Переиспользовать существующий сервис каталога и проверяемые чтения RouterOS. Объединить `/interface` с адресами, VRF, bridge-портами, транспортом, маршрутами underlay и владельцем привязки. Старые данные трафика подходят для истории. Для каждого интерфейса показывать имя, тип, состояние, время наблюдения и причину ограничения. Пустой результат, отказ доступа, устаревший снимок и обрыв связи различимы.
|
||||
* Выбрать либо существующий подходящий интерфейс CHR, либо **Создать управляемый туннель**. В маршрутах предлагать только привязки, пригодные для роли. Подтверждать устройство, имя, принадлежность и используемые адреса повторным чтением перед записью. После смены узла сбросить старый выбор и игнорировать запоздалый ответ предыдущего запроса. [Каталог интерфейсов](../backend/src/routes/users.ts), [чтение перед применением](../backend/src/services/internet-exchange-execution.ts).
|
||||
* Сохранённый Router ID площадки имеет приоритет. Для новой площадки backend определяет домен маршрутизации и опрашивает эффективные BGP/OSPF Router ID и `/routing/id`, включая ссылки на именованные ID. Учитывать существующие IX-ревизии, черновики и параллельные резервации. Уже используемый ID можно сохранить у той же логической площадки после сверки владения. Если нужен новый, предложить свободный IPv4 ID из настроенного инфраструктурного пула с проверкой коллизий во всех связанных доменах. При отсутствии пула мастер предлагает выделить диапазон один раз на установку. Выводить источник и допускать проверяемое ручное значение. [Разрешение идентификаторов OSPF](../backend/src/services/ospf-identity-catalog.ts).
|
||||
* Предложение в браузере предварительное. При сохранении атомарно занять ID в PostgreSQL с уникальностью по домену и ID, затем проверить актуальные данные перед применением. Повтор той же операции сохраняет ID. Параллельный запрос получает другой свободный адрес или явный конфликт ручного значения. При неполном инвентаре показывать возраст и неопределённость, разрешать сохранить черновик. Для изменения работающего ID вывести предупреждение о перезапуске BGP-сессии. Резервации освобождаются после проверенного удаления, незавершённая запись резерв удерживает.
|
||||
|
||||
## Изменения в архитектуре
|
||||
|
||||
1. **Контракт и хранение.** Расширить модель сегмента стабильными идентификаторами клиентских подключений, профилей, выходов и межузловых связей. На старте использовать существующие ревизии и эксплуатационные блокировки. Уникальные ресурсы узла (Router ID, адреса туннеля, слушающие порты) резервировать атомарно. Новые поля и миграция совместимы с уже применёнными конфигурациями. Старые привязки проецируются в карточки с исходными именами, владельцем, правами и статусом “настройка из прежней версии”. Отсутствующие данные отмечаются. Переход к новой ACL выполняется через обозримый diff. [Контракты](../packages/contracts/src/internet-exchange.ts), [хранилище ревизий](../backend/src/services/internet-exchange-store.ts).
|
||||
2. **Один сценарий изменения.** WebUI вызывает REST, MCP — зарегистрированные инструменты с его обычными разрешениями. Оба канала используют общую службу планирования и исполнения. Она вычисляет желаемую конфигурацию, зависимости, diff по каждому устройству, проверяет права, состояние и ревизии, применяет и перечитывает объекты. Для секрета — отдельная выдача после успеха. Существующие клиенты REST/MCP сохраняют свои контракты. [IX REST](../backend/src/routes/internet-exchange.ts), [IX MCP](../backend/src/modules/mcp/internet-exchange-actions.ts), [права](../backend/src/lib/permissions.ts).
|
||||
3. **Несколько устройств.** Готовить удалённый конец и обратный маршрут, затем включать пересылку от клиента последним шагом. Для промежуточной ошибки сохранять статусы каждого устройства, исходные значения и владельцев объекта. Повтор перечитывает уже выполненные шаги. При неизвестном результате интерфейс предлагает сверку и продолжение или возврат по проверенному плану. Кнопки должны показывать “Частично применено” и “Требует сверки”. Удаление клиента снимает только принадлежащие ему объекты и ключи, общий выход живёт до последней зависимости.
|
||||
4. **Границы масштаба.** Сейчас контракт допускает до двух площадок на сегмент и до 20 интерфейсов на площадку. Двадцать Linux-клиентов плюс uplink уже выходят за вторую границу при отдельном интерфейсе на клиента. Развести перечни клиентов и площадок, пагинировать каталог, пересмотреть привязанное к интерфейсам ограничение и измерить план/применение по изменённым объектам. Межузловая связь с другим IX или ExitNode имеет собственные два конца и может связывать существующие сегменты. Один общий WireGuard-интерфейс допустим для совместимых политик после проверки изоляции по ключам и адресам.
|
||||
|
||||
## Очерёдность и условия приёмки
|
||||
|
||||
| Этап | Что получит оператор | Чем подтвердим |
|
||||
| --- | --- | --- |
|
||||
| **1. Узел** | Понятная навигация, реальные интерфейсы, автозаполнение Router ID и карта занятых ресурсов. | Стенд показывает `ether1`, WG и GRE. Занятый WAN помечен с причиной. Проверить смену CHR при незавершённом запросе, отказ REST, коллизию двух параллельных выдач, сохранение Router ID после перезапуска. |
|
||||
| **2. Клиент и права** | Добавление Linux, выпуск WG и GRE/IPsec из формы, выдача/ротация/отзыв, отдельные поля доступа и маршрута. | Установить пакет, скачанный из WebUI, на Linux. Проверить реальные пакеты в обе стороны, закрытый GRE при потере SA, подмену источника и чужой префикс, запрет административных сервисов, отзыв только одного из двух клиентов. Проверить права read-only и отсутствие секретов в планах и логах. |
|
||||
| **3. Выходы и BGP** | Локальный выход, выход через вторую IX или ExitNode, смена профиля, рекурсивный резерв и объяснение пути. | Две тестовые CHR 7.24.5 плюс Linux и тестовый получатель. CHR A работает как IX, CHR B последовательно играет роли второго IX и ExitNode. Проверить каждый путь в обе стороны, внешний адрес у получателя, BGP IPv4/IPv6, переключение и возврат основного пути, отказ всех путей, отсутствие утечек в `main`, отдельные выходы для двух клиентов и изолированный режим. Для одноинтерфейсного варианта непрерывно проверять доступ к управлению CHR. |
|
||||
| **4. Совместимость и выпуск** | Старые сегменты открываются, REST и MCP показывают одно состояние. Обновлено руководство по карточке клиента. | На копии старой PostgreSQL проверить миграцию, профиль записи и ревизии. Прогнать повтор/конкуренцию/частичный сбой двух устройств, клиента из старой ревизии, 20+ клиентов с uplink, внешний путь после перезагрузки Linux. Перед тестом независимо подтвердить изолированные устройства, чтобы совпадение IP с рабочим инвентарём не привело к записи в продакшен. |
|
||||
|
||||
Стенд должен раздельно зафиксировать **конфигурацию перечитали**, **туннель поднялся**, **маршрут выбран** и **пакет дошёл и вернулся**. Для каждого транспорта и семейства сохраняются источник, назначение, активный путь, счётчики, наблюдаемый исходящий адрес и результат до, во время и после отказа. Опорные сценарии — [REST WebUI](../backend/scripts/acceptance/ix-web-rest.mts), [две CHR](../backend/scripts/acceptance/ix-two-chr.mts), [GRE и MCP](../backend/scripts/acceptance/ix-gre-mcp.mts). Практическим критерием приёмки служит выдача доступа и смена выхода одного VPS из его карточки, с проверенным результатом и работающим соседним клиентом.
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
# Точки обмена трафиком
|
||||
|
||||
В **Управление → Точки обмена трафиком** выберите транзитный IX Node, сохраните сегмент и примените план из WebUI. Черновик хранится в PostgreSQL. Запись на CHR начинается после подтверждения плана. MCP использует общий механизм применения и доступен для отдельного управления.
|
||||
|
||||
## Конфигурация сегмента
|
||||
|
||||
- **Площадка** указывает CHR, локальный ASN и Router ID. Для новой площадки предлагается свободный Router ID из `10.255.0.0/16`. Другой пул можно задать через `MMAPP_IX_ROUTER_ID_POOL`. При повторном открытии отображается сохранённый ID. Ручное значение можно указать в форме. Для одного сегмента можно указать до двух площадок.
|
||||
- **Интерфейс** связывает площадку с WireGuard, GRE/IPsec или выделенным uplink. Для подготовленного вручную интерфейса задайте комментарий `IX:<имя сегмента>`. Интерфейс не должен принадлежать другой VRF или обслуживать статический маршрут в `main`.
|
||||
- **Группа шлюзов** содержит служебный адрес, основной путь с интерфейсом, непосредственно достижимым шлюзом и контрольным адресом. У резерва другой интерфейс и своя проба. `onFailure` выбирает `block` или `segment-exit`.
|
||||
- **BGP-сосед** привязан к интерфейсу площадки. Для публичного фида правила сопоставляют community с группой. Для частного соседа задаются группа и диапазоны, принадлежащие этому подключению. По умолчанию импорт и экспорт отклоняются, если правило не совпало.
|
||||
- **Выходы** содержат ссылки на группы в порядке приоритета. NAT можно включить только на выделенном локальном IPv4-uplink.
|
||||
|
||||
Точки и адреса ниже учебные. Пример подготавливается на одной CHR, с отдельными уже настроенными транспортами и локальным uplink.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "compute",
|
||||
"sites": [{
|
||||
"serverId": 17,
|
||||
"autonomousSystem": 64512,
|
||||
"routerId": "192.0.2.17",
|
||||
"interfaces": [
|
||||
{"name": "wg-eu", "kind": "wireguard"},
|
||||
{"name": "wg-arn", "kind": "wireguard"},
|
||||
{"name": "wg-feed", "kind": "wireguard"},
|
||||
{"name": "ix-wan", "kind": "uplink", "natIpv4": true}
|
||||
],
|
||||
"groups": [
|
||||
{
|
||||
"id": "europe",
|
||||
"gateway": "198.18.0.1",
|
||||
"primary": {"interface": "wg-eu", "nextHop": "10.0.1.2", "probe": "192.0.2.101"},
|
||||
"backup": {"interface": "wg-arn", "nextHop": "10.0.2.2", "probe": "192.0.2.102"},
|
||||
"onFailure": "block"
|
||||
},
|
||||
{
|
||||
"id": "local",
|
||||
"gateway": "198.18.0.2",
|
||||
"primary": {"interface": "ix-wan", "nextHop": "10.0.3.2", "probe": "192.0.2.103"}
|
||||
}
|
||||
],
|
||||
"exits": ["local"],
|
||||
"neighbors": [{
|
||||
"id": "feed",
|
||||
"type": "public-feed",
|
||||
"address": "10.0.4.2",
|
||||
"localAddress": "10.0.4.1",
|
||||
"remoteAs": 64513,
|
||||
"binding": "wg-feed",
|
||||
"rules": [{"community": "65000:120", "group": "europe"}]
|
||||
}]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
### Доступ конечных Linux-серверов
|
||||
|
||||
1. Откройте сегмент IX и нажмите **Подключить Linux**. Выберите транспорт и выход VPS. **Только разрешённые сети** направляет в туннель выбранные префиксы, **Интернет с этого IX** выводит трафик через его WAN. Для удалённого выхода выберите конкретный ExitNode или другой IX. Менеджер использует подходящий настроенный выход либо подготовит транзит вместе с клиентом.
|
||||
2. Нажмите **Сохранить**. В окне подтверждения проверьте узлы и изменения RouterOS, затем нажмите **Подтвердить**. Кнопка **Конфиг Linux** в строке клиента выдаёт файлы из применённой ревизии. Отмена до подтверждения оставляет изменения в черновике. Его можно открыть той же кнопкой **Сохранить**.
|
||||
3. В строке клиента нажмите на название выхода, чтобы сменить маршрут или приостановить доступ. В меню действий **Проверить путь** показывает фактический шлюз, а **Отозвать доступ** удаляет клиентское подключение после подтверждения. Во вкладке **Маршрутизация** можно настроить общие выходы и резерв, интерфейсы CHR, статические маршруты и BGP.
|
||||
|
||||
- **WireGuard.** IX автоматически создаёт пару ключей Linux. После применения скачайте готовый `.conf` из карточки клиента, сохраните под исходным именем в `/etc/wireguard/` с правами `0600` и запустите `sudo wg-quick up <имя-файла-без-.conf>`. Указанный внешний IP Linux сохраняет исходный путь управления при полном туннеле. Для клиента со своей парой ключей доступен шаблон с полем для его приватного ключа.
|
||||
- **Получение WireGuard через MCP.** Вызовите `mm_wireguard_export_plan` с полями `serverId`, `interfaceName` клиента, `ixSegmentId` и `format: "peer-conf"`. После подтверждения и выполнения плана ссылка на готовый файл доступна авторизованному владельцу подключения 15 минут. Ключ находится только в скачиваемом файле.
|
||||
- **GRE/IPsec.** Укажите два фиксированных внешних IPv4-адреса. Менеджер создаёт на CHR GRE с выключенным FastPath и IKEv2/IPsec в транспортном режиме. Оператор с правами записи скачивает конфиг strongSwan с индивидуальным PSK и команды настройки Linux. Старые вручную подготовленные подключения остаются доступны по прежнему шаблону.
|
||||
|
||||
### Выход и резерв
|
||||
|
||||
**Интернет с этого IX** использует действующий WAN из `main`. WAN остаётся в своей таблице, для клиента на этом выходе добавляются отдельные правила и обратный маршрут. **Добавить удалённый выход** готовит оба конца межузлового WireGuard с возвратом и IPv4 SNAT на целевом IX или ExitNode. Такой выход доступен в карточке клиента как группа шлюзов. В конфигурации группы можно выбрать другой интерфейс резерва или взять параметры заранее подготовленного выхода.
|
||||
|
||||
При выборе **Только разрешённые сети** клиенту открываются согласованные префиксы, которые маршрутизируются внутри IX. **Проверить путь** показывает FIB и активный next hop. Доступность назначения и фактический внешний адрес проверяйте с Linux.
|
||||
|
||||
Если операция оборвалась после записи части объектов, нажмите **Сохранить** для текущей ревизии. Если обычное сравнение выявит частично применённые изменения, выберите в окне **Сверить и продолжить**. Менеджер проверяет запись о предыдущей попытке и адресатов, перечитывает CHR и предлагает план оставшихся изменений.
|
||||
|
||||
До автоматической выдачи ключей на изолированном стенде с двумя CHR RouterOS 7.24.5 проверены WireGuard и GRE/IKEv2, IPv4 TCP на локальных выходах и блокировка открытого GRE после снятия IPsec. Для выхода через ExitNode получатель увидел смену WAN второй CHR на WAN первой и обратно после восстановления туннеля. В роли второго IX та же пара передала IPv6 с сохранением адреса Linux. Стендовый BGP-анонс выбран через заданный шлюз, после отзыва активировался защитный маршрут отбрасывания. Автоматическая выдача WireGuard проверена через REST и MCP с временной PostgreSQL и имитацией RouterOS.
|
||||
|
||||
### Удаление сегмента
|
||||
|
||||
Откройте карточку сегмента, нажмите «Удалить сегмент» и подтвердите. Черновик исчезнет из списка. Для применённого сегмента WebUI показывает план очистки RouterOS. Перед удалением отключите вручную подключённые интерфейсы из этого сегмента, если WebUI сообщает об этом. Запись скрывается после проверки удаления управляемых объектов, история ревизий сохраняется.
|
||||
|
||||
## MCP и ввод в эксплуатацию
|
||||
|
||||
`mm_ix_segments_list` и `mm_ix_segment_get` читают конфигурацию и наблюдения в разрешённой области. `mm_ix_inventory_get` читает интерфейсы узла, `mm_ix_linux_path_get` показывает маршруты клиента. `mm_ix_change_plan` готовит изменение, `mm_ix_restore_plan` готовит восстановление сохранённой ревизии. Применение, сверка и журнал общие с остальными функциями MCP.
|
||||
|
||||
Перед запуском стендовых сценариев SSH задайте `MMAPP_IX_CHR_HOSTS` двумя IPv4-адресами выделенной пары и проверьте, что они отсутствуют в рабочем инвентаре.
|
||||
|
||||
Перед запуском backend оператор применяет миграцию `0058_internet_exchange.sql` штатной подготовкой базы. Для подписанного PostgreSQL-профиля используется **source59**. Он добавляет в каталог три таблицы IX, сохраняет профиль source58 как точного предшественника и связывает новый профиль с хешем миграций.
|
||||
|
||||
При переходе source58 → source59 сначала сохраните подтверждённый текущий head. После миграции примените выдачу прав и защит из `ixWriterProfileEnrollmentSql(runtimeRole, captureRole)` в отдельной предварительно допущенной транзакции оператора. `source-catalogue-inspect` проверяет фактический каталог source59 на том же источнике и наборе ролей. Штатный `upgrade` принимает независимое подтверждение `application-writer-upgrade58-to59-approval-v1`, привязанное к прежнему head и новому каталогу. Runtime допускает только профиль, соответствующий миграциям текущего выпуска. Команда `node --import tsx backend/scripts/acceptance/ix-writer-profile.mts` проверяет права, блокировку записи и каталог на своей временной базе PostgreSQL.
|
||||
|
||||
Перед включением пользовательского трафика проверьте на выделенных CHR изоляцию, работу BGP, блокировку открытого GRE, обратные маршруты и переключение при отказе всех путей. Статус «Применена» означает, что конфигурация перечитана с RouterOS. Он не подтверждает прохождение пользовательского трафика.
|
||||
|
||||
## BGP и резервирование на RouterOS 7.24.5
|
||||
|
||||
Входной фильтр выбирает группу шлюзов по BGP community. RouterOS разрешает адрес, заданный фильтром `set gw`, через таблицу `main`. Поэтому IX создаёт там один служебный маршрут на группу BGP. Он направляет разрешение обратно в VRF IX, где отдельные ICMP-пробы выбирают основной, резервный путь или отбрасывание. Полученные префиксы и маршруты пользователей остаются в VRF IX.
|
||||
|
||||
Для служебных адресов групп BGP используйте уникальные для каждой CHR адреса из `198.18.0.0/15` или `fd00:198:18::/48`. При наличии другого маршрута с тем же служебным адресом в `main` MikrotikManager отклоняет применение.
|
||||
|
||||
Сценарий `node --import tsx backend/scripts/acceptance/ix-two-chr.mts --owned-test-pair` собирает конфигурацию тем же компилятором и применяет её через SSH на двух выделенных тестовых CHR. Он проверяет принятие префикса и передачу ICMP с одного источника на обоих путях, блокирует UDP основного WireGuard-туннеля на второй CHR, проверяет переход и возврат при сохранённой BGP-сессии и удаляет временную конфигурацию. Время в отчёте измеряется от подтверждения удалённого изменения до наблюдения маршрута и включает задержки SSH.
|
||||
|
||||
Результат прогона 22 ноября 2026 года на двух CHR с RouterOS 7.24.5 stable:
|
||||
|
||||
| Проверка | Результат |
|
||||
| --- | --- |
|
||||
| eBGP и изоляция | Community `65000:120` направила `192.0.2.200/32` в заданную группу. Префикс присутствовал в VRF IX и отсутствовал в `main`. |
|
||||
| Основной путь → резерв | `immediate-gw` перешёл на второй WireGuard через 28,842 с. На обоих путях получены 3 из 3 ICMP-ответов с одного источника. |
|
||||
| Резерв → основной путь | Возврат наблюдался через 2,346 с. Получены 3 из 3 ICMP-ответов. Время запуска BGP-сессии осталось прежним. |
|
||||
| Завершение | Проверено удаление объектов тестового сценария на обеих CHR. |
|
||||
|
||||
Повторный прогон с параметром `--ipv6` на той же паре CHR 23 ноября 2026 года подтвердил приём `2001:db8:3::200/128` по eBGP, его изоляцию от `main` и по 3 из 3 ICMPv6-ответов на основном пути, на резерве и после возврата. Переход наблюдался через 23,895 с, возврат — через 10,418 с. BGP-сессия сохранилась, временные объекты на обеих CHR удалены.
|
||||
|
||||
## Применение через REST и MCP
|
||||
|
||||
Сценарий `node --import tsx backend/scripts/acceptance/ix-gre-mcp.mts --owned-test-pair` запускает отдельный MikrotikManager с временной PostgreSQL. HTTP API сохраняет черновик. MCP создаёт план, отклоняет его исполнение до явного подтверждения и после подтверждения применяет конфигурацию через RouterOS REST по HTTPS с проверкой сертификатов. Проверяются терминальный статус `applied / passed`, перечитывание обеих площадок и идемпотентный повтор `mm_change_apply`.
|
||||
|
||||
Лимит изменений MCP должен покрывать все объекты обеих площадок и запись ревизии. Штатные 10 изменений в час не покрыли двухплощадочный стендовый план. В тесте лимит 40 временно задан только проверочному подключению, подтверждение плана остаётся обязательным.
|
||||
|
||||
На двух CHR с RouterOS 7.24.5 stable 23 ноября 2026 года тот же сценарий подтвердил GRE поверх IKEv2/IPsec в режиме transport. На каждой CHR наблюдались две активные IPsec SA и 3 из 3 ответов на ICMP через VRF IX. При отключённых политиках IPsec обе стороны получили 0 из 3 ответов. После повторного включения IPsec трафик восстановился. С обеих CHR удалены временные правила, туннели, учётные записи и сертификаты, служба HTTPS возвращена в исходное состояние.
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { isTrafficLiveSample } from "@/hooks/use-traffic-live"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export interface GreTrafficTarget {
|
||||
edgeId: string
|
||||
serverId: string
|
||||
iface: string
|
||||
}
|
||||
|
||||
type Rate = { bps: number; bpsFwd: number; bpsRev: number; receivedAt: number }
|
||||
const MAX_CONCURRENT_READS = 4
|
||||
const REFRESH_MS = 8_000
|
||||
const MAX_SAMPLE_AGE_MS = 30_000
|
||||
|
||||
export function useMapGreTraffic(backendUrl: string, targets: GreTrafficTarget[]) {
|
||||
const key = JSON.stringify(targets)
|
||||
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
|
||||
|
||||
useEffect(() => {
|
||||
const scope: GreTrafficTarget[] = JSON.parse(key)
|
||||
if (!scope.length) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const run = async () => {
|
||||
if (document.hidden) {
|
||||
timer = setTimeout(run, REFRESH_MS)
|
||||
return
|
||||
}
|
||||
for (let offset = 0; offset < scope.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
|
||||
const batch = await Promise.all(scope.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ edgeId, serverId, iface }) => {
|
||||
try {
|
||||
const query = new URLSearchParams({ iface, once: "1" })
|
||||
const sample = await requestJson<unknown>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(6_000)]),
|
||||
cache: "no-store",
|
||||
})
|
||||
if (isTrafficLiveSample(sample)) {
|
||||
const bpsFwd = sample.rxMbps * 1_000_000
|
||||
const bpsRev = sample.txMbps * 1_000_000
|
||||
return { edgeId, rate: { bps: bpsFwd + bpsRev, bpsFwd, bpsRev, receivedAt: Date.now() } }
|
||||
}
|
||||
} catch {
|
||||
// One unavailable interface cannot hide readings on other links.
|
||||
}
|
||||
return { edgeId }
|
||||
}))
|
||||
if (controller.signal.aborted) return
|
||||
setSnapshot(previous => {
|
||||
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
|
||||
for (const { edgeId, rate } of batch) {
|
||||
if (rate) rates.set(edgeId, rate)
|
||||
else rates.delete(edgeId)
|
||||
}
|
||||
return { backendUrl, key, rates }
|
||||
})
|
||||
}
|
||||
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
|
||||
}
|
||||
void run()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [backendUrl, key])
|
||||
|
||||
return (edgeId: string) => {
|
||||
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
|
||||
return rate && Date.now() - rate.receivedAt <= MAX_SAMPLE_AGE_MS ? rate : undefined
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,14 @@ export interface TrafficLiveSample {
|
||||
timestampKind?: "backend-receipt"
|
||||
}
|
||||
|
||||
export function isTrafficLiveSample(value: unknown): value is TrafficLiveSample {
|
||||
const sample = value as Partial<TrafficLiveSample> | null
|
||||
return !!sample && typeof sample.rxMbps === "number" && Number.isFinite(sample.rxMbps) && sample.rxMbps >= 0 &&
|
||||
typeof sample.txMbps === "number" && Number.isFinite(sample.txMbps) && sample.txMbps >= 0 &&
|
||||
typeof sample.at === "string" && Number.isFinite(Date.parse(sample.at)) &&
|
||||
(sample.timestampKind === undefined || sample.timestampKind === "backend-receipt")
|
||||
}
|
||||
|
||||
function parseSseBlock(block: string): { event: string; data: string } {
|
||||
let event = "message"
|
||||
const dataLines: string[] = []
|
||||
@@ -90,8 +98,8 @@ export function useTrafficLive(opts: {
|
||||
if (!raw.trim()) continue
|
||||
const ev = parseSseBlock(raw)
|
||||
if (ev.event === "sample" && ev.data) {
|
||||
const parsed = JSON.parse(ev.data) as TrafficLiveSample
|
||||
if (!parsed || !Number.isFinite(parsed.rxMbps) || !Number.isFinite(parsed.txMbps) || parsed.rxMbps < 0 || parsed.txMbps < 0 || typeof parsed.at !== "string" || !Number.isFinite(Date.parse(parsed.at)) || parsed.timestampKind !== undefined && parsed.timestampKind !== "backend-receipt") {
|
||||
const parsed: unknown = JSON.parse(ev.data)
|
||||
if (!isTrafficLiveSample(parsed)) {
|
||||
throw new Error("Некорректные данные live-потока")
|
||||
}
|
||||
awaitSample()
|
||||
|
||||
@@ -34,6 +34,7 @@ export const SERVER_FILTER_FIELDS: FilterField[] = [
|
||||
{ value: "jump-host", label: "JumpHost" },
|
||||
{ value: "exit-node", label: "Exit Node" },
|
||||
{ value: "home-router", label: "Home Router" },
|
||||
{ value: "ix-node", label: "IX Node" },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { FilterQuery } from "@/components/reui/filters/filters-types"
|
||||
import { SERVER_FILTER_FIELDS } from "./server-filter-fields"
|
||||
import { serverTypeSchema } from "@mmapp/contracts/servers"
|
||||
|
||||
export type ServerTypeFilter = "all" | "jump-host" | "exit-node" | "home-router"
|
||||
export type ServerTypeFilter = "all" | import("@/lib/data").ServerType
|
||||
export const emptyServerQuery = (): FilterQuery => ({ id: "root", type: "group", combinator: "and", rules: [] })
|
||||
const types = ["jump-host", "exit-node", "home-router"]
|
||||
const types: readonly string[] = serverTypeSchema.options
|
||||
const MAX_BYTES = 8192
|
||||
const options = new Map(SERVER_FILTER_FIELDS.map(field => [field.id, new Set((field.options ?? []).map(option => option.value))]))
|
||||
const record = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
|
||||
@@ -36,10 +36,10 @@ export function patchUptimeUrl(params: URLSearchParams, changes: Record<string,
|
||||
|
||||
export type UrlSetter<T> = Dispatch<SetStateAction<T>>
|
||||
|
||||
export type ResourceTypeFilter = "all" | "jump-host" | "exit-node" | "home-router"
|
||||
export type ResourceTypeFilter = "all" | import("@mmapp/contracts/servers").ServerType
|
||||
export function readResourceUrl(params: URLSearchParams) {
|
||||
const raw = params.get("rtype")
|
||||
const valid = raw === null || ["jump-host", "exit-node", "home-router"].includes(raw)
|
||||
const valid = raw === null || ["jump-host", "exit-node", "home-router", "ix-node"].includes(raw)
|
||||
const error = !valid || ["rq", "rtype"].some(key => params.getAll(key).length > 1)
|
||||
? "В ссылке указаны неверные или повторяющиеся фильтры ресурсов." : null
|
||||
return { search: params.get("rq") ?? "", type: (valid && raw !== null ? raw : "all") as ResourceTypeFilter, error }
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
export type ServerStatus = "online" | "offline" | "degraded" | "unknown"
|
||||
export type ServerType = "jump-host" | "exit-node" | "home-router"
|
||||
export type ServerType = import("@mmapp/contracts/servers").ServerType
|
||||
|
||||
export interface WanUplink {
|
||||
id: string
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { serverTypeSchema } from "@mmapp/contracts/servers"
|
||||
import { z } from "zod"
|
||||
|
||||
const context = { id: z.string().min(1), rosId: z.string().min(1), serverId: z.string().min(1), serverName: z.string(), family: z.enum(["ip", "ip6"]) }
|
||||
@@ -19,7 +20,7 @@ export const firewallResponseSchema = z.object({
|
||||
|
||||
export const firewallServersSchema = z.array(z.object({
|
||||
id: z.number().int().positive(), name: z.string(), host: z.string(), enabled: z.boolean(), country: z.string(),
|
||||
type: z.enum(["jump-host", "exit-node", "home-router"]), site: z.string().default(""), asn: z.string().default(""),
|
||||
type: serverTypeSchema, site: z.string().default(""), asn: z.string().default(""),
|
||||
status: z.enum(["online", "offline", "degraded"]).nullable().default(null), latency: z.number().finite().nullable().default(null),
|
||||
})).refine(rows => new Set(rows.map(row => row.id)).size === rows.length)
|
||||
|
||||
|
||||
+20
-20
@@ -8,6 +8,10 @@ export interface MatchedNetflowHop {
|
||||
bytes: number
|
||||
}
|
||||
|
||||
export interface GreNetflowHop extends MatchedNetflowHop {
|
||||
exactInterface: boolean
|
||||
}
|
||||
|
||||
function ifaceNorm(s: string | undefined): string {
|
||||
return (s ?? "").trim().toLowerCase()
|
||||
}
|
||||
@@ -40,45 +44,41 @@ export function hopHasRate(h: MatchedNetflowHop | undefined): h is MatchedNetflo
|
||||
return h != null && Number.isFinite(h.bps) && h.bps > 0
|
||||
}
|
||||
|
||||
export function formatNetflowRate(hop: MatchedNetflowHop): string {
|
||||
export function formatNetflowRate<T extends Pick<MatchedNetflowHop, "bps">>(hop: T): string {
|
||||
return fmtRate(hop.bps / 1_000_000)
|
||||
}
|
||||
|
||||
export function formatNetflowDir(hop: MatchedNetflowHop): string {
|
||||
export function formatNetflowDir(hop: Pick<MatchedNetflowHop, "bpsFwd" | "bpsRev">): string {
|
||||
return `↓${fmtRate(hop.bpsFwd / 1_000_000)} ↑${fmtRate(hop.bpsRev / 1_000_000)}`
|
||||
}
|
||||
|
||||
/** GRE: сначала имя интерфейса туннеля на любом конце, иначе пара узлов. */
|
||||
/** Собственный интерфейс GRE даёт точную привязку, совпадение пары узлов — только оценку. */
|
||||
export function matchNetflowForGreEdge(
|
||||
edge: {
|
||||
tunnel: { name: string }
|
||||
tunnel: { name: string; serverId: string }
|
||||
fromServer: { id: string }
|
||||
toServer: { id: string }
|
||||
},
|
||||
hops: FlowMapHop[],
|
||||
): MatchedNetflowHop | undefined {
|
||||
): GreNetflowHop | undefined {
|
||||
const name = ifaceNorm(edge.tunnel.name)
|
||||
const fromId = String(edge.fromServer.id)
|
||||
const toId = String(edge.toServer.id)
|
||||
if (name) {
|
||||
const ifaceHits = hops.filter((h) =>
|
||||
h.kind === "iface"
|
||||
&& ifaceNorm(h.iface) === name
|
||||
&& (h.fromId === fromId || h.fromId === toId),
|
||||
)
|
||||
if (ifaceHits.length) return mergeDirected(ifaceHits, fromId)
|
||||
const greNamed = hops.filter((h) =>
|
||||
h.kind === "gre"
|
||||
&& ifaceNorm(h.iface) === name
|
||||
&& (h.fromId === fromId || h.fromId === toId || h.toId === fromId || h.toId === toId),
|
||||
)
|
||||
if (greNamed.length) return mergeDirected(greNamed, fromId)
|
||||
}
|
||||
const ownerId = edge.tunnel.serverId
|
||||
const peerId = ownerId === fromId ? toId : fromId
|
||||
const want = pairKey(fromId, toId)
|
||||
if (name) {
|
||||
const local = hops.filter((h) => h.kind === "iface" && h.fromId === ownerId && ifaceNorm(h.iface) === name)
|
||||
if (local.length) return { ...mergeDirected(local, fromId), exactInterface: true }
|
||||
const named = hops.filter((h) =>
|
||||
h.kind === "gre" && h.fromId === ownerId && h.toId === peerId && ifaceNorm(h.iface) === name,
|
||||
)
|
||||
if (named.length) return { ...mergeDirected(named, fromId), exactInterface: true }
|
||||
}
|
||||
const pairHits = hops.filter((h) =>
|
||||
h.kind === "gre" && Boolean(h.toId) && pairKey(h.fromId, h.toId) === want,
|
||||
)
|
||||
if (pairHits.length) return mergeDirected(pairHits, fromId)
|
||||
if (pairHits.length) return { ...mergeDirected(pairHits, fromId), exactInterface: false }
|
||||
return undefined
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ export const navigationItems: NavigationItem[] = [
|
||||
{ id: "recursive-routes", title: "Рекурсивные маршруты", group: "Управление", url: "/recursive-routes", icon: RouteIcon, keywords: ["recursive","route","static","маршруты"] },
|
||||
{ id: "firewall", title: "Firewall", group: "Управление", url: "/firewall", icon: ShieldIcon, keywords: ["rules","правила","брандмауэр","acl"] },
|
||||
{ id: "wireguard", title: "WireGuard", group: "Управление", url: "/wireguard", icon: ShieldCheckIcon, keywords: ["vpn","tunnel","туннель","wg"] },
|
||||
{ id: "ix", title: "Точки обмена трафиком", group: "Управление", url: "/ix", icon: NetworkIcon, keywords: ["ix","peering","транзит","bgp"] },
|
||||
{ id: "ipsec", title: "IPsec / IKEv2", group: "Управление", url: "/ipsec", icon: LockIcon, keywords: ["vpn","ikev2","ipsec","сертификат","p12","клиент"] },
|
||||
{ id: "gre", title: "GRE-туннели", group: "Управление", url: "/gre", icon: CableIcon, keywords: ["gre","ipsec","tunnel","туннель"] },
|
||||
{ id: "vxlan", title: "VXLAN", group: "Управление", url: "/vxlan", icon: NetworkIcon, keywords: ["overlay","vni","vtep","l2"] },
|
||||
|
||||
@@ -49,12 +49,13 @@ export const MAP_SERVICE_NODE_H = 58
|
||||
/** Одна горизонтальная «полка» на карте: Home → JH → Exit слева направо. */
|
||||
export const NETWORK_MAP_PIPELINE_Y = 300
|
||||
|
||||
type NodeRole = "HR" | "JH" | "EN"
|
||||
type NodeRole = "HR" | "JH" | "EN" | "IX"
|
||||
|
||||
function roleOfServer(s: Server): NodeRole | null {
|
||||
if (s.type === "home-router") return "HR"
|
||||
if (s.type === "jump-host") return "JH"
|
||||
if (s.type === "exit-node") return "EN"
|
||||
if (s.type === "ix-node") return "IX"
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -63,6 +64,7 @@ function roleLayer(role: NodeRole): number {
|
||||
case "HR": return 1
|
||||
case "JH": return 2
|
||||
case "EN": return 3
|
||||
case "IX": return 2
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,6 +275,7 @@ export function computeNetworkMapLayout(
|
||||
// - JH: центральная (40–60%),
|
||||
// - EN: правая (80–100%).
|
||||
const laneOrder: ServerType[] = ["home-router", "jump-host", "exit-node"]
|
||||
if (servers.some(server => server.type === "ix-node")) laneOrder.splice(2, 0, "ix-node")
|
||||
const laneByType = new Map<ServerType, Server[]>()
|
||||
const minNodeY = MARGIN + 70
|
||||
const maxNodeY = H - 72
|
||||
@@ -281,6 +284,7 @@ export function computeNetworkMapLayout(
|
||||
"home-router": -14,
|
||||
"jump-host": 0,
|
||||
"exit-node": 14,
|
||||
"ix-node": 0,
|
||||
}
|
||||
const siteWeight = (s: Server): number => {
|
||||
const typeBoost = s.type === "jump-host" ? 3 : s.type === "home-router" ? 2 : 1
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export const networkMapFilters=["all","online","degraded","offline","unknown","jump-host","exit-node","home-router"] as const
|
||||
export const networkMapFilters=["all","online","degraded","offline","unknown","jump-host","exit-node","home-router","ix-node"] as const
|
||||
export type NetworkMapFilter=typeof networkMapFilters[number]
|
||||
export function readNetworkMapUrl(params:URLSearchParams){
|
||||
const server=params.get("server"),search=params.get("q")??"",filter=params.get("filter")??"all",dest=params.get("dest")??"services",wan=params.get("wan")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { serverTypeSchema } from "@mmapp/contracts/servers"
|
||||
import { z } from "zod"
|
||||
const response = z.object({ output: z.string().max(1024 * 1024) }).strict()
|
||||
export function readProbeOutput(raw: unknown): string {
|
||||
@@ -11,5 +12,5 @@ export const probeServersSchema = z.array(z.object({
|
||||
id: z.number().int().positive(), name: z.string(), host: z.string().min(1), enabled: z.boolean(),
|
||||
status: z.enum(["online", "offline", "degraded", "unknown"]).nullable(),
|
||||
site: z.string().optional(), country: z.string().optional(), asn: z.string().optional(),
|
||||
type: z.enum(["jump-host", "exit-node", "home-router"]), latency: z.number().finite().nonnegative().nullable().optional(),
|
||||
type: serverTypeSchema, latency: z.number().finite().nonnegative().nullable().optional(),
|
||||
})).refine(rows => new Set(rows.map(row => row.id)).size === rows.length, "Повторяющийся идентификатор устройства")
|
||||
@@ -144,7 +144,7 @@ export interface OptimizerApiServer {
|
||||
id: number
|
||||
name: string
|
||||
host: string
|
||||
type: "jump-host" | "exit-node" | "home-router"
|
||||
type: import("@mmapp/contracts/servers").ServerType
|
||||
site: string
|
||||
country: string
|
||||
enabled: boolean
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { serverTypeSchema } from "@mmapp/contracts/servers"
|
||||
import {z} from "zod"
|
||||
import {ospfOptimizeSchema} from "./ospf-response"
|
||||
import {filtersResponseSchema} from "./filters-response"
|
||||
const unique = <T,>(rows:T[],key:(row:T)=>string|number)=>new Set(rows.map(key)).size===rows.length
|
||||
const measured = z.number().finite().nonnegative().nullable()
|
||||
export const optimizerServersSchema=z.array(z.object({
|
||||
id:z.number().int().positive(),name:z.string(),host:z.string().min(1),type:z.enum(["home-router","jump-host","exit-node"]),
|
||||
id:z.number().int().positive(),name:z.string(),host:z.string().min(1),type:serverTypeSchema,
|
||||
enabled:z.boolean(),country:z.string(),site:z.string().optional().default(""),
|
||||
status:z.enum(["online","offline","degraded"]).nullable().optional().default(null),
|
||||
latency:measured.optional().default(null),model:z.string().nullable().optional().default(null),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { serverTypeSchema } from "@mmapp/contracts/servers"
|
||||
import { z } from "zod"
|
||||
|
||||
export const vxlanResponseSchema = z.object({
|
||||
@@ -15,7 +16,7 @@ export const vxlanResponseSchema = z.object({
|
||||
|
||||
export const vxlanServersSchema = z.array(z.object({
|
||||
id: z.number().int().positive(), name: z.string(), host: z.string(), country: z.string(), enabled: z.boolean(),
|
||||
type: z.enum(["jump-host", "exit-node", "home-router"]).optional(), site: z.string().optional(),
|
||||
type: serverTypeSchema.optional(), site: z.string().optional(),
|
||||
asn: z.string().optional(), status: z.enum(["online", "offline", "degraded"]).nullable().optional(),
|
||||
latency: z.number().finite().nullable().optional(),
|
||||
})).refine(rows => new Set(rows.map(row => row.id)).size === rows.length)
|
||||
@@ -10,6 +10,10 @@
|
||||
"build": "tsc -p tsconfig.json"
|
||||
},
|
||||
"exports": {
|
||||
"./internet-exchange": {
|
||||
"types": "./dist/internet-exchange.d.ts",
|
||||
"default": "./dist/internet-exchange.js"
|
||||
},
|
||||
"./bridge-vlan": {
|
||||
"types": "./dist/bridge-vlan.d.ts",
|
||||
"default": "./dist/bridge-vlan.js"
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const key = z.string().regex(/^[a-z][a-z0-9-]{0,23}$/)
|
||||
const interfaceName = z.string().regex(/^[A-Za-z0-9_.-]{1,48}$/)
|
||||
const address = z.union([z.ipv4(), z.ipv6()])
|
||||
const prefix = z.union([z.cidrv4(), z.cidrv6()])
|
||||
const serverId = z.number().int().positive().safe()
|
||||
const asn = z.number().int().min(1).max(4294967295)
|
||||
const community = z.string().regex(/^\d{1,5}:\d{1,5}$/)
|
||||
.refine(value => value.split(":").every(part => Number(part) <= 65535))
|
||||
.transform(value => value.split(":").map(Number).join(":"))
|
||||
|
||||
const path = z.object({
|
||||
interface: interfaceName,
|
||||
nextHop: address,
|
||||
probe: address,
|
||||
viaMain: z.boolean().optional(),
|
||||
}).strict()
|
||||
|
||||
const group = z.object({
|
||||
id: key,
|
||||
gateway: address,
|
||||
primary: path,
|
||||
backup: path.optional(),
|
||||
onFailure: z.enum(["block", "segment-exit"]).default("block"),
|
||||
}).strict()
|
||||
|
||||
const wireguardProvision = z.object({
|
||||
peerPublicKey: z.string().regex(/^[A-Za-z0-9+/]{43}=$/),
|
||||
credentialId: z.string().uuid().optional(),
|
||||
listenPort: z.number().int().min(1).max(65535),
|
||||
localAddress: prefix,
|
||||
peerAddress: address,
|
||||
hubEndpoint: address.optional(),
|
||||
endpointPort: z.number().int().min(1).max(65535).optional(),
|
||||
}).strict()
|
||||
|
||||
const greProvision = z.object({
|
||||
localAddress: prefix,
|
||||
peerAddress: address,
|
||||
credentialId: z.string().uuid(),
|
||||
}).strict()
|
||||
|
||||
const linuxPolicy = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
enabled: z.boolean(),
|
||||
destinations: z.array(prefix).max(64),
|
||||
exit: key.optional(),
|
||||
peerEndpoint: address.optional(),
|
||||
}).strict()
|
||||
|
||||
const transitProvision = z.object({
|
||||
localEndpoint: z.ipv4(),
|
||||
remoteEndpoint: z.ipv4(),
|
||||
localAddress: prefix,
|
||||
remoteAddress: address,
|
||||
localPort: wireguardProvision.shape.listenPort,
|
||||
remotePort: wireguardProvision.shape.listenPort,
|
||||
remoteWan: path,
|
||||
credentialId: z.string().uuid(),
|
||||
}).strict()
|
||||
|
||||
const interfaceBinding = z.object({
|
||||
name: interfaceName,
|
||||
kind: z.enum(["wireguard", "gre-ipsec", "uplink"]),
|
||||
peerServerId: serverId.optional(),
|
||||
localEndpoint: address.optional(),
|
||||
endpoint: address.optional(),
|
||||
natIpv4: z.boolean().optional(),
|
||||
provisionWireguard: wireguardProvision.optional(),
|
||||
provisionGre: greProvision.optional(),
|
||||
provisionTransit: transitProvision.optional(),
|
||||
linux: linuxPolicy.optional(),
|
||||
prefixes: z.array(prefix).max(128).default([]),
|
||||
}).strict()
|
||||
|
||||
const rule = z.object({
|
||||
community,
|
||||
group: key,
|
||||
}).strict()
|
||||
|
||||
const neighbor = z.object({
|
||||
id: key,
|
||||
type: z.enum(["public-feed", "member", "exchange"]),
|
||||
address,
|
||||
localAddress: address,
|
||||
remoteAs: asn,
|
||||
binding: interfaceName,
|
||||
group: key.optional(),
|
||||
prefixes: z.array(prefix).max(128).default([]),
|
||||
exportPrefixes: z.array(prefix).max(128).default([]),
|
||||
rules: z.array(rule).max(100).default([]),
|
||||
limit: z.union([z.literal(10), z.literal(100), z.literal(1000), z.literal(10000)]).default(1000),
|
||||
}).strict()
|
||||
|
||||
const site = z.object({
|
||||
serverId,
|
||||
autonomousSystem: asn,
|
||||
routerId: z.ipv4(),
|
||||
autoRouterId: z.boolean().optional(),
|
||||
interfaces: z.array(interfaceBinding).max(80).default([]),
|
||||
groups: z.array(group).max(24).default([]),
|
||||
exits: z.array(key).max(2).default([]),
|
||||
routes: z.array(z.object({ prefix, group: key }).strict()).max(250).default([]),
|
||||
neighbors: z.array(neighbor).max(16).default([]),
|
||||
discardNetworks: z.array(prefix).max(250).default([]),
|
||||
}).strict()
|
||||
|
||||
export const ixSegmentConfigurationSchema = z.object({
|
||||
name: key,
|
||||
sites: z.array(site).min(1).max(2),
|
||||
}).strict()
|
||||
|
||||
export const ixChangeSchema = z.object({
|
||||
id: z.string().uuid().optional(),
|
||||
revision: z.number().int().nonnegative(),
|
||||
configuration: ixSegmentConfigurationSchema,
|
||||
}).strict().refine(input => Boolean(input.id) === (input.revision > 0), {
|
||||
message: "Для новой точки укажите ревизию 0, для существующей — её текущую ревизию",
|
||||
})
|
||||
|
||||
export type IxSite = z.infer<typeof site>
|
||||
export type IxConfiguration = z.infer<typeof ixSegmentConfigurationSchema>
|
||||
export type IxChange = z.infer<typeof ixChangeSchema>
|
||||
|
||||
const ixTransitOptions = z.object({
|
||||
targetServerId: serverId,
|
||||
name: key,
|
||||
localEndpoint: z.ipv4(),
|
||||
remoteEndpoint: z.ipv4(),
|
||||
family: z.union([z.literal(4), z.literal(6)]).default(4),
|
||||
probe: address.optional(),
|
||||
}).strict()
|
||||
|
||||
export const ixLinuxClientRequest = z.object({
|
||||
revision: z.number().int().positive(),
|
||||
serverId,
|
||||
interfaceName: interfaceName.optional(),
|
||||
name: linuxPolicy.shape.name,
|
||||
enabled: z.boolean().default(true),
|
||||
kind: z.enum(["wireguard", "gre-ipsec"]),
|
||||
hubEndpoint: address,
|
||||
peerEndpoint: address.optional(),
|
||||
peerPublicKey: wireguardProvision.shape.peerPublicKey.optional(),
|
||||
localAddress: prefix.optional(),
|
||||
peerAddress: address.optional(),
|
||||
prefixes: z.array(prefix).max(64).default([]),
|
||||
destinations: linuxPolicy.shape.destinations.default([]),
|
||||
exit: key.optional(),
|
||||
transit: ixTransitOptions.optional(),
|
||||
rotate: z.boolean().optional(),
|
||||
}).strict().refine(input => !input.transit || !input.exit || input.exit === input.transit.name,
|
||||
{ path: ["exit"], message: "Выход клиента должен совпадать с выбранным транзитом" })
|
||||
|
||||
export type IxLinuxClientRequest = z.infer<typeof ixLinuxClientRequest>
|
||||
|
||||
export const ixTransitRequest = ixTransitOptions.extend({
|
||||
revision: z.number().int().positive(),
|
||||
serverId,
|
||||
})
|
||||
|
||||
export type IxTransitRequest = z.infer<typeof ixTransitRequest>
|
||||
|
||||
export interface IxNodeInventory {
|
||||
observedAt: string
|
||||
routerId: string | null
|
||||
interfaces: Array<{
|
||||
name: string
|
||||
type: string
|
||||
running: boolean
|
||||
disabled: boolean
|
||||
addresses: string[]
|
||||
restriction: string | null
|
||||
}>
|
||||
wireguardPorts: number[]
|
||||
defaultRoutes: Array<{ family: 4 | 6; gateway: string; interface: string }>
|
||||
}
|
||||
|
||||
export interface IxSegment {
|
||||
id: string
|
||||
revision: number
|
||||
appliedRevision: number | null
|
||||
configuration: IxConfiguration
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface IxRouterObject {
|
||||
serverId: number
|
||||
path: string
|
||||
fields: Record<string, string>
|
||||
}
|
||||
|
||||
export interface IxWebPlan {
|
||||
revision: number
|
||||
digest: string
|
||||
resume?: boolean
|
||||
changes: Array<IxRouterObject & { action: "create" | "update" | "delete"; target?: string; placeBefore?: string }>
|
||||
}
|
||||
|
||||
export interface IxLinuxBinding {
|
||||
serverId: number
|
||||
interfaceName: string
|
||||
kind: "wireguard" | "gre-ipsec"
|
||||
name?: string
|
||||
managedWireguard?: boolean
|
||||
enabled?: boolean
|
||||
policy?: IxSite["interfaces"][number]["linux"]
|
||||
connection?: { state: "connected" | "waiting" | "unknown"; observedAt: string; rx?: string; tx?: string }
|
||||
}
|
||||
|
||||
export interface IxLinuxAccess {
|
||||
kind: IxLinuxBinding["kind"]
|
||||
revision: number
|
||||
filename: string
|
||||
template: string
|
||||
setup?: string
|
||||
bgp?: {
|
||||
localAs: number
|
||||
remoteAs: number
|
||||
neighbor: string
|
||||
advertisedPrefixes: string[]
|
||||
}
|
||||
}
|
||||
|
||||
export interface IxSiteObservation {
|
||||
serverId: number
|
||||
observedAt: string
|
||||
available: boolean
|
||||
routes: Array<{ prefix: string; gateway: string; immediateGateway: string | null; active: boolean }>
|
||||
neighbors: Array<{ name: string; established: boolean }>
|
||||
}
|
||||
|
||||
export interface IxLinuxPath {
|
||||
observedAt: string
|
||||
table: string
|
||||
policy: string | null
|
||||
routes: IxSiteObservation["routes"]
|
||||
}
|
||||
@@ -176,15 +176,9 @@ export const mcpPageQuerySchema = z.object({
|
||||
export type McpConnection = z.infer<typeof mcpConnectionSchema>
|
||||
export type McpConnectionCreate = z.infer<typeof mcpConnectionCreateSchema>
|
||||
|
||||
const pollOwnerCapacitySchema=z.object({used:z.number().int().min(0).max(8),limit:z.literal(8),remaining:z.number().int().min(0).max(8)}).strict().refine(value=>value.used+value.remaining<=value.limit)
|
||||
const pollGlobalCapacitySchema=z.object({used:z.number().int().min(0).max(128),limit:z.literal(128),remaining:z.number().int().min(0).max(128)}).strict().refine(value=>value.used+value.remaining<=value.limit)
|
||||
/** Heavy reservations. Retained archive bytes/rows can further reduce the
|
||||
* remaining capacity; this observation never grants an execution admission. */
|
||||
export const mcpPollStorageCapacitySchema=z.discriminatedUnion("status",[
|
||||
export const mcpPollStorageUsageSchema=z.discriminatedUnion("status",[
|
||||
z.object({status:z.literal("unavailable")}).strict(),
|
||||
z.object({status:z.literal("observed"),owner:pollOwnerCapacitySchema,
|
||||
global:z.object({exhausted:z.boolean(),usage:pollGlobalCapacitySchema.nullable()}).strict()
|
||||
.refine(value=>value.usage===null||value.exhausted===(value.usage.remaining===0)),
|
||||
retentionDays:z.number().int().min(1).max(365)}).strict(),
|
||||
z.object({status:z.literal("observed"), ownerFull:z.number().int().nonnegative().safe(),
|
||||
globalFull:z.number().int().nonnegative().safe().nullable(), retentionDays:z.number().int().min(1).max(365)}).strict(),
|
||||
])
|
||||
export type McpPollStorageCapacity=z.infer<typeof mcpPollStorageCapacitySchema>
|
||||
export type McpPollStorageUsage=z.infer<typeof mcpPollStorageUsageSchema>
|
||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user