Files
MikrotikManager/backend/src/services/internet-exchange-execution.ts
T
Denozordec 5a46594ec9
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m24s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
fix(ix): объединить туннели по клиентам и показать счётчики трафика
2026-11-24 10:48:21 +07:00

1042 lines
70 KiB
TypeScript

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, assertIxBondClientAssignments, assertIxName, assertIxRevision, assertIxRouterIds, assertIxSites, assertIxSegmentWithoutBonds, ixBondClientId, ixKnownVpsClient, ixReservedLinuxPoolBlocks, ixReservedRouterIds, ixReservedTunnelBindings, nextIxRouterId, readIxRevision, readIxSegment, writeIxRevision } from "./internet-exchange-store.js"
import { MikrotikClient } from "./mikrotik.js"
import { ixGreClientTemplate, ixLegacyWireguardRoutes, ixLinuxBindingKind, ixLinuxInterfaceName, ixWireguardClientTemplate } from "./internet-exchange-client.js"
import { ixWireguardPublicKey, type IxExistingTransport } from "@mmapp/contracts/internet-exchange"
type NativeRow = Record<string, string>
type IpCore = Pick<MikrotikClient, "get" | "put" | "patch" | "delete">
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(",") }))
return nativeRows(raw, props)
}
function nativeRows(raw: unknown, props: readonly string[]) {
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) {
if (input.vpsClientId && !await ixKnownVpsClient(input.vpsClientId)) throw new IxConflict("VPS больше не зарегистрирован в применённой конфигурации IX")
if (input.additionalGre && (isIP(input.peerEndpoint ?? "") !== 4 || isIP(input.hubEndpoint) !== 4)) {
throw new IxConflict("Для подключения по обоим протоколам укажите два внешних IPv4-адреса", 400)
}
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
const companion = input.companionOf && site?.interfaces.find(binding => binding.name === input.companionOf && binding.linux)
if (input.companionOf && !companion) throw new IxConflict("Исходное подключение Linux не найдено", 404)
if (input.interfaceName && input.vpsClientId) {
const groupVps = await ixBondClientId(segment.id, input.serverId, input.interfaceName)
if (groupVps && groupVps !== input.vpsClientId) throw new IxConflict("Сначала исключите подключение из действующей группы VPS")
}
const existingId = companion ? companion.linux?.clientId ?? await ixBondClientId(segment.id, input.serverId, companion.name) : undefined
const name = companion ? companion.linux!.name : input.name
const first = await configureIxLinuxTunnel(segment, { ...input, name })
const second = input.additionalGre ? await configureIxLinuxTunnel({ ...segment, configuration: first.configuration }, {
...input, kind: "gre-ipsec", localAddress: undefined, peerAddress: undefined, peerPublicKey: undefined, prefixes: [],
}) : undefined
const result = second ?? first
const currentId = site?.interfaces.find(binding => binding.name === input.interfaceName)?.linux?.clientId
const clientId = existingId ?? input.vpsClientId ?? currentId ??
(input.interfaceName ? await ixBondClientId(segment.id, input.serverId, input.interfaceName) : undefined) ?? randomUUID()
const siblings = new Set([first.interfaceName, second?.interfaceName, companion ? companion.name : undefined])
return { interfaceName: first.interfaceName, configuration: {
...result.configuration,
sites: result.configuration.sites.map(site => site.serverId !== input.serverId ? site : {
...site, interfaces: site.interfaces.map(binding =>
binding.linux && (siblings.has(binding.name) || !input.vpsClientId && binding.linux.clientId === clientId)
? { ...binding, linux: { ...binding.linux, name, clientId } } : binding),
}),
} }
}
async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRequest) {
const site = segment.configuration.sites.find(candidate => candidate.serverId === input.serverId)
if (!site) throw new IxConflict("Узел не входит в сегмент IX", 404)
const previous = site.interfaces.find(binding => binding.name === input.interfaceName && binding.linux)
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 occupiedBlocks = await ixReservedLinuxPoolBlocks()
const used = inventory.interfaces.flatMap(item => item.addresses).concat(reserved
.concat(segment.configuration.sites.flatMap(candidate => candidate.interfaces))
.flatMap(binding => [binding.provisionWireguard?.localAddress, binding.provisionGre?.localAddress,
binding.provisionTransit?.localAddress, ...binding.prefixes].filter(value => value !== undefined)))
for (let index = 0; index < 65536; index += 4) {
if (occupiedBlocks.has(index)) continue
const base = "10.254." + (index >> 8) + "."
const next = base + ((index & 255) + 1) + "/30"
if (used.some(network => inIxNetwork(network, next) || inIxNetwork(next, network))) continue
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 slug = input.name.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24).replace(/-$/, "")
const transport = input.kind === "wireguard" ? "wg" : "gre"
const name = previous?.name ?? ["il", transport, slug || "vps", randomUUID().replace(/-/g, "").slice(0, 12)].join("-")
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, clientId: previous?.linux?.clientId, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
exit: input.exit === "local-wan" ? localExit : input.exit },
}
if (input.kind === "wireguard") {
const 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)
if (site.interfaces.some(item => item !== previous && item.kind === "gre-ipsec" &&
item.localEndpoint === input.hubEndpoint && item.endpoint === input.peerEndpoint)) {
throw new IxConflict("Эта пара внешних адресов уже используется для GRE/IPsec")
}
binding.endpoint = input.peerEndpoint
binding.localEndpoint = input.hubEndpoint
binding.provisionGre = { localAddress, peerAddress,
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
}
/** Inspect operator-owned transports without running the provisioning or VRF planner. */
export async function verifyIxExistingTransport(segmentId: string, serverId: number, name: string, path: IxExistingTransport) {
const client = await requiredIxNode(serverId)
const addrPath = (address: string) => isIP(address) === 4 ? "/ip/address" : "/ipv6/address"
const readAddresses = (ip: string) => readRows(client, addrPath(ip), ["address", "network", "interface", "vrf", "disabled", "invalid"])
const [addresses, vrfs, reserved] = await Promise.all([readAddresses(path.probe), readRows(client, "/ip/vrf", ["name", "interfaces", "disabled"]), ixReservedTunnelBindings(serverId, segmentId)])
if (reserved.some(b => b.name === name)) throw new IxConflict("Интерфейс уже закреплён за другим сегментом: " + name)
const sameIP = (a: string | undefined, b: string) => !!a && isIP(a) === isIP(b) &&
inIxNetwork(b + (isIP(b) === 4 ? "/32" : "/128"), a)
const local = addresses.find(row => !isTrue(row.disabled) && !isTrue(row.invalid) && row.interface === name && sameIP(row.address?.split("/")[0], path.probe))
if (!local) throw new IxConflict("Адрес IX для проверки не назначен интерфейсу " + name)
const allowedVrf = (value: string) => value === "main" || value === ixNamespace(segmentId)
if (local.vrf) {
if (!allowedVrf(local.vrf)) throw new IxConflict("Адрес принадлежит другой VRF: " + name)
} else {
const names = new Set((await readRows(client, "/interface", ["name"])).map(row => row.name))
let owner: string | undefined
for (const row of vrfs.filter(v => !isTrue(v.disabled))) {
const selectors = row.interfaces?.split(",") ?? []
if (selectors.some(s => s === name || s === "all")) { owner = row.name; break }
// Older RouterOS may omit address.vrf. An unexpanded list could match before main.
if (selectors.some(s => s !== "none" && !names.has(s))) break
}
if (!owner || !allowedVrf(owner)) throw new IxConflict("Не подтверждена принадлежность интерфейса VRF узла: " + name)
}
if (path.kind === "gre-ipsec") {
const [interfaces, policies] = await Promise.all([readRows(client, "/interface/gre", [...greColumns, "disabled"]),
readRows(client, "/ip/ipsec/policy", ipsecPolicyColumns)])
const gre = verifyGreBinding({ name, kind: path.kind, localEndpoint: path.endpoint, endpoint: path.remoteEndpoint, prefixes: [] }, interfaces, policies)
if (isTrue(gre.disabled)) throw new IxConflict("Интерфейс отключён: " + name)
if (!sameIP(local.network, path.address) && !inIxNetwork(local.address, path.address)) {
const routes = await readRows(client, isIP(path.address) === 4 ? "/ip/route" : "/ipv6/route", ["dst-address", "gateway", "immediate-gw", "disabled"])
const host = path.address + (isIP(path.address) === 4 ? "/32" : "/128")
if (!routes.some(r => !isTrue(r.disabled) && r["dst-address"] === host &&
[r.gateway, r["immediate-gw"]].some(gw => gw?.split("@")[0] === name || gw?.split("%")[1]?.split("@")[0] === name))) {
throw new IxConflict("Адрес VPS не подтверждён подсетью или хост-маршрутом GRE: " + name)
}
}
return undefined
}
const [wireguard, peers, outer] = await Promise.all([readRows(client, "/interface/wireguard", ["name", "public-key", "disabled"]),
readRows(client, "/interface/wireguard/peers", ["interface", "public-key", "allowed-address", "disabled"]),
addrPath(path.endpoint) === addrPath(path.probe) ? addresses : readAddresses(path.endpoint)])
if (!outer.some(r => !isTrue(r.disabled) && !isTrue(r.invalid) && r.interface !== name && sameIP(r.address?.split("/")[0], path.endpoint))) {
throw new IxConflict("Внешний адрес WireGuard не найден на узле IX")
}
const hub = wireguard.find(r => r.name === name && !isTrue(r.disabled))
const peer = peers.find(r => r.interface === name && !isTrue(r.disabled) && r["public-key"] === path.clientPublicKey &&
r["allowed-address"]?.split(",").some(cidr => cidr.includes("/") && inIxNetwork(cidr.trim(), path.address)))
if (!peer || !ixWireguardPublicKey.safeParse(hub?.["public-key"]).success) throw new IxConflict("Не подтверждены WireGuard, публичный ключ VPS или allowed-address на " + name)
return hub!["public-key"]
}
function validateBindings(configuration: IxConfiguration, id: string, devices: NativeDevice[], knownObjects: IxRouterObject[]) {
for (const site of configuration.sites) {
const device = devices.find(entry => entry.serverId === site.serverId)!
if (rowsFor(device, "/interface/bridge/port").some(row => row.bridge === ixDiscardInterface(id))) {
throw new IxConflict("Изолированный bridge отбрасывания IX содержит порты")
}
// Активация WAN-выхода создаёт в main обратный маршрут через клиентский туннель.
const ownedMainRoutes = new Map<string, IxRouterObject[]>()
for (const object of knownObjects) {
if (object.serverId !== site.serverId || !["/ip/route", "/ipv6/route"].includes(object.path) || object.fields["routing-table"] !== "main") continue
const key = objectMarker(object)
const known = ownedMainRoutes.get(key) ?? []
known.push(object)
ownedMainRoutes.set(key, known)
}
const foreignMainRoutes = ["/ip/route", "/ipv6/route"].flatMap(path => rowsFor(device, path).filter(row => {
if (row["routing-table"] !== "main" || isTrue(row.dynamic)) return false
return !ownedMainRoutes.get(marker(path, row.comment ?? ""))?.some(known => matches(row, known.fields))
}))
for (const binding of site.interfaces) {
const iface = rowsFor(device, "/interface").find(row => row.name === binding.name)
if (!iface && (binding.provisionWireguard || binding.provisionGre || binding.provisionTransit)) continue
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))
if (foreignVrf || foreignMainRoutes.some(row => row.gateway?.split(",").some(gateway =>
gateway.trim().split("@")[0].split("%").at(-1) === binding.name))) {
throw new IxConflict("Интерфейс " + binding.name + " уже используется другой маршрутизацией")
}
if (binding.kind === "gre-ipsec") {
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> {
if (configuration) await assertIxBondClientAssignments(id, configuration)
for (const site of configuration?.sites ?? []) for (const binding of site.interfaces) {
const wg = binding.provisionWireguard
if (!wg?.credentialId) continue
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, resume ? objects.concat(previous) : previous)
for (const device of before) verifyEgressMembers(device, id, resume ? previous.concat(objects) : previous)
for (const old of previousConfiguration?.sites ?? []) {
const next = configuration?.sites.find(site => site.serverId === old.serverId)
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.filter(object => object.fields.comment).map(objectMarker))
const named = new Set(managed.filter(object => !object.fields.comment && object.fields.name).map(objectMarker))
const interfaces = new Set(managed.filter(object => ["/interface/wireguard", "/interface/bridge", "/ip/vrf"].includes(object.path))
.map(object => object.fields.name))
for (const [path, rows] of Object.entries(device.rows)) {
if (path === "/interface") continue // RouterOS mirrors WireGuard and bridge objects here.
if (rows.some(row => !isTrue(row.dynamic) && !known.has(marker(path, row.comment ?? "")) && !named.has(marker(path, row.name ?? "")) &&
(row.comment?.startsWith(namespace + ":") || row["routing-table"] === namespace ||
[row.interface, row.bridge, row["in-interface"], row["out-interface"], ...(row.gateway?.split(/[@%]/) ?? [])].some(value => interfaces.has(value)) ||
[row["in-interface-list"], row["out-interface-list"]].includes(ixEgressList(id)) ||
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) {
await assertIxSegmentWithoutBonds(id)
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 hasGre = bindings.some(binding => binding.linux?.enabled && binding.provisionGre)
const counterFields = ["name", "rx-byte", "tx-byte"]
const [peers, ipsec, stats] = await Promise.all([
bindings.some(binding => binding.linux && binding.provisionWireguard) ? readRows(client, "/interface/wireguard/peers",
["interface", "public-key", "last-handshake", "rx", "tx"]).catch(() => null) : [],
hasGre ? readRows(client, "/ip/ipsec/active-peers", ["remote-address", "state"]).catch(() => null) : [],
hasGre ? client.post<unknown>("/interface/print", { stats: "", ".proplist": counterFields })
.then(raw => nativeRows(raw, counterFields)).catch(() => []) : [],
])
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 + ":")))
const iface = binding.provisionGre && stats.find(row => row.name === binding.name)
const state = fresh || established ? "connected" : (binding.provisionGre ? ipsec : peers) === null ? "unknown" : "waiting"
items[index].connection = { observedAt, state,
rx: peer?.rx ?? (iface ? iface["rx-byte"] : undefined), tx: peer?.tx ?? (iface ? iface["tx-byte"] : undefined) }
}
} 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, transportOnly = false): Promise<IxLinuxAccess> {
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
const site = configuration.sites.find(site => site.serverId === serverId)
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, transportOnly) }
}
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"] : [])]
: ixLegacyWireguardRoutes(configuration, binding)
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",
hubPublicKey: iface?.["public-key"],
template: ixWireguardClientTemplate(binding, iface?.["public-key"] ?? "", routes, privateKey, transportOnly),
}
}
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()
await assertIxSegmentWithoutBonds(id)
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 })
}