66 lines
5.1 KiB
TypeScript
66 lines
5.1 KiB
TypeScript
import { isIP } from "node:net"
|
|
|
|
export type BgpExportMode = "disabled" | "connected" | "static"
|
|
export type NativeBgpRow = Record<string, unknown> & { ".id": string }
|
|
const flag = (value: unknown) => value === true || value === "true" || value === "yes" ? true : value === false || value === "false" || value === "no" ? false : null
|
|
const fail = () => new Error("Не подтверждён источник экспорта BGP")
|
|
|
|
export function nativeBgpRows(payload: unknown): NativeBgpRow[] {
|
|
if (!Array.isArray(payload) || payload.length > 10000 || payload.some(row => !row || typeof row !== "object" || Array.isArray(row) || typeof row[".id"] !== "string" || !/^\*[A-Za-z0-9]+$/.test(row[".id"]) || row[".id"].length > 200)) throw fail()
|
|
if (new Set(payload.map(row => row[".id"])).size !== payload.length) throw fail()
|
|
return payload.map(row => ({ ...row }))
|
|
}
|
|
/** RouterOS /get supplies the effective value, including an explicit empty value. */
|
|
export function bgpRedistributionMode(response: unknown): BgpExportMode | null {
|
|
// A successful /get with no !done data is nil, not an explicit empty override.
|
|
if (Array.isArray(response) && response.length === 0) return null
|
|
if (!response || typeof response !== "object" || !("ret" in response) || typeof response.ret !== "string") throw fail()
|
|
if (response.ret === "") return "disabled"
|
|
if (response.ret === "connected" || response.ret === "static") return response.ret
|
|
throw new Error("Текущий экспорт BGP содержит неподдерживаемый или смешанный набор источников")
|
|
}
|
|
export function bgpTemplateReferences(response: unknown): string[] {
|
|
if (Array.isArray(response) && response.length === 0) return []
|
|
if (!response || typeof response !== "object" || !("ret" in response)) throw fail()
|
|
const value = response.ret
|
|
const refs = typeof value === "string" ? value === "" ? [] : value.split(",") : Array.isArray(value) ? value : null
|
|
if (!refs || refs.length > 100 || refs.some(ref => typeof ref !== "string" || !ref.trim() || ref.length > 200)) throw fail()
|
|
const result = refs.map(ref => (ref as string).trim())
|
|
if (new Set(result).size !== result.length) throw fail()
|
|
return result
|
|
}
|
|
export function nativeBgpExportValue(mode: BgpExportMode): string { return mode === "disabled" ? "" : mode }
|
|
|
|
/** Positive native origin flags select sources; a missing flag is not a known false.
|
|
* Unknown origins in the selected table fail closed, instead of disappearing. */
|
|
export function bgpExportSources(payload: unknown, table: string, kinds: readonly BgpExportMode[], family: 4 | 6) {
|
|
const rows = nativeBgpRows(payload), modes = new Set(kinds.filter(mode => mode !== "disabled"))
|
|
if (!modes.size) return []
|
|
const selected: { id: string; family: 4 | 6; table: string; prefix: string; kind: "connected" | "static"; active: boolean | null; proof: Record<string, unknown> }[] = []
|
|
for (const row of rows) {
|
|
if (typeof row["routing-table"] !== "string" || !row["routing-table"]) throw fail()
|
|
if (row["routing-table"] !== table) continue
|
|
const connected = flag(row.connect), configured = flag(row.static), dynamic = flag(row.dynamic)
|
|
if (connected === true && configured === true || connected === true && dynamic !== true || configured === true && dynamic !== false) throw fail()
|
|
const kind = connected === true ? "connected" : configured === true ? "static" : null
|
|
if (!kind) {
|
|
if (!["bgp", "ospf", "rip", "dhcp", "vpn", "modem", "isis", "bgp-mpls-vpn"].some(key => flag(row[key]) === true)) throw fail()
|
|
continue
|
|
}
|
|
if (!modes.has(kind)) continue
|
|
if (typeof row["dst-address"] !== "string" || row["dst-address"].length > 300) throw fail()
|
|
const [address, prefix, extra] = row["dst-address"].split("/")
|
|
if (extra !== undefined || isIP(address) !== family || prefix === undefined || !/^\d+$/.test(prefix) || Number(prefix) > (family === 4 ? 32 : 128)) throw fail()
|
|
// Preserve all source attributes in a private proof except provider debug pointers.
|
|
const proof = Object.fromEntries(Object.entries(row).filter(([key]) => !key.startsWith("debug.")))
|
|
selected.push({ id: row[".id"], family, table, prefix: row["dst-address"], kind, active: flag(row.active), proof })
|
|
}
|
|
return selected.sort((a, b) => a.id.localeCompare(b.id))
|
|
}
|
|
|
|
export function bgpExportConnection(row: NativeBgpRow, mode: BgpExportMode): NativeBgpRow {
|
|
if (flag(row.dynamic) !== false || flag(row.disabled) === null || [row.instance, row.vrf, row["routing-table"]].some(value => typeof value !== "string" || !value.trim() || value.length > 100)) throw new Error("Экспорт BGP требует подтверждённое статическое подключение с известным disabled и явными instance, VRF и таблицей")
|
|
// Inactive is a session status; it is not a change to connection configuration.
|
|
return { ...Object.fromEntries(Object.entries(row).filter(([key]) => !["inactive", "invalid", "running"].includes(key) && !key.startsWith("debug."))), ".id": row[".id"], dynamic: "false", disabled: flag(row.disabled) ? "true" : "false", "output.redistribute": nativeBgpExportValue(mode) }
|
|
}
|