import { z } from "zod" import type { MikrotikClient } from "./mikrotik.js" import { observedDurationMs, observedInteger } from "./ospf-observed-values.js" import type { RosIpAddress, RosInterface, RosResource, RosIdentity, RosIpRoute, RosFirewallFilter, RosLogEntry, RosBgpSession, RosPingResult, RosOspfNeighbor, RosOspfArea, RosOspfInstance, RosOspfInterfaceTemplate, RosBfdSession } from "../types/server.js" // ── string helpers ───────────────────────────────────────────────────────────── function p(s: string | undefined, len: number): string { return (s?.trim() || "?").padEnd(len) } function flag(val: string | undefined, char: string): string { return val === "true" ? char : val === "false" ? " " : "?" } // ── formatters ───────────────────────────────────────────────────────────────── function fmtIpAddresses(addrs: RosIpAddress[]): string { const hdr = [ "Flags: X - disabled, I - invalid, D - dynamic", " # ADDRESS NETWORK INTERFACE", ] const rows = addrs.map((a, i) => { const f = `${flag(a.disabled,"X")}${flag(a.invalid,"I")}${flag(a.dynamic,"D")}` return ` ${String(i).padStart(2)} ${f} ${p(a.address,18)} ${p(a.network,15)} ${a.interface}${a.comment ? ` ; ${a.comment}` : ""}` }) return [...hdr, ...rows].join("\n") } function fmtInterfaces(ifaces: RosInterface[]): string { const hdr = [ "Flags: X - disabled, D - dynamic, R - running", " # NAME TYPE MTU MAC-ADDRESS", ] const rows = ifaces.map((f, i) => { const flags = `${flag(f.disabled,"X")} ${flag(f.running,"R")}` const name = p(f.name, 20) const type = p(f.type, 12) const mtu = p(f["actual-mtu"] ?? f.mtu, 6) const mac = f["mac-address"] ?? "" return ` ${String(i).padStart(2)} ${flags} ${name} ${type} ${mtu} ${mac}${f.comment ? ` ; ${f.comment}` : ""}` }) return [...hdr, ...rows].join("\n") } function fmtResource(r: RosResource, id: RosIdentity): string { const kv = (k: string, v: string) => `${k.padStart(30)}: ${v}` const mib = (b: string | undefined) => b && /^\d+$/.test(b) && Number.isSafeInteger(Number(b)) ? `${(parseInt(b) / 1024 / 1024).toFixed(1)} MiB` : "?" return [ kv("uptime", r["uptime"] ?? "?"), kv("version", r["version"] ?? "?"), kv("build-time", r["build-time"] ?? "?"), kv("free-memory", mib(r["free-memory"])), kv("total-memory", mib(r["total-memory"])), kv("cpu", r["cpu"] ?? "?"), kv("cpu-count", r["cpu-count"] ?? "?"), kv("cpu-frequency", r["cpu-frequency"] ? `${r["cpu-frequency"]} MHz` : "?"), kv("cpu-load", r["cpu-load"] ? `${r["cpu-load"]}%` : "?"), kv("free-hdd-space", mib(r["free-hdd-space"])), kv("total-hdd-space", mib(r["total-hdd-space"])), kv("architecture-name",r["architecture-name"] ?? "?"), kv("board-name", r["board-name"] ?? "?"), kv("platform", r["platform"] ?? "?"), kv("identity", id.name ?? "?"), ].join("\n") } function fmtIpRoutes(routes: RosIpRoute[]): string { const hdr = [ "Flags: X - disabled, A - active, D - dynamic, C - connect, S - static,", " r - rip, b - bgp, o - ospf, B - blackhole, U - unreachable, P - prohibit", " # DST-ADDRESS PREF-SRC GATEWAY DIST", ] const rows = routes.map((r, i) => { const f = [ flag(r.active, "A"), flag(r.dynamic, "D"), flag(r.connect, "C"), flag(r.static, "S"), flag(r.bgp, "b"), flag(r.ospf, "o"), flag(r.blackhole, "B"), flag(r.unreachable, "U"), flag(r.prohibit, "P"), ].join("") const dst = p(r["dst-address"] ?? "", 18) const pref = p(r["pref-src"] ?? "", 15) const gw = p(r["gateway"] ?? r["interface"] ?? "", 16) const dist = r["distance"] ?? "?" return ` ${String(i).padStart(2)} ${f} ${dst} ${pref} ${gw} ${dist}` }) return [...hdr, ...rows].join("\n") } function fmtBgpSessions(sessions: RosBgpSession[]): string { const hdr = [ "Flags: E - established", " # NAME REMOTE-AS REMOTE-ADDRESS STATE UPTIME", ] const rows = sessions.map((s, i) => { const est = s["established"] === "true" || s["state"] === "established" const fl = est ? "E" : " " const name = p(s["name"] ?? s[".id"], 23) const remAs = p(s["remote.as"], 10) const remIp = p((s["remote.address"] ?? "").split("/")[0], 22) const state = est ? "established" : (s["state"] ?? "?") const up = s["uptime"] ?? "—" return ` ${String(i).padStart(2)} ${fl} ${name} ${remAs} ${remIp} ${p(state, 12)} ${up}` }) return [...hdr, ...rows].join("\n") } function fmtOspfNeighbors(neighbors: RosOspfNeighbor[]): string { const hdr = [ "Flags: V - virtual", " # ROUTER-ID STATE CHANGES ADJACENCY INTERFACE", ] const rows = neighbors.map((n, i) => { return ` ${String(i).padStart(2)} ${p(n["router-id"],16)} ${p(n["state"],8)} ${p(n["state-changes"] ?? "?",8)} ${p(n["adjacency"] ?? "—",15)} ${n["interface"] ?? ""}` }) return [...hdr, ...rows].join("\n") } function fmtOspfAreas(areas: RosOspfArea[]): string { const hdr = [" # NAME AREA-ID TYPE INSTANCE"] const rows = areas.map((a, i) => ` ${String(i).padStart(2)} ${p(a.name,20)} ${p(a["area-id"] ?? "?",15)} ${p(a.type ?? "?",12)} ${a.instance}` ) return [...hdr, ...rows].join("\n") } function fmtOspfInstances(insts: RosOspfInstance[]): string { const hdr = [" # NAME ROUTER-ID VER DISTRIBUTE"] const rows = insts.map((inst, i) => ` ${String(i).padStart(2)} ${p(inst.name,15)} ${p(inst["router-id"],18)} ${p(inst.version ?? "?",4)} ${inst["redistribute"] ?? "—"}` ) return [...hdr, ...rows].join("\n") } function fmtOspfIfaceTemplates(templates: RosOspfInterfaceTemplate[]): string { const hdr = [" # INTERFACES AREA COST TYPE BFD"] const rows = templates.map((t, i) => ` ${String(i).padStart(2)} ${p(t.interfaces ?? "—",21)} ${p(t.area,19)} ${p(t.cost ?? "?",5)} ${p(t.type ?? "?",10)} ${t["use-bfd"] === "true" ? "yes" : t["use-bfd"] === "false" ? "no" : "?"}` ) return [...hdr, ...rows].join("\n") } function fmtBfdSessions(sessions: RosBfdSession[]): string { const hdr = [" # LOCAL-ADDRESS REMOTE-ADDRESS STATE UPTIME"] const rows = sessions.map((s, i) => ` ${String(i).padStart(2)} ${p(s["local-address"],27)} ${p(s["remote-address"],27)} ${p(s["state"] ?? "?",8)} ${s["uptime"] ?? "—"}` ) return [...hdr, ...rows].join("\n") } function fmtFirewallFilter(rules: RosFirewallFilter[]): string { const lines: string[] = ["Flags: X - disabled, I - invalid, D - dynamic"] rules.forEach((r, i) => { const f = `${flag(r.disabled,"X")}${flag(r.invalid,"I")}${flag(r.dynamic,"D")}` lines.push(``) lines.push(` ${String(i).padStart(2)} ${f}`) if (r.comment) lines.push(` ;;; ${r.comment}`) const parts = [`chain=${r.chain}`, `action=${r.action}`] if (r.protocol) parts.push(`protocol=${r.protocol}`) if (r["connection-state"])parts.push(`connection-state=${r["connection-state"]}`) if (r["src-address"]) parts.push(`src-address=${r["src-address"]}`) if (r["dst-address"]) parts.push(`dst-address=${r["dst-address"]}`) if (r["src-address-list"])parts.push(`src-address-list=${r["src-address-list"]}`) if (r["dst-address-list"])parts.push(`dst-address-list=${r["dst-address-list"]}`) if (r["src-port"]) parts.push(`src-port=${r["src-port"]}`) if (r["dst-port"]) parts.push(`dst-port=${r["dst-port"]}`) if (r["in-interface"]) parts.push(`in-interface=${r["in-interface"]}`) if (r["out-interface"]) parts.push(`out-interface=${r["out-interface"]}`) if (r["tls-host"]) parts.push(`tls-host=${r["tls-host"]}`) lines.push(` ${parts.join(" ")}`) if (r.packets != null || r.bytes != null) lines.push(` packets=${r.packets ?? "?"} bytes=${r.bytes ?? "?"}`) }) return lines.join("\n") } function fmtLogs(entries: RosLogEntry[]): string { if (entries.length === 0) return "(no log entries)" return entries.map(e => `${(e.time ?? "").padEnd(20)} ${(e.topics ?? "").padEnd(28)} ${e.message ?? ""}` ).join("\n") } function fmtPing(results: RosPingResult[], host: string): string { const lines = [`PING ${host}`] // individual replies for (const r of results) { if (r.status === "timeout") { lines.push(` seq=${r.seq??"?"} timeout`) } else if(r.time!=null||r.ttl!=null) { lines.push(` seq=${r.seq??"?"} ttl=${r.ttl ?? "?"} time=${r.time ?? "?"}`) } } // summary — last item with sent/received fields const sum = [...results].reverse().find(r => r.sent != null) if (sum) { const loss = sum["packet-loss"] ?? "?" lines.push(` sent=${sum.sent} received=${sum.received??"?"} packet-loss=${loss}`) const average = sum["avg-rtt"] const received = typeof sum.received === "string" ? observedInteger(sum.received, 1) : null lines.push(` avg-rtt=${received !== null && typeof average === "string" && observedDurationMs(average) !== null ? average : "?"}`) } return lines.join("\n") } // ── help text ────────────────────────────────────────────────────────────────── const HELP_TEXT = [ "Доступные команды (RouterOS REST API):", " ip address print — IP-адреса", " ip route print — таблица маршрутов", " interface print — интерфейсы", " system resource print — ресурсы системы", " system identity print — имя роутера", " ip firewall filter print — правила firewall", " routing bgp session print — BGP-сессии", " routing ospf neighbor print — OSPF-соседи", " routing ospf area print — OSPF-зоны", " routing ospf instance print — OSPF-инстансы", " routing ospf interface print — OSPF-интерфейсы", " routing bfd session print — BFD-сессии", " log print [limit=N] — системный лог", " ping [count=N] — пинг", ].join("\n") export const terminalDiagnosticNames = ["help", "addresses", "interfaces", "resources", "identity", "routes", "firewall_filters", "bgp_sessions", "ospf_neighbors", "ospf_areas", "ospf_instances", "ospf_interfaces", "bfd_sessions", "logs", "ping"] as const export const terminalDiagnosticSchema = z.object({ diagnostic: z.enum(terminalDiagnosticNames), target: z.string().min(1).max(1019).regex(/^\S+$/).optional(), count: z.number().int().positive().safe().max(20).optional(), limit: z.number().int().positive().safe().max(200).optional(), }).strict().superRefine((value, context) => { if (value.diagnostic === "ping" ? !value.target || value.limit !== undefined : value.target !== undefined || value.count !== undefined || value.diagnostic !== "logs" && value.limit !== undefined) context.addIssue({ code: "custom", message: "Параметры не соответствуют выбранной диагностике" }) }) export type TerminalDiagnostic = z.infer export type TerminalDiagnosticClient = Pick export const terminalInterfaceCountersSchema = z.object({ diagnostic: z.literal("interface_counters"), interface: z.string().min(1).max(128).regex(/^[^\p{Cc}]+$/u).optional(), limit: z.number().int().min(1).max(50).default(20), }).strict() export async function readTerminalInterfaceCounters( client: Pick, input: z.infer, protect: (value: string) => string, ) { const [interfaces, resource] = await Promise.all([client.getInterfaces(), client.getResource()]) const properties = { rxBytes: "rx-byte", txBytes: "tx-byte", rxPackets: "rx-packet", txPackets: "tx-packet", rxDrops: "rx-drop", txDrops: "tx-drop", txQueueDrops: "tx-queue-drop", rxErrors: "rx-error", txErrors: "tx-error", linkDowns: "link-downs", } as const const text = (value: unknown, max: number) => typeof value === "string" && value.length <= max && /^[^\p{Cc}]+$/u.test(value) ? protect(value) : null const counter = (value: unknown) => { if (typeof value !== "string" || !/^\d{1,20}$/.test(value) || BigInt(value) > 18446744073709551615n) return null return protect(value) === value ? value : null } const flag = (value: unknown) => value === "true" ? true : value === "false" ? false : null const selected = interfaces.filter(row => input.interface === undefined || row.name === input.interface) const rows = selected.slice(0, input.limit).map(row => { const native = row as typeof row & Partial> const counters = Object.fromEntries(Object.entries(properties).map(([key, property]) => [key, counter(native[property])])) as Record return { name: text(row.name, 128), type: text(row.type, 64), running: flag(row.running), disabled: flag(row.disabled), counters, lastLinkDownAt: text(native["last-link-down-time"], 40), lastLinkUpAt: text(native["last-link-up-time"], 40), } }) return { rows, total: selected.length, limit: input.limit, truncated: rows.length < selected.length, observedAt: new Date().toISOString(), routerUptime: text(resource.uptime, 64), countersAreCumulative: true, lastCounterResetAt: null, resetHistoryAvailable: false, } } export class ExecValidationError extends Error { readonly statusCode = 400 } /** REST grammar is intentionally an allowlist, never a RouterOS script. */ export function parseTerminalCommand(raw: string): TerminalDiagnostic { const cmd = raw.trim().replace(/^\/+/, ""), lower = cmd.toLowerCase().replace(/\s+/g, " ") const commands: Record = { "?": "help", help: "help", "ip address print": "addresses", "interface print": "interfaces", "system resource print": "resources", "system identity print": "identity", "ip route print": "routes", "ip firewall filter print": "firewall_filters", "routing bgp session print": "bgp_sessions", "bgp session print": "bgp_sessions", "bgp peer print": "bgp_sessions", "routing ospf neighbor print": "ospf_neighbors", "ospf neighbor print": "ospf_neighbors", "routing ospf area print": "ospf_areas", "ospf area print": "ospf_areas", "routing ospf instance print": "ospf_instances", "ospf instance print": "ospf_instances", "routing ospf interface print": "ospf_interfaces", "routing ospf interface-template print": "ospf_interfaces", "routing bfd session print": "bfd_sessions", "bfd session print": "bfd_sessions", } if (Object.hasOwn(commands, lower)) return { diagnostic: commands[lower] } if (/^log print(?:\s|$)/.test(lower)) { const match = lower.match(/^log print(?: limit=(\d+))?$/) if (!match) throw new ExecValidationError("Используйте log print [limit=N].") const limit = match[1] ? Number(match[1]) : 50 if (!Number.isSafeInteger(limit) || limit < 1) throw new ExecValidationError("limit должен быть положительным целым числом.") return { diagnostic: "logs", limit: Math.min(limit, 200) } } if (lower.split(" ")[0] === "ping") { const parts = cmd.replace(/\s+/g, " ").split(" ") if (parts.length < 2 || parts.length > 3) throw new ExecValidationError("Используйте ping [count=N].") const match = parts[2]?.match(/^count=(\d+)$/i) if (parts[2] && !match) throw new ExecValidationError("count должен быть положительным целым числом.") const count = match ? Number(match[1]) : 4 if (!Number.isSafeInteger(count) || count < 1) throw new ExecValidationError("count должен быть положительным целым числом.") return { diagnostic: "ping", target: parts[1], count: Math.min(count, 20) } } throw new ExecValidationError("Команда не поддерживается REST терминалом. Введите help для списка.") } /** Same presentation and semantic client methods for REST aliases and typed MCP. */ export async function executeTerminalDiagnostic(client: TerminalDiagnosticClient, input: TerminalDiagnostic): Promise { switch (input.diagnostic) { case "help": return HELP_TEXT case "addresses": return fmtIpAddresses(await client.getIpAddresses()) case "interfaces": return fmtInterfaces(await client.getInterfaces()) case "resources": { const [resource, identity] = await Promise.all([client.getResource(), client.getIdentity()]); return fmtResource(resource, identity) } case "identity": return ` name: ${(await client.getIdentity()).name}` case "routes": return fmtIpRoutes(await client.getIpRoutes()) case "firewall_filters": return fmtFirewallFilter(await client.getFirewallFilters()) case "bgp_sessions": return fmtBgpSessions(await client.getBgpSessions()) case "ospf_neighbors": return fmtOspfNeighbors(await client.getOspfNeighbors()) case "ospf_areas": return fmtOspfAreas(await client.getOspfAreas()) case "ospf_instances": return fmtOspfInstances(await client.getOspfInstances()) case "ospf_interfaces": return fmtOspfIfaceTemplates(await client.getOspfInterfaceTemplates()) case "bfd_sessions": return fmtBfdSessions(await client.getBfdSessions()) case "logs": return fmtLogs(await client.getLogs(input.limit ?? 50)) case "ping": return fmtPing(await client.ping(input.target!, input.count ?? 4), input.target!) } } export function dispatchTerminalCommand(client: TerminalDiagnosticClient, raw: string) { return executeTerminalDiagnostic(client, parseTerminalCommand(raw)) }