84 lines
5.7 KiB
TypeScript
84 lines
5.7 KiB
TypeScript
import { isIP } from "node:net"
|
|
import { z } from "zod"
|
|
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
|
import { observedBoolean, observedDurationMs } from "./ospf-observed-values.js"
|
|
|
|
const iface = z.string().trim().min(1).max(200).refine(value => !/[\u0000-\u001f\u007f,]/.test(value))
|
|
function duration(maxMs: number, allowMilliseconds = true, special?: string) {
|
|
return z.string().max(64).transform((value, context) => {
|
|
if (special && value === special) return value
|
|
const ms = observedDurationMs(value)
|
|
if (ms !== null && Number.isSafeInteger(ms) && ms >= 0 && ms <= maxMs && (allowMilliseconds || ms % 1000 === 0)) {
|
|
if (ms === 0 && special && special !== "infinity") return special
|
|
return ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`
|
|
}
|
|
context.addIssue({ code: "custom", message: "Некорректный интервал IPv6 ND" }); return z.NEVER
|
|
})
|
|
}
|
|
const raInterval = z.string().max(128).transform((value, context) => {
|
|
const parts = value.split("-"), min = observedDurationMs(parts[0]), max = observedDurationMs(parts[1])
|
|
if (parts.length === 2 && min !== null && max !== null && min % 1000 === 0 && max % 1000 === 0 && min >= 3000 && min <= 1250000 && max >= 4000 && max <= 1800000 && min <= max * 0.75) return `${min / 1000}s-${max / 1000}s`
|
|
context.addIssue({ code: "custom", message: "Некорректная пара интервалов Router Advertisement" }); return z.NEVER
|
|
})
|
|
const prefix = z.string().max(64).transform((value, context) => {
|
|
if (value === "none") return value
|
|
try { if (isIP(value.split("/")[0]) === 6) return canonicalBgpPolicyPrefix(value) } catch { /* Invalid CIDR. */ }
|
|
context.addIssue({ code: "custom", message: "Требуется префикс IPv6 или none" }); return z.NEVER
|
|
})
|
|
const dns = z.string().max(1000).refine(value => value === "" || value.split(",").every(address => isIP(address) === 6))
|
|
const pref64 = z.string().max(1000).transform((value, context) => {
|
|
if (value === "") return value
|
|
try {
|
|
const entries = value.split(",").map(entry => {
|
|
const [address, length] = entry.trim().split("/")
|
|
if (isIP(address) !== 6 || !["32", "40", "48", "56", "64", "96"].includes(length)) throw new Error("Invalid PREF64")
|
|
return canonicalBgpPolicyPrefix(entry.trim())
|
|
})
|
|
if (new Set(entries).size === entries.length) return entries.join(",")
|
|
} catch { /* Invalid native prefix shape. */ }
|
|
context.addIssue({ code: "custom", message: "Требуются уникальные префиксы PREF64 с допустимыми длинами" }); return z.NEVER
|
|
})
|
|
const ignoredOptions = z.string().max(12).transform((value, context) => {
|
|
if (value === "") return value
|
|
const options = value.split(",").map(part => part.trim())
|
|
if (options.every(part => part === "dns" || part === "mtu") && new Set(options).size === options.length) return options.sort().join(",")
|
|
context.addIssue({ code: "custom", message: "Требуется список опций dns и mtu без повторов" }); return z.NEVER
|
|
})
|
|
export const ipv6NdSettingsFields = z.object({
|
|
"router-advertisement-route-distance": z.number().int().min(0).max(255).optional(),
|
|
"router-advertisement-ignored-options": ignoredOptions.optional(),
|
|
}).strict()
|
|
const optionalNumber = (min: number, max: number) => z.union([
|
|
z.literal("unspecified"), z.number().int().min(min).max(max),
|
|
z.string().regex(/^\d{1,10}$/).transform(Number).pipe(z.number().int().min(min).max(max)),
|
|
])
|
|
const common = { interface: iface.optional(), disabled: z.boolean().optional(), comment: z.string().max(1000).optional() }
|
|
export const ipv6NdFields = z.object({
|
|
...common, "ra-interval": raInterval.optional(), "ra-delay": duration(Number.MAX_SAFE_INTEGER).optional(),
|
|
"ra-lifetime": duration(9000000, false, "none").optional(), "ra-preference": z.enum(["low", "medium", "high"]).optional(),
|
|
mtu: optionalNumber(1280, 4294967295).optional(),
|
|
"hop-limit": optionalNumber(1, 255).optional(),
|
|
"reachable-time": duration(3600000, true, "unspecified").optional(), "retransmit-interval": duration(4294967295, true, "unspecified").optional(),
|
|
"advertise-dns": z.enum(["no", "yes", "self"]).optional(), dns: dns.optional(), pref64: pref64.optional(), "advertise-mac-address": z.boolean().optional(),
|
|
"managed-address-configuration": z.boolean().optional(), "other-configuration": z.boolean().optional(),
|
|
}).strict()
|
|
export const ipv6NdPrefixFields = z.object({
|
|
...common, prefix: prefix.optional(), "6to4-interface": iface.optional(), "on-link": z.boolean().optional(), autonomous: z.boolean().optional(),
|
|
"dhcp6-pd-preferred": z.boolean().optional(), "valid-lifetime": duration(4294967294000, false, "infinity").optional(),
|
|
"preferred-lifetime": duration(4294967294000, false, "infinity").optional(),
|
|
}).strict()
|
|
|
|
export function normalizeIpv6NdRow(resource: string, row: Record<string, unknown>) {
|
|
const schema = resource === "ipv6_nd_prefix" ? ipv6NdPrefixFields : resource === "ipv6_nd_settings" ? ipv6NdSettingsFields : ipv6NdFields
|
|
for (const [key, validator] of Object.entries(schema.shape)) {
|
|
if (!Object.hasOwn(row, key)) continue
|
|
const value = row[key]
|
|
const input = typeof value === "string" && /^\d+$/.test(value) && (key === "mtu" || key === "hop-limit" || key === "router-advertisement-route-distance")
|
|
? Number(value) === 0 && key !== "router-advertisement-route-distance" ? "unspecified" : Number(value)
|
|
: typeof value === "string" && validator.safeParse(true).success ? observedBoolean(value) ?? value : value
|
|
const parsed = validator.safeParse(input)
|
|
if (parsed.success && parsed.data !== undefined) row[key] = String(parsed.data)
|
|
}
|
|
if (resource === "ipv6_nd" && ["true", "false"].includes(String(row["advertise-dns"]))) row["advertise-dns"] = row["advertise-dns"] === "true" ? "yes" : "no"
|
|
}
|