Files
MikrotikManager/backend/src/services/bgp-community-policy-model.ts
T

95 lines
7.8 KiB
TypeScript

import { isIP } from "node:net"
import { z } from "zod"
import { standardCommunitySchema } from "./filter-rules-write-model.js"
/** Canonical network address; never embed unchecked text in routing-filter code. */
export function canonicalBgpPolicyPrefix(value: string) {
const [address, mask, extra] = value.trim().split("/")
const family = isIP(address)
if (extra !== undefined || !family || address.includes("%") || !/^\d{1,3}$/.test(mask ?? "") || Number(mask) > (family === 4 ? 32 : 128)) throw new Error("Нужен literal IPv4/IPv6 CIDR")
const length = Number(mask), width = family === 4 ? 32 : 128
let numeric: bigint
if (family === 4) numeric = address.split(".").reduce((sum, part) => (sum << 8n) + BigInt(part), 0n)
else {
let text = address.toLowerCase()
if (text.includes(".")) {
const end = text.lastIndexOf(":"), v4 = text.slice(end + 1).split(".").map(Number)
text = text.slice(0, end + 1) + ((v4[0] << 8) + v4[1]).toString(16) + ":" + ((v4[2] << 8) + v4[3]).toString(16)
}
const halves = text.split("::"), left = halves[0] ? halves[0].split(":") : [], right = halves[1] ? halves[1].split(":") : []
const words = halves.length === 1 ? left : [...left, ...Array<string>(8 - left.length - right.length).fill("0"), ...right]
numeric = words.reduce((sum, part) => (sum << 16n) + BigInt("0x" + part), 0n)
}
const shift = BigInt(width - length), network = numeric >> shift << shift
if (family === 4) return Array.from({ length: 4 }, (_, index) => Number(network >> BigInt((3 - index) * 8) & 255n)).join(".") + "/" + length
const words = Array.from({ length: 8 }, (_, index) => (network >> BigInt((7 - index) * 16) & 65535n).toString(16))
let bestStart = -1, bestLength = 1
for (let index = 0; index < words.length;) {
if (words[index] !== "0") { index++; continue }
const start = index; while (index < words.length && words[index] === "0") index++
if (index - start > bestLength) { bestStart = start; bestLength = index - start }
}
const canonical = bestStart < 0 ? words.join(":") : words.slice(0, bestStart).join(":") + "::" + words.slice(bestStart + bestLength).join(":")
return canonical + "/" + length
}
const prefix = z.string().trim().max(100).transform((value, context) => {
try { return canonicalBgpPolicyPrefix(value) } catch { context.addIssue({ code: "custom", message: "Нужен literal IPv4/IPv6 CIDR" }); return z.NEVER }
})
const ruleSchema = z.object({
prefix, match: z.enum(["exact", "subnet"]).default("exact"), minLength: z.number().int().min(0).max(128).optional(), maxLength: z.number().int().min(0).max(128).optional(),
communityMode: z.enum(["keep", "set", "append", "clear"]).default("keep"), communities: z.array(standardCommunitySchema).max(32).default([]),
action: z.enum(["accept", "reject", "continue"]).default("accept"),
}).strict().superRefine((rule, context) => {
const [address, bits] = rule.prefix.split("/"), length = Number(bits), width = isIP(address) === 4 ? 32 : 128
const min = rule.minLength ?? length, max = rule.maxLength ?? (rule.match === "exact" ? length : width)
if (min < length || max > width || min > max || rule.match === "exact" && (min !== length || max !== length)) context.addIssue({ code: "custom", path: ["minLength"], message: "Некорректные границы длины префикса" })
if (new Set(rule.communities).size !== rule.communities.length) context.addIssue({ code: "custom", path: ["communities"], message: "Community повторяется после нормализации" })
if (["set", "append"].includes(rule.communityMode) ? !rule.communities.length : !!rule.communities.length) context.addIssue({ code: "custom", path: ["communities"], message: "Set/append требуют непустой список; keep/clear — пустой" })
if (rule.action === "reject" && rule.communityMode !== "keep" || rule.action === "continue" && rule.communityMode === "keep") context.addIssue({ code: "custom", path: ["action"], message: "Reject не меняет attributes; continue должен менять Community" })
}).transform(rule => ({ ...rule, minLength: rule.minLength ?? Number(rule.prefix.split("/")[1]), maxLength: rule.maxLength ?? (rule.match === "exact" ? Number(rule.prefix.split("/")[1]) : isIP(rule.prefix.split("/")[0]) === 4 ? 32 : 128) }))
export const bgpCommunityPolicySchema = z.object({ policyId: z.string().regex(/^[a-z][a-z0-9_-]{0,47}$/), rules: z.array(ruleSchema).max(500), defaultAction: z.enum(["accept", "reject"]).default("reject") }).strict()
export type BgpCommunityPolicy = z.output<typeof bgpCommunityPolicySchema>
export const bgpCommunityPolicyChain = (policyId: string) => "mmapp-bgp-out-" + bgpCommunityPolicySchema.shape.policyId.parse(policyId)
export const bgpCommunityPolicyComment = (policyId: string) => "MikrotikManager: MCP BGP output " + bgpCommunityPolicySchema.shape.policyId.parse(policyId)
export function compileBgpCommunityPolicy(input: unknown) {
const policy = bgpCommunityPolicySchema.parse(input)
const body = policy.rules.map(rule => {
const condition = rule.match === "exact" ? `dst == ${rule.prefix}` : `dst in ${rule.prefix} && dst-len ${rule.minLength === rule.maxLength ? `== ${rule.minLength}` : `in ${rule.minLength}-${rule.maxLength}`}`
const lines = [`if (${condition}) {`]
if (rule.communityMode === "set" || rule.communityMode === "append") lines.push(` ${rule.communityMode === "set" ? "set" : "append"} bgp-communities ${rule.communities.join(",")};`)
else if (rule.communityMode === "clear") lines.push(" delete bgp-communities wk,other;")
if (rule.action !== "continue") lines.push(` ${rule.action};`)
return [...lines, "}"].join("\n")
}).concat(policy.defaultAction + ";").join("\n")
if (Buffer.byteLength(body, "utf8") > 65536) throw new Error("Тело Community export policy превышает 64 KiB")
return { policy, chain: bgpCommunityPolicyChain(policy.policyId), comment: bgpCommunityPolicyComment(policy.policyId), body }
}
/** Decode only an exact program emitted by this compiler. Never interpret arbitrary
* RouterOS code or return unknown native text in the human/agent plan preview. */
export function readCompiledBgpCommunityPolicy(policyId: string, body: unknown): BgpCommunityPolicy | null {
if (typeof body !== "string" || Buffer.byteLength(body, "utf8") > 65536) return null
try {
let remaining = body
const rules: Record<string, unknown>[] = []
while (remaining.startsWith("if (")) {
const block = /^if \(([^)\n]+)\) \{\n((?: [^\n]+\n)*)\}\n/.exec(remaining)
if (!block || rules.length >= 500) return null
const exact = /^dst == (\S+)$/.exec(block[1]), subnet = /^dst in (\S+) && dst-len (?:== (\d+)|in (\d+)-(\d+))$/.exec(block[1])
if (!exact && !subnet) return null
const rule: Record<string, unknown> = exact ? { prefix: exact[1] } : { prefix: subnet![1], match: "subnet", minLength: Number(subnet![2] ?? subnet![3]), maxLength: Number(subnet![2] ?? subnet![4]) }
const lines = block[2].trimEnd().split("\n")
const assignment = /^ (set|append) bgp-communities (\d{1,5}:\d{1,5}(?:,\d{1,5}:\d{1,5})*);$/.exec(lines[0])
if (assignment) { rule.communityMode = assignment[1]; rule.communities = assignment[2].split(","); lines.shift() }
else if (lines[0] === " delete bgp-communities wk,other;") { rule.communityMode = "clear"; lines.shift() }
if (!lines.length) rule.action = "continue"
else if (lines.length === 1 && /^ (accept|reject);$/.test(lines[0])) rule.action = lines[0].trim().slice(0, -1)
else return null
rules.push(rule); remaining = remaining.slice(block[0].length)
}
if (remaining !== "accept;" && remaining !== "reject;") return null
const compiled = compileBgpCommunityPolicy({ policyId, rules, defaultAction: remaining.slice(0, -1) })
return compiled.body === body ? compiled.policy : null
} catch { return null }
}