Init commit

This commit is contained in:
Denozordec committed 2026-05-02 01:17:08 +07:00
commit f3f831653f
104 files changed
+43827

No files matched your search

+208
View File
@@ -0,0 +1,208 @@
import { eq } from "drizzle-orm"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { db } from "../db/index.js"
import { servers } from "../db/schema.js"
import { MikrotikClient } from "../services/mikrotik.js"
import { ServerIdParamSchema } from "../types/server.js"
import type { RosBgpSession, BgpSessionRead } from "../types/server.js"
type ServerRow = typeof servers.$inferSelect
/** Parse RouterOS duration like "1m30s", "1d5h13m23s580ms", "30s" → seconds */
function parseDuration(s: string | undefined): number {
if (!s) return 0
let total = 0
const matches = s.matchAll(/(\d+)(w|d|h|m(?!s)|s|ms)/g)
for (const m of matches) {
const n = parseInt(m[1])
switch (m[2]) {
case "w": total += n * 604800; break
case "d": total += n * 86400; break
case "h": total += n * 3600; break
case "m": total += n * 60; break
case "s": total += n; break
// ms ignored for seconds precision
}
}
return total
}
/**
* Map RouterOS 7.x short capability codes to human-readable names.
* Both local and remote capability strings are comma-separated short codes.
*/
function parseCapabilities(capStr: string | undefined): string[] {
if (!capStr) return []
const codeMap: Record<string, string> = {
mp: "MP-BGP",
rr: "Route Refresh",
gr: "Graceful Restart",
as4: "4-byte-AS",
enhe: "Extended Next-Hop",
role: "BGP Role",
err: "Extended Route Refresh",
llgr: "Long-Lived GR",
"add-path": "ADD-PATH",
}
return capStr.split(",")
.map(c => c.trim().toLowerCase())
.filter(Boolean)
.map(c => codeMap[c] ?? c)
.filter((v, i, a) => a.indexOf(v) === i) // deduplicate
}
/**
* Determine BGP session state from a RouterOS 7.x session object.
*
* RouterOS 7.x does NOT include a "state" field.
* Instead: "established": "true" means the session is up.
* For non-established sessions the "state" field may appear (RouterOS 6.x compat),
* or we fall back by checking other indicators.
*/
function detectState(s: RosBgpSession): string {
// RouterOS 7.x: explicit established flag
if (s["established"] === "true") return "Established"
// RouterOS 6.x / some 7.x builds: "state" field
if (s["state"]) {
const map: Record<string, string> = {
established: "Established",
active: "Active",
idle: "Idle",
connect: "Connect",
opensent: "OpenSent",
openconfirm: "OpenConfirm",
"open sent": "OpenSent",
"open confirm": "OpenConfirm",
}
const key = s["state"].trim().toLowerCase()
if (map[key]) return map[key]
// partial match
for (const [k, v] of Object.entries(map)) {
if (key.startsWith(k)) return v
}
return key.charAt(0).toUpperCase() + key.slice(1)
}
// Has uptime but no established flag → assume degraded Active
if (s["uptime"]) return "Active"
return "Idle"
}
function parseSessions(server: ServerRow, raw: RosBgpSession[]): BgpSessionRead[] {
return raw.map((s, idx) => {
const remoteAs = parseInt(s["remote.as"] ?? "0") || 0
const localAs = parseInt(s["local.as"] ?? "0") || 0
const type: "eBGP" | "iBGP" = (localAs > 0 && localAs === remoteAs) ? "iBGP" : "eBGP"
// Capabilities: prefer local caps (what we negotiated); merge with remote
const localCaps = parseCapabilities(s["local.capabilities"])
const remoteCaps = parseCapabilities(s["remote.capabilities"])
// Old-style boolean capability fields (RouterOS 6.x)
const legacyCaps: string[] = []
if (s["4-octet-as-capability"] === "true") legacyCaps.push("4-byte-AS")
if (s["as4-capability"] === "true") legacyCaps.push("4-byte-AS")
if (s["refresh-capability"] === "true") legacyCaps.push("Route Refresh")
if (s["add-path-capability"] === "true") legacyCaps.push("ADD-PATH")
if (s["graceful-restart-capability"] === "true") legacyCaps.push("Graceful Restart")
if (s["extended-message-capability"] === "true") legacyCaps.push("Extended Messages")
const caps = [...new Set([...localCaps, ...legacyCaps])]
// Hold time: RouterOS 7 uses "hold-time" ("1m30s"), RouterOS 6 uses "active-holdtime" (seconds)
const holdTime = parseDuration(s["hold-time"])
|| parseInt(s["active-holdtime"] ?? "0")
|| 90
// Keepalive: may have "s" suffix
const keepalive = parseDuration(s["keepalive-time"])
|| 30
// Message counts: RouterOS 7 uses "remote.messages" / "local.messages"
const inputMessages = parseInt(s["remote.messages"] ?? s["total-messages-received"] ?? "0") || 0
const outputMessages = parseInt(s["local.messages"] ?? s["total-messages-sent"] ?? "0") || 0
const peerIp = (s["remote.address"] ?? "").replace(/\/\d+$/, "")
return {
id: s[".id"] ?? String(idx),
serverId: server.id,
serverName: server.name || server.host,
serverSite: server.site,
serverCountry: server.country,
name: s["name"] ?? peerIp,
peerIp,
remoteAs,
localAs,
localId: s["local.id"] ?? "",
remoteId: s["remote.id"] ?? "",
state: detectState(s),
type,
uptime: s["uptime"] || null,
holdTime,
keepalive,
prefixesRx: parseInt(s["prefix-count"] ?? s["total-updates-received"] ?? "0") || 0,
prefixesTx: parseInt(s["total-updates-sent"] ?? "0") || 0,
inputMessages,
outputMessages,
capabilities: caps,
lastError: s["last-notification"] || null,
}
})
}
const bgpRoutes: FastifyPluginAsyncZod = async (app) => {
// GET /api/bgp/sessions/raw/:id — raw RouterOS response for a single server (debug)
app.get("/bgp/sessions/raw/:id", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
const server = db.select().from(servers).where(eq(servers.id, req.params.id)).limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
try {
const client = MikrotikClient.fromServer(server)
const raw = await client.getBgpSessionsRaw()
app.log.info({ serverId: server.id, host: server.host, raw }, "BGP raw response")
return reply.send({ server: { id: server.id, host: server.host, name: server.name }, raw })
} catch (err) {
return reply.status(500).send({ error: String(err) })
}
})
// GET /api/bgp/sessions — aggregate from ALL enabled servers
app.get("/bgp/sessions", async (_req, reply) => {
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
const results: BgpSessionRead[][] = await Promise.all(
allServers.map(async (server) => {
try {
const client = MikrotikClient.fromServer(server)
const raw = await client.getBgpSessions()
return parseSessions(server, raw)
} catch {
return []
}
}),
)
return reply.send(results.flat())
})
// GET /api/servers/:id/bgp/sessions — single server
app.get("/servers/:id/bgp/sessions", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
const server = db
.select().from(servers)
.where(eq(servers.id, req.params.id))
.limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
try {
const client = MikrotikClient.fromServer(server)
const raw = await client.getBgpSessions()
return reply.send(parseSessions(server, raw))
} catch {
return reply.send([])
}
})
}
export default bgpRoutes
+336
View File
@@ -0,0 +1,336 @@
import { eq } from "drizzle-orm"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { z } from "zod"
import { db } from "../db/index.js"
import { servers } from "../db/schema.js"
import { MikrotikClient } from "../services/mikrotik.js"
import { ServerIdParamSchema } from "../types/server.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 ?? "").padEnd(len)
}
function flag(val: string | undefined, char: string): string {
return val === "true" ? char : " "
}
// ── 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 ? `${(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"] ?? "MikroTik"),
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"] ?? "active")
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"] ?? "0",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"] ?? "0.0.0.0",15)} ${p(a.type ?? "default",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 ?? "2",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 ?? "10",5)} ${p(t.type ?? "broadcast",10)} ${t["use-bfd"] === "true" ? "yes" : "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"] ?? "down",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 || r.bytes) lines.push(` packets=${r.packets ?? "0"} bytes=${r.bytes ?? "0"}`)
})
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.time && !r.ttl) continue // skip summary-only items
if (r.status === "timeout") {
lines.push(` seq=${r.seq} timeout`)
} else {
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)
if (sum) {
const loss = sum["packet-loss"] ?? "0%"
lines.push(` sent=${sum.sent} received=${sum.received} packet-loss=${loss}`)
if (sum.time) lines.push(` avg-rtt=${sum.time}`)
}
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 <host> [count=N] — пинг",
].join("\n")
// ── command dispatcher ─────────────────────────────────────────────────────────
async function dispatch(client: MikrotikClient, raw: string): Promise<string> {
// strip leading slashes, normalize whitespace
const cmd = raw.trim().replace(/^\/+/, "")
const lower = cmd.toLowerCase().replace(/\s+/g, " ")
if (lower === "?" || lower === "help") return HELP_TEXT
if (lower === "ip address print")
return fmtIpAddresses(await client.getIpAddresses())
if (lower === "interface print")
return fmtInterfaces(await client.getInterfaces())
if (lower === "system resource print") {
const [res, id] = await Promise.all([client.getResource(), client.getIdentity()])
return fmtResource(res, id)
}
if (lower === "system identity print")
return ` name: ${(await client.getIdentity()).name}`
if (lower === "ip route print")
return fmtIpRoutes(await client.getIpRoutes())
if (lower === "ip firewall filter print")
return fmtFirewallFilter(await client.getFirewallFilters())
if (lower === "routing bgp session print" || lower === "bgp session print" || lower === "bgp peer print")
return fmtBgpSessions(await client.getBgpSessions())
if (lower === "routing ospf neighbor print" || lower === "ospf neighbor print")
return fmtOspfNeighbors(await client.getOspfNeighbors())
if (lower === "routing ospf area print" || lower === "ospf area print")
return fmtOspfAreas(await client.getOspfAreas())
if (lower === "routing ospf instance print" || lower === "ospf instance print")
return fmtOspfInstances(await client.getOspfInstances())
if (lower === "routing ospf interface print" || lower === "routing ospf interface-template print")
return fmtOspfIfaceTemplates(await client.getOspfInterfaceTemplates())
if (lower === "routing bfd session print" || lower === "bfd session print")
return fmtBfdSessions(await client.getBfdSessions().catch(() => []))
if (lower.startsWith("log print")) {
const limitArg = lower.match(/limit=(\d+)/)
const limit = limitArg ? parseInt(limitArg[1]) : 50
return fmtLogs(await client.getLogs(Math.min(limit, 200)))
}
if (lower.startsWith("ping")) {
const parts = cmd.split(/\s+/)
const host = parts[1]
if (!host) return "Usage: ping <address> [count=N]"
const countArg = parts.find(p => p.toLowerCase().startsWith("count="))
const count = countArg ? parseInt(countArg.split("=")[1]) : 4
const results = await client.ping(host, Math.min(count, 20))
return fmtPing(results, host)
}
const firstToken = cmd.split(" ")[0]
return `bad command name ${firstToken} (line 1 column 1)`
}
// ── route plugin ───────────────────────────────────────────────────────────────
const ExecBodySchema = z.object({
command: z.string().min(1).max(1024),
})
const execRoutes: FastifyPluginAsyncZod = async (app) => {
// POST /api/servers/:id/exec — execute a RouterOS CLI-style command via REST API
app.post(
"/servers/:id/exec",
{ schema: { params: ServerIdParamSchema, body: ExecBodySchema } },
async (req, reply) => {
const server = db
.select().from(servers)
.where(eq(servers.id, req.params.id))
.limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
const client = MikrotikClient.fromServer(server)
try {
const output = await dispatch(client, req.body.command)
return reply.send({ output })
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
// Return as output (not HTTP error) so the terminal can display it
return reply.send({ output: `error: ${msg}` })
}
}
)
}
export default execRoutes
+336
View File
@@ -0,0 +1,336 @@
import { and, asc, eq, inArray } from "drizzle-orm"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { db } from "../db/index.js"
import { filterRules, servers } from "../db/schema.js"
import { MikrotikClient } from "../services/mikrotik.js"
type ServerRow = typeof servers.$inferSelect
function parseServerId(raw: unknown): number | null {
const direct = Number.parseInt(String(raw ?? ""), 10)
if (Number.isFinite(direct)) return direct
const fromLegacy = String(raw ?? "").match(/(\d+)/)?.[1]
if (!fromLegacy) return null
const parsed = Number.parseInt(fromLegacy, 10)
return Number.isFinite(parsed) ? parsed : null
}
interface RosGre {
".id"?: string
name?: string
"local-address"?: string
"remote-address"?: string
"allow-fast-path"?: string
"clamp-tcp-mss"?: string
mtu?: string
"keepalive"?: string
dscp?: string
running?: string
disabled?: string
comment?: string
}
interface RosFilterRule {
".id"?: string
chain?: string
rule?: string
comment?: string
disabled?: string
}
interface LiveGreTunnel {
id: string
name: string
serverId: string
localAddress: string
remoteAddress: string
localInnerIp: string
remoteInnerIp: string
poolId: string
ipsec: null
mtu: number
keepaliveInterval: number
keepaliveRetries: number
dscp: "inherit" | number
clampTcpMss: boolean
allowFastPath: boolean
comment: string
enabled: boolean
status: "up" | "down" | "degraded"
}
interface ApiFilterRule {
id: string
community: string
communityName?: string
action?: "route" | "blackhole"
gateway: string
gatewayTunnelId: string
description: string
}
function parseKeepalive(value: string | undefined): { interval: number; retries: number } {
if (!value || value.toLowerCase() === "none") return { interval: 0, retries: 0 }
const [intervalRaw, retriesRaw] = value.split(",")
const interval = Number.parseInt((intervalRaw ?? "").trim(), 10)
const retries = Number.parseInt((retriesRaw ?? "").trim(), 10)
return {
interval: Number.isFinite(interval) ? interval : 0,
retries: Number.isFinite(retries) ? retries : 0,
}
}
function parseDscp(value: string | undefined): "inherit" | number {
if (!value || value === "inherit") return "inherit"
const n = Number.parseInt(value, 10)
return Number.isFinite(n) ? n : "inherit"
}
function parseInnerIps(rule: string | undefined): { localInnerIp: string; remoteInnerIp: string } {
if (!rule) return { localInnerIp: "", remoteInnerIp: "" }
const local = rule.match(/address\s*=\s*([0-9.]+\/\d+)/)?.[1] ?? ""
const remote = rule.match(/(?:network|gateway)\s*=\s*([0-9.]+\/\d+)/)?.[1] ?? ""
return { localInnerIp: local, remoteInnerIp: remote }
}
function parseFilterRule(raw: RosFilterRule): ApiFilterRule[] {
const text = raw.rule ?? ""
// RouterOS rule formats vary across versions/config styles:
// - bgp-communities.has("AS:NNN")
// - bgp-communities includes AS:NNN
const communities = [
...text.matchAll(/bgp-communities\.has\("([^"]+)"\)/gi),
...text.matchAll(/bgp-communities\s+includes\s+([0-9]+:[0-9]+)/gi),
].map(m => m[1]).filter(Boolean)
if (communities.length === 0) return []
const uniqueCommunities = [...new Set(communities)]
const isBlackhole = /set\s+type\s+blackhole/i.test(text)
const gwToken = text.match(/set\s+gw(?:ateway)?\s+([^\s;]+)/i)?.[1] ?? ""
const outIface = text.match(/set\s+out-interface\s+([^\s;]+)/i)?.[1] ?? ""
const inlineComment = text.match(/#\s*([^\n]+)/)?.[1]?.trim()
return uniqueCommunities.map((community, idx) => ({
id: `${raw[".id"] ?? "live"}-${idx}`,
community,
action: isBlackhole ? "blackhole" : "route",
gateway: isBlackhole ? "" : gwToken,
gatewayTunnelId: isBlackhole ? "" : outIface,
description: inlineComment || raw.comment?.trim() || "",
}))
}
async function fetchServerFilters(server: ServerRow) {
const client = MikrotikClient.fromServer(server)
const [greRaw, filterRaw] = await Promise.all([
client.get<RosGre[]>("/interface/gre"),
client.get<RosFilterRule[]>("/routing/filter/rule"),
])
const tunnels: LiveGreTunnel[] = greRaw.map((g, idx) => {
const keepalive = parseKeepalive(g["keepalive"])
const inner = parseInnerIps(g.comment)
const running = g.running === "true"
const disabled = g.disabled === "true"
return {
id: g.name || g[".id"] || `gre-${server.id}-${idx}`,
name: g.name || `gre-${idx + 1}`,
serverId: String(server.id),
localAddress: g["local-address"] ?? "",
remoteAddress: g["remote-address"] ?? "",
localInnerIp: inner.localInnerIp,
remoteInnerIp: inner.remoteInnerIp,
poolId: "live",
ipsec: null,
mtu: Number.parseInt(g.mtu ?? "1476", 10) || 1476,
keepaliveInterval: keepalive.interval,
keepaliveRetries: keepalive.retries,
dscp: parseDscp(g.dscp),
clampTcpMss: g["clamp-tcp-mss"] !== "false",
allowFastPath: g["allow-fast-path"] !== "false",
comment: g.comment ?? "",
enabled: !disabled,
status: disabled ? "down" : (running ? "up" : "degraded"),
}
})
const rules = filterRaw
.filter(r => (r.chain ?? "").trim().toLowerCase() === "bgp-in")
.flatMap(parseFilterRule)
return {
serverId: String(server.id),
rules,
tunnels,
}
}
function toApiRulesets(serverRows: ServerRow[]) {
const dbRules = db.select().from(filterRules).orderBy(asc(filterRules.serverId), asc(filterRules.sortOrder)).all()
return serverRows.map(s => ({
serverId: String(s.id),
rules: dbRules
.filter(r => r.serverId === s.id)
.map((r): ApiFilterRule => ({
id: String(r.id),
community: r.community,
communityName: r.communityName ?? undefined,
action: r.action,
gateway: r.gateway,
gatewayTunnelId: r.gatewayTunnelId,
description: r.description,
})),
}))
}
function toRouterRuleBody(rules: ApiFilterRule[]): string {
return rules.map((rule, i) => {
const kw = i === 0 ? "if" : "} else if"
const comment = rule.description ? ` # ${rule.description}` : ""
if (rule.action === "blackhole") {
return [
` ${kw} (bgp-communities.has("${rule.community}")) {`,
comment,
" set type blackhole;",
" accept;",
].filter(Boolean).join("\n")
}
return [
` ${kw} (bgp-communities.has("${rule.community}")) {`,
comment,
` set gateway ${rule.gateway};`,
` set out-interface ${rule.gatewayTunnelId};`,
" accept;",
].filter(Boolean).join("\n")
}).join("\n")
}
async function replaceDbRules(serverId: number, rules: ApiFilterRule[]) {
db.delete(filterRules).where(eq(filterRules.serverId, serverId)).run()
if (rules.length === 0) return
const now = new Date().toISOString()
db.insert(filterRules).values(
rules.map((r, i) => ({
serverId,
sortOrder: i,
community: r.community,
communityName: r.communityName ?? null,
action: r.action ?? "route",
gateway: r.gateway,
gatewayTunnelId: r.gatewayTunnelId,
description: r.description,
createdAt: now,
updatedAt: now,
})),
).run()
}
const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
app.get("/filters/rules", async (_req, reply) => {
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
const dbRulesets = toApiRulesets(allServers)
const results = await Promise.all(allServers.map(async (server) => {
try {
const remote = await fetchServerFilters(server)
return { serverId: String(server.id), tunnels: remote.tunnels }
} catch {
return { serverId: String(server.id), tunnels: [] as LiveGreTunnel[] }
}
}))
return reply.send({
rulesets: dbRulesets,
greTunnels: results.flatMap(r => r.tunnels),
})
})
app.put("/filters/rules", async (req, reply) => {
const body = req.body as { rulesets?: Array<{ serverId: string; rules: ApiFilterRule[] }> }
const payload = body.rulesets ?? []
const serverIds = payload.map(r => Number.parseInt(r.serverId, 10)).filter(Number.isFinite)
if (serverIds.length > 0) {
db.delete(filterRules).where(inArray(filterRules.serverId, serverIds)).run()
}
for (const rs of payload) {
const sid = Number.parseInt(rs.serverId, 10)
if (!Number.isFinite(sid)) continue
await replaceDbRules(sid, rs.rules ?? [])
}
return reply.send({ ok: true })
})
app.post("/filters/sync/from-router", async (_req, reply) => {
const body = _req.body as { serverId?: string | number } | undefined
const rawServerId = body?.serverId
const serverId = parseServerId(rawServerId)
if (serverId === null) {
return reply.status(400).send({ error: "serverId is required" })
}
const server = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
try {
app.log.info({ serverId, host: server.host }, "Filters sync from router started")
const remote = await fetchServerFilters(server)
await replaceDbRules(server.id, remote.rules)
app.log.info({ serverId, totalRules: remote.rules.length }, "Filters sync from router completed")
return reply.send({ ok: true, updatedServers: 1, totalRules: remote.rules.length, serverId })
} catch (err) {
app.log.error({ serverId, err: String(err) }, "Filters sync from router failed")
return reply.status(500).send({ error: String(err) })
}
})
app.post("/filters/sync/to-router", async (_req, reply) => {
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
let updatedServers = 0
let pushedRules = 0
for (const server of allServers) {
try {
const client = MikrotikClient.fromServer(server)
const existing = await client.get<RosFilterRule[]>("/routing/filter/rule")
const managed = existing.filter(r => (r.comment ?? "").startsWith("RouterLists:"))
for (const r of managed) {
if (!r[".id"]) continue
await client.delete(`/routing/filter/rule/${encodeURIComponent(r[".id"])}`)
}
const rows = db.select().from(filterRules)
.where(and(eq(filterRules.serverId, server.id)))
.orderBy(asc(filterRules.sortOrder))
.all()
const rules: ApiFilterRule[] = rows.map(r => ({
id: String(r.id),
community: r.community,
communityName: r.communityName ?? undefined,
action: r.action,
gateway: r.gateway,
gatewayTunnelId: r.gatewayTunnelId,
description: r.description,
}))
if (rules.length > 0) {
const ruleBody = toRouterRuleBody(rules)
await client.post("/routing/filter/rule", {
chain: "bgp-in",
comment: `RouterLists: ${server.name || server.host}`,
rule: ruleBody,
})
pushedRules += rules.length
}
updatedServers += 1
} catch {
// ignore failed server push
}
}
return reply.send({ ok: true, updatedServers, pushedRules })
})
}
export default filtersRoutes
+327
View File
@@ -0,0 +1,327 @@
import { eq } from "drizzle-orm"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { db } from "../db/index.js"
import { servers } from "../db/schema.js"
import { MikrotikClient } from "../services/mikrotik.js"
import { ServerIdParamSchema } from "../types/server.js"
import type {
RosOspfNeighbor, RosOspfArea, RosOspfInterfaceTemplate, RosOspfInstance,
RosBfdSession,
OspfNeighborRead, OspfInterfaceRead, OspfInstanceRead, BfdSessionRead,
} from "../types/server.js"
type ServerRow = typeof servers.$inferSelect
// ── helpers ───────────────────────────────────────────────────────────────────
/** Parse RouterOS duration string like "1h30m17s", "40s", "10m" → seconds */
function parseDuration(s: string | undefined): number {
if (!s) return 0
let total = 0
for (const m of s.matchAll(/(\d+)(w|d|h|m(?!s)|s)/g)) {
const n = parseInt(m[1])
switch (m[2]) {
case "w": total += n * 604800; break
case "d": total += n * 86400; break
case "h": total += n * 3600; break
case "m": total += n * 60; break
case "s": total += n; break
}
}
return total
}
/** Build area-name → area-id lookup from a list of raw areas */
function buildAreaMap(areas: RosOspfArea[]): Map<string, string> {
const map = new Map<string, string>()
for (const a of areas) {
map.set(a.name, a["area-id"] ?? "0.0.0.0")
}
return map
}
/** Parse "200ms" | "1s" | "500ms" → milliseconds */
function parseMs(s: string | undefined): number {
if (!s) return 0
const ms = s.match(/^(\d+)ms$/)
if (ms) return parseInt(ms[1])
const sec = s.match(/^(\d+)s$/)
if (sec) return parseInt(sec[1]) * 1000
return parseInt(s) || 0
}
/** Normalize BFD state: "up" → "Up", "down" → "Down", etc. */
function normalizeBfdState(state: string | undefined): string {
const map: Record<string, string> = {
up: "Up", down: "Down", init: "Init", admindown: "AdminDown",
}
return map[(state ?? "").toLowerCase()] ?? (state ?? "Down")
}
/** Extract IP and interface from RouterOS address format "10.0.0.1%eth0" */
function parseAddrIface(addr: string): { ip: string; iface: string } {
const [ip, iface = ""] = addr.split("%")
return { ip, iface }
}
/** Fetch all OSPF + BFD data for one server */
async function fetchServerOspf(server: ServerRow) {
const client = MikrotikClient.fromServer(server)
const [neighbors, areas, ifaceTemplates, instances, bfdSessions] = await Promise.all([
client.getOspfNeighbors(),
client.getOspfAreas(),
client.getOspfInterfaceTemplates(),
client.getOspfInstances(),
client.getBfdSessions().catch(() => [] as RosBfdSession[]), // BFD is optional
])
return { neighbors, areas, ifaceTemplates, instances, bfdSessions }
}
// ── BFD parser ────────────────────────────────────────────────────────────────
function parseBfdSessions(server: ServerRow, raw: RosBfdSession[]): BfdSessionRead[] {
return raw.map((s, idx) => {
const local = parseAddrIface(s["local-address"])
const remote = parseAddrIface(s["remote-address"])
// Prefer interface from local-address; fallback to remote-address suffix
const iface = local.iface || remote.iface
return {
id: s[".id"] ?? String(idx),
serverId: server.id,
serverName: server.name || server.host,
serverSite: server.site,
serverCountry: server.country,
localAddr: local.ip,
remoteAddr: remote.ip,
interface: iface,
state: normalizeBfdState(s["state"]),
uptime: s["uptime"] ?? null,
multihop: s["multihop"] === "true",
multiplier: parseInt(s["multiplier"] ?? "3") || 3,
txInterval: parseMs(s["actual-tx-interval"] ?? s["desired-tx-interval"]),
rxInterval: parseMs(s["required-min-rx"]),
holdTime: parseMs(s["hold-time"]),
packetsRx: parseInt(s["packets-rx"] ?? "0") || 0,
packetsTx: parseInt(s["packets-tx"] ?? "0") || 0,
stateChanges: parseInt(s["state-changes"] ?? "0") || 0,
}
})
}
// ── parsers ───────────────────────────────────────────────────────────────────
function parseNeighbors(
server: ServerRow,
neighbors: RosOspfNeighbor[],
areaMap: Map<string, string>,
): OspfNeighborRead[] {
return neighbors.map((n, idx) => ({
id: n[".id"] ?? String(idx),
serverId: server.id,
serverName: server.name || server.host,
serverSite: server.site,
serverCountry: server.country,
address: n.address,
routerId: n["router-id"],
instance: n.instance,
area: n.area,
areaId: areaMap.get(n.area) ?? n.area,
interface: n.interface,
state: n.state,
uptime: n.adjacency ?? null,
stateChanges: parseInt(n["state-changes"] ?? "0") || 0,
priority: parseInt(n.priority ?? "1") || 1,
}))
}
function parseInterfaces(
server: ServerRow,
templates: RosOspfInterfaceTemplate[],
areas: RosOspfArea[],
instances: RosOspfInstance[],
areaMap: Map<string, string>,
): OspfInterfaceRead[] {
// Build instance-id → instance name map (for interface-template instance-id field)
const instanceIdMap = new Map<string, string>()
instances.forEach((inst, i) => { instanceIdMap.set(String(i), inst.name) })
return templates.map((t, idx) => {
// Resolve interface name: may be a "*ID" reference (RouterOS internal ID)
const ifaceName = (t.interfaces ?? "").startsWith("*")
? `(ref ${t.interfaces})`
: (t.interfaces ?? "—")
return {
id: t[".id"] ?? String(idx),
serverId: server.id,
serverName: server.name || server.host,
serverSite: server.site,
serverCountry: server.country,
instance: instanceIdMap.get(t["instance-id"] ?? "") ?? t["instance-id"] ?? "",
area: t.area,
areaId: areaMap.get(t.area) ?? t.area,
interface: ifaceName,
cost: parseInt(t.cost ?? "10") || 10,
type: t.type ?? "broadcast",
disabled: t.disabled === "true",
inactive: t.inactive === "true",
priority: parseInt(t.priority ?? "1") || 1,
helloInterval: parseDuration(t["hello-interval"]),
deadInterval: parseDuration(t["dead-interval"]),
useBfd: t["use-bfd"] === "true",
}
})
}
function parseInstances(
server: ServerRow,
instances: RosOspfInstance[],
): OspfInstanceRead[] {
return instances.map((inst, idx) => ({
id: inst[".id"] ?? String(idx),
serverId: server.id,
serverName: server.name || server.host,
serverSite: server.site,
serverCountry: server.country,
name: inst.name,
routerId: inst["router-id"],
version: parseInt(inst.version ?? "2") || 2,
disabled: inst.disabled === "true",
inactive: inst.inactive === "true",
redistribute: inst.redistribute ?? "",
}))
}
// ── route plugin ──────────────────────────────────────────────────────────────
const ospfRoutes: FastifyPluginAsyncZod = async (app) => {
// GET /api/ospf/neighbors — aggregate OSPF neighbors from ALL enabled servers
app.get("/ospf/neighbors", async (_req, reply) => {
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
const results = await Promise.all(
allServers.map(async (server) => {
try {
const { neighbors, areas } = await fetchServerOspf(server)
const areaMap = buildAreaMap(areas)
return parseNeighbors(server, neighbors, areaMap)
} catch {
return []
}
}),
)
return reply.send(results.flat())
})
// GET /api/ospf/interfaces — aggregate OSPF interface templates from ALL enabled servers
app.get("/ospf/interfaces", async (_req, reply) => {
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
const results = await Promise.all(
allServers.map(async (server) => {
try {
const { ifaceTemplates, areas, instances } = await fetchServerOspf(server)
const areaMap = buildAreaMap(areas)
return parseInterfaces(server, ifaceTemplates, areas, instances, areaMap)
} catch {
return []
}
}),
)
return reply.send(results.flat())
})
// GET /api/ospf/instances — aggregate OSPF instances from ALL enabled servers
app.get("/ospf/instances", async (_req, reply) => {
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
const results = await Promise.all(
allServers.map(async (server) => {
try {
const { instances } = await fetchServerOspf(server)
return parseInstances(server, instances)
} catch {
return []
}
}),
)
return reply.send(results.flat())
})
// GET /api/ospf/all — single round-trip: neighbors + interfaces + instances + BFD
app.get("/ospf/all", async (_req, reply) => {
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
const perServer = await Promise.all(
allServers.map(async (server) => {
try {
const { neighbors, areas, ifaceTemplates, instances, bfdSessions } = await fetchServerOspf(server)
const areaMap = buildAreaMap(areas)
return {
neighbors: parseNeighbors(server, neighbors, areaMap),
interfaces: parseInterfaces(server, ifaceTemplates, areas, instances, areaMap),
instances: parseInstances(server, instances),
bfdSessions: parseBfdSessions(server, bfdSessions),
}
} catch {
return { neighbors: [], interfaces: [], instances: [], bfdSessions: [] }
}
}),
)
return reply.send({
neighbors: perServer.flatMap(r => r.neighbors),
interfaces: perServer.flatMap(r => r.interfaces),
instances: perServer.flatMap(r => r.instances),
bfdSessions: perServer.flatMap(r => r.bfdSessions),
})
})
// GET /api/bfd/sessions — BFD sessions only (for direct access)
app.get("/bfd/sessions", async (_req, reply) => {
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
const results = await Promise.all(
allServers.map(async (server) => {
try {
const client = MikrotikClient.fromServer(server)
const raw = await client.getBfdSessions()
return parseBfdSessions(server, raw)
} catch {
return []
}
}),
)
return reply.send(results.flat())
})
// GET /api/servers/:id/ospf — single server OSPF + BFD data
app.get("/servers/:id/ospf", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
const server = db
.select().from(servers)
.where(eq(servers.id, req.params.id))
.limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
try {
const { neighbors, areas, ifaceTemplates, instances, bfdSessions } = await fetchServerOspf(server)
const areaMap = buildAreaMap(areas)
return reply.send({
neighbors: parseNeighbors(server, neighbors, areaMap),
interfaces: parseInterfaces(server, ifaceTemplates, areas, instances, areaMap),
instances: parseInstances(server, instances),
bfdSessions: parseBfdSessions(server, bfdSessions),
areas: areas.map(a => ({ name: a.name, areaId: a["area-id"] ?? "0.0.0.0", type: a.type, disabled: a.disabled === "true", inactive: a.inactive === "true", instance: a.instance })),
})
} catch (err) {
return reply.status(500).send({ error: String(err) })
}
})
}
export default ospfRoutes
+264
View File
@@ -0,0 +1,264 @@
import { asc, eq } from "drizzle-orm"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { db } from "../db/index.js"
import { recursiveRoutes, servers } from "../db/schema.js"
import { MikrotikClient } from "../services/mikrotik.js"
type ServerRow = typeof servers.$inferSelect
interface RosRoute {
".id"?: string
"dst-address"?: string
gateway?: string
distance?: string
scope?: string
"target-scope"?: string
"routing-table"?: string
"check-gateway"?: string
comment?: string
disabled?: string
static?: string
dynamic?: string
blackhole?: string
unreachable?: string
prohibit?: string
active?: string
}
interface GatewayOptionDto {
id: string
name: string
ip: string
status: "up" | "down"
}
interface RecursiveRouteDto {
id: string
dstAddress: string
gateway: string
distance: number
scope: number | null
targetScope: number | null
routingTable: string
checkGateway: string
country: string
comment: string
disabled: boolean
}
function parseServerId(raw: unknown): number | null {
const direct = Number.parseInt(String(raw ?? ""), 10)
if (Number.isFinite(direct)) return direct
const legacy = String(raw ?? "").match(/(\d+)/)?.[1]
if (!legacy) return null
const parsed = Number.parseInt(legacy, 10)
return Number.isFinite(parsed) ? parsed : null
}
function isIpGateway(gw: string): boolean {
return /^\d{1,3}(\.\d{1,3}){3}(?:%\S+)?$/.test(gw.trim())
}
function isRecursiveRoute(r: RosRoute): boolean {
if ((r.static ?? "false") !== "true") return false
if ((r.dynamic ?? "false") === "true") return false
if ((r.blackhole ?? "false") === "true") return false
if ((r.unreachable ?? "false") === "true") return false
if ((r.prohibit ?? "false") === "true") return false
const dst = r["dst-address"] ?? ""
const gw = r.gateway ?? ""
if (!dst || !gw) return false
return isIpGateway(gw)
}
function hasRecursiveCommentMask(comment: string | undefined): boolean {
if (!comment) return false
return /^recursive:\s*/i.test(comment.trim())
}
function splitGateway(raw: string): { ip: string; name: string } | null {
const v = raw.trim()
if (!v) return null
const [ip, name] = v.split("%")
if (!ip || !/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) return null
return { ip, name: name || ip }
}
function mapDbRoutes(serverId: number): RecursiveRouteDto[] {
const rows = db
.select()
.from(recursiveRoutes)
.where(eq(recursiveRoutes.serverId, serverId))
.orderBy(asc(recursiveRoutes.sortOrder))
.all()
return rows.map((r) => ({
id: String(r.id),
dstAddress: r.dstAddress,
gateway: r.gateway,
distance: r.distance,
scope: r.scope ?? null,
targetScope: r.targetScope ?? null,
routingTable: r.routingTable,
checkGateway: r.checkGateway,
country: r.country ?? "",
comment: r.comment,
disabled: r.disabled,
}))
}
function toRouterPayload(route: RecursiveRouteDto): Record<string, string> {
return {
"dst-address": route.dstAddress,
gateway: route.gateway,
distance: String(route.distance),
...(route.scope != null ? { scope: String(route.scope) } : {}),
...(route.targetScope != null ? { "target-scope": String(route.targetScope) } : {}),
...(route.routingTable ? { "routing-table": route.routingTable } : {}),
...(route.checkGateway ? { "check-gateway": route.checkGateway } : {}),
comment: route.comment
? `RouterLists:recursive ${route.comment}`
: "RouterLists:recursive",
disabled: route.disabled ? "true" : "false",
}
}
async function replaceDbRoutes(serverId: number, routes: RecursiveRouteDto[]) {
db.delete(recursiveRoutes).where(eq(recursiveRoutes.serverId, serverId)).run()
if (routes.length === 0) return
const now = new Date().toISOString()
db.insert(recursiveRoutes).values(
routes.map((r, i) => ({
serverId,
sortOrder: i,
dstAddress: r.dstAddress,
gateway: r.gateway,
distance: r.distance,
scope: r.scope,
targetScope: r.targetScope,
routingTable: r.routingTable || "main",
checkGateway: r.checkGateway ?? "",
country: r.country ?? "",
comment: r.comment ?? "",
disabled: r.disabled,
createdAt: now,
updatedAt: now,
})),
).run()
}
const recursiveRoutesPlugin: FastifyPluginAsyncZod = async (app) => {
app.get("/recursive-routes/gateways", async (req, reply) => {
const q = req.query as { serverId?: string | number }
const serverId = parseServerId(q.serverId)
if (serverId === null) return reply.status(400).send({ error: "serverId is required" })
const server = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
try {
const client = MikrotikClient.fromServer(server)
const rosRoutes = await client.get<RosRoute[]>("/ip/route")
const map = new Map<string, GatewayOptionDto>()
for (const r of rosRoutes) {
const g = splitGateway(r.gateway ?? "")
if (!g) continue
const id = `${g.ip}%${g.name}`
if (!map.has(id)) {
map.set(id, {
id,
name: g.name,
ip: g.ip,
status: r.active === "true" ? "up" : "down",
})
}
}
return reply.send({ gateways: [...map.values()] })
} catch (err) {
return reply.status(500).send({ error: String(err) })
}
})
app.get("/recursive-routes", async (req, reply) => {
const q = req.query as { serverId?: string | number }
const serverId = parseServerId(q.serverId)
if (serverId === null) return reply.status(400).send({ error: "serverId is required" })
const server = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
return reply.send({ routes: mapDbRoutes(serverId) })
})
app.put("/recursive-routes", async (req, reply) => {
const body = req.body as { serverId?: string | number; routes?: RecursiveRouteDto[] }
const serverId = parseServerId(body.serverId)
if (serverId === null) return reply.status(400).send({ error: "serverId is required" })
const server = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
await replaceDbRoutes(serverId, body.routes ?? [])
return reply.send({ ok: true })
})
app.post("/recursive-routes/sync/from-router", async (req, reply) => {
const body = req.body as { serverId?: string | number } | undefined
const serverId = parseServerId(body?.serverId)
if (serverId === null) return reply.status(400).send({ error: "serverId is required" })
const server: ServerRow | undefined = db
.select().from(servers)
.where(eq(servers.id, serverId))
.limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
try {
const client = MikrotikClient.fromServer(server)
const rosRoutes = await client.get<RosRoute[]>("/ip/route")
const rec = rosRoutes.filter(r =>
isRecursiveRoute(r) && hasRecursiveCommentMask(r.comment),
)
const mapped: RecursiveRouteDto[] = rec.map((r, i) => ({
id: r[".id"] ?? `ros-${i}`,
dstAddress: r["dst-address"] ?? "",
gateway: r.gateway ?? "",
distance: Number.parseInt(r.distance ?? "1", 10) || 1,
scope: r.scope ? (Number.parseInt(r.scope, 10) || null) : null,
targetScope: r["target-scope"] ? (Number.parseInt(r["target-scope"], 10) || null) : null,
routingTable: r["routing-table"] ?? "main",
checkGateway: r["check-gateway"] ?? "",
country: "",
comment: r.comment ?? "",
disabled: r.disabled === "true",
}))
await replaceDbRoutes(serverId, mapped)
return reply.send({ ok: true, serverId, totalRoutes: mapped.length })
} catch (err) {
return reply.status(500).send({ error: String(err) })
}
})
app.post("/recursive-routes/sync/to-router", async (req, reply) => {
const body = req.body as { serverId?: string | number } | undefined
const serverId = parseServerId(body?.serverId)
if (serverId === null) return reply.status(400).send({ error: "serverId is required" })
const server = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
try {
const client = MikrotikClient.fromServer(server)
const existing = await client.get<RosRoute[]>("/ip/route")
const managed = existing.filter(r => (r.comment ?? "").startsWith("RouterLists:recursive"))
for (const r of managed) {
if (!r[".id"]) continue
await client.delete(`/ip/route/${encodeURIComponent(r[".id"])}`)
}
const dbRows = mapDbRoutes(serverId)
for (const route of dbRows) {
await client.post("/ip/route", toRouterPayload(route))
}
return reply.send({ ok: true, serverId, pushedRoutes: dbRows.length })
} catch (err) {
return reply.status(500).send({ error: String(err) })
}
})
}
export default recursiveRoutesPlugin
+224
View File
@@ -0,0 +1,224 @@
import { desc, eq } from "drizzle-orm"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { db } from "../db/index.js"
import { servers, serverSnapshots } from "../db/schema.js"
import type { ServerRead } from "../types/server.js"
import {
ServerCreateSchema,
ServerUpdateSchema,
ServerIdParamSchema,
SnapshotsQuerySchema,
TestConnectionSchema,
} from "../types/server.js"
import { pollServer, toSnapshotRead } from "../services/poller.js"
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
// ── helpers ────────────────────────────────────────────────────────────────────
type ServerRow = typeof servers.$inferSelect
type SnapshotRow = typeof serverSnapshots.$inferSelect
/** Merge a server row with its latest snapshot into the frontend-compatible shape */
function toServerRead(server: ServerRow, snap: SnapshotRow | undefined): ServerRead {
return {
id: server.id,
name: server.name || server.host,
host: server.host,
port: server.port,
useSsl: server.useSsl,
verifySsl: server.verifySsl,
username: server.username,
password: server.password,
type: server.type,
site: server.site,
country: server.country,
asn: server.asn,
comment: server.comment,
enabled: server.enabled,
createdAt: server.createdAt,
updatedAt: server.updatedAt,
// snapshot fields (null if never polled)
status: snap ? snap.status : null,
latency: snap?.latencyMs ?? null,
os: snap?.rosVersion ?? null,
model: snap?.boardName ?? null,
uptime: snap?.uptime ?? null,
cpuLoad: snap?.cpuLoad ?? null,
freeMemory: snap?.freeMemory ?? null,
totalMemory: snap?.totalMemory ?? null,
identityName: snap?.identityName ?? null,
sessions: 0,
polledAt: snap?.polledAt ?? null,
}
}
/** Get latest snapshot for a single server */
function getLatestSnapshot(serverId: number): SnapshotRow | undefined {
return db
.select()
.from(serverSnapshots)
.where(eq(serverSnapshots.serverId, serverId))
.orderBy(desc(serverSnapshots.polledAt))
.limit(1)
.all()[0]
}
// ── plugin ─────────────────────────────────────────────────────────────────────
const serversRoutes: FastifyPluginAsyncZod = async (app) => {
// POST /api/servers/test-connection — check credentials before saving
app.post("/test-connection", { schema: { body: TestConnectionSchema } }, async (req, reply) => {
const { host, port, useSsl, verifySsl, apiPath, username, password } = req.body
const client = new MikrotikClient({ host, port, useSsl, verifySsl, apiPath, username, password })
try {
const t0 = performance.now()
const [identity, resource] = await Promise.all([
client.getIdentity(),
client.getResource(),
])
const latencyMs = Math.round(performance.now() - t0)
return reply.send({
success: true,
latencyMs,
identity: identity.name,
version: resource["version"],
boardName: resource["board-name"],
uptime: resource["uptime"],
message: `Подключено · RouterOS ${resource["version"]} · ${resource["board-name"]}`,
})
} catch (err) {
let message = "Не удалось подключиться"
if (err instanceof MikrotikError) {
if (err.statusCode === 401) message = "Неверный логин или пароль (401 Unauthorized)"
else if (err.statusCode === 403) message = "Нет прав доступа к REST API (403 Forbidden)"
else message = `Ошибка RouterOS API: ${err.statusCode}`
} else if (err instanceof Error) {
const msg = err.message.toLowerCase()
if (msg.includes("timeout") || msg.includes("abort"))
message = `Нет ответа от ${host}:${port} — проверьте IP и что сервис www/www-ssl включён`
else if (msg.includes("econnrefused"))
message = `Соединение отклонено — порт ${port} закрыт`
else if (msg.includes("cert") || msg.includes("ssl") || msg.includes("tls"))
message = "Ошибка SSL-сертификата — отключите «Проверять SSL» для self-signed"
else if (msg.includes("enotfound") || msg.includes("getaddrinfo"))
message = `Хост не найден: ${host}`
else
message = err.message
}
return reply.status(502).send({ success: false, message })
}
})
// GET /api/servers
app.get("/", async (_req, reply) => {
const all = db.select().from(servers).all()
const result: ServerRead[] = all.map(s => toServerRead(s, getLatestSnapshot(s.id)))
return reply.send(result)
})
// POST /api/servers
app.post("/", { schema: { body: ServerCreateSchema } }, async (req, reply) => {
const now = new Date().toISOString()
const [inserted] = db
.insert(servers)
.values({ ...req.body, createdAt: now, updatedAt: now })
.returning()
.all()
return reply.status(201).send(toServerRead(inserted, undefined))
})
// GET /api/servers/:id
app.get("/:id", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
const server = db
.select().from(servers)
.where(eq(servers.id, req.params.id))
.limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
return reply.send(toServerRead(server, getLatestSnapshot(server.id)))
})
// PUT /api/servers/:id
app.put(
"/:id",
{ schema: { params: ServerIdParamSchema, body: ServerUpdateSchema } },
async (req, reply) => {
const existing = db
.select().from(servers)
.where(eq(servers.id, req.params.id))
.limit(1).all()[0]
if (!existing) return reply.status(404).send({ error: "Server not found" })
const [updated] = db
.update(servers)
.set({ ...req.body, updatedAt: new Date().toISOString() })
.where(eq(servers.id, req.params.id))
.returning()
.all()
return reply.send(toServerRead(updated, getLatestSnapshot(updated.id)))
},
)
// DELETE /api/servers/:id
app.delete("/:id", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
const existing = db
.select().from(servers)
.where(eq(servers.id, req.params.id))
.limit(1).all()[0]
if (!existing) return reply.status(404).send({ error: "Server not found" })
db.delete(servers).where(eq(servers.id, req.params.id)).run()
return reply.status(204).send()
})
// POST /api/servers/:id/poll
app.post("/:id/poll", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
const existing = db
.select().from(servers)
.where(eq(servers.id, req.params.id))
.limit(1).all()[0]
if (!existing) return reply.status(404).send({ error: "Server not found" })
try {
const snap = await pollServer(req.params.id)
return reply.send(snap)
} catch (err) {
return reply.status(500).send({ error: (err as Error).message })
}
})
// GET /api/servers/:id/snapshots
app.get(
"/:id/snapshots",
{ schema: { params: ServerIdParamSchema, querystring: SnapshotsQuerySchema } },
async (req, reply) => {
const existing = db
.select().from(servers)
.where(eq(servers.id, req.params.id))
.limit(1).all()[0]
if (!existing) return reply.status(404).send({ error: "Server not found" })
const snaps = db
.select()
.from(serverSnapshots)
.where(eq(serverSnapshots.serverId, req.params.id))
.orderBy(desc(serverSnapshots.polledAt))
.limit(req.query.limit)
.all()
return reply.send(snaps.map(toSnapshotRead))
},
)
}
export default serversRoutes
+285
View File
@@ -0,0 +1,285 @@
import { desc, eq } from "drizzle-orm"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { db } from "../db/index.js"
import { serverSnapshots, servers } from "../db/schema.js"
import {
collectTrafficOnce,
getTrafficCollectorState,
getTrafficSettings,
readServerSamplesInRange,
updateTrafficSettings,
} from "../services/traffic-collector.js"
type SnapshotRow = typeof serverSnapshots.$inferSelect
interface TrafficServerDto {
id: string
name: string
site: string
country: string
status: "online" | "offline" | "degraded"
rxNow: number
txNow: number
rxPeak: number
txPeak: number
rxTotal: number
txTotal: number
sessions: number
rxSeries: number[]
txSeries: number[]
}
interface TrafficInterfaceDto {
name: string
running: boolean
disabled: boolean
rxNow: number
txNow: number
}
function latestSnapshot(serverId: number): SnapshotRow | undefined {
return db
.select()
.from(serverSnapshots)
.where(eq(serverSnapshots.serverId, serverId))
.orderBy(desc(serverSnapshots.polledAt))
.limit(1)
.all()[0]
}
function rangeToMinutes(range: string | undefined): number {
switch ((range ?? "1h").toLowerCase()) {
case "5m": return 5
case "15m": return 15
case "1h": return 60
case "4h": return 240
case "24h": return 1440
default: return 60
}
}
function toSeries(values: number[], target = 60): number[] {
if (values.length === 0) return Array(target).fill(0)
if (values.length === target) return values
if (values.length > target) return values.slice(values.length - target)
const head = Array(target - values.length).fill(values[0] ?? 0)
return [...head, ...values]
}
function buildServerTraffic(
s: typeof servers.$inferSelect,
status: TrafficServerDto["status"],
rows: Array<{
interfaceName: string
sampledAt: string
rxBps: number
txBps: number
rxBytes: number
txBytes: number
running: boolean
disabled: boolean
}>,
onlyInterface?: string,
): TrafficServerDto {
const filteredRows = onlyInterface
? rows.filter((r) => r.interfaceName === onlyInterface)
: rows
if (filteredRows.length === 0) {
return {
id: String(s.id),
name: s.name || s.host,
site: s.site || "—",
country: s.country || "UN",
status,
rxNow: 0,
txNow: 0,
rxPeak: 0,
txPeak: 0,
rxTotal: 0,
txTotal: 0,
sessions: 0,
rxSeries: Array(60).fill(0),
txSeries: Array(60).fill(0),
}
}
const bySampleTs = new Map<string, { rx: number; tx: number }>()
const byIface = new Map<string, typeof filteredRows>()
for (const r of filteredRows) {
const ts = r.sampledAt
const cur = bySampleTs.get(ts) ?? { rx: 0, tx: 0 }
cur.rx += Math.max(0, r.rxBps) / 1_000_000
cur.tx += Math.max(0, r.txBps) / 1_000_000
bySampleTs.set(ts, cur)
const arr = byIface.get(r.interfaceName) ?? []
arr.push(r)
byIface.set(r.interfaceName, arr)
}
const seriesPoints = [...bySampleTs.entries()]
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([, v]) => ({ rx: Math.round(v.rx), tx: Math.round(v.tx) }))
const rxSeries = toSeries(seriesPoints.map((p) => p.rx))
const txSeries = toSeries(seriesPoints.map((p) => p.tx))
const rxNow = rxSeries[rxSeries.length - 1] ?? 0
const txNow = txSeries[txSeries.length - 1] ?? 0
const rxPeak = rxSeries.reduce((m, v) => Math.max(m, v), 0)
const txPeak = txSeries.reduce((m, v) => Math.max(m, v), 0)
let rxBytesDelta = 0
let txBytesDelta = 0
let sessions = 0
for (const arr of byIface.values()) {
const sorted = [...arr].sort((a, b) => a.sampledAt.localeCompare(b.sampledAt))
const first = sorted[0]
const last = sorted[sorted.length - 1]
if (first && last) {
const dRx = last.rxBytes - first.rxBytes
const dTx = last.txBytes - first.txBytes
rxBytesDelta += dRx >= 0 ? dRx : last.rxBytes
txBytesDelta += dTx >= 0 ? dTx : last.txBytes
if (last.running && !last.disabled) sessions += 1
}
}
return {
id: String(s.id),
name: s.name || s.host,
site: s.site || "—",
country: s.country || "UN",
status,
rxNow,
txNow,
rxPeak,
txPeak,
rxTotal: Number((rxBytesDelta / (1024 ** 3)).toFixed(1)),
txTotal: Number((txBytesDelta / (1024 ** 3)).toFixed(1)),
sessions,
rxSeries,
txSeries,
}
}
const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
app.get("/traffic/settings", async (_req, reply) => {
const settings = getTrafficSettings()
const state = getTrafficCollectorState()
return reply.send({
enabled: settings.enabled,
intervalSec: settings.intervalSec,
retentionDays: settings.retentionDays,
lastCollectedAt: settings.lastCollectedAt ?? null,
lastDurationMs: settings.lastDurationMs ?? null,
lastError: settings.lastError || null,
collectorRunning: state.running,
})
})
app.put("/traffic/settings", async (req, reply) => {
const body = req.body as {
enabled?: boolean
intervalSec?: number | string
retentionDays?: number | string
}
const intervalSec = body.intervalSec == null ? undefined : Math.max(5, Number.parseInt(String(body.intervalSec), 10) || 30)
const retentionDays = body.retentionDays == null ? undefined : Math.max(1, Number.parseInt(String(body.retentionDays), 10) || 14)
const updated = updateTrafficSettings({
enabled: body.enabled,
intervalSec,
retentionDays,
})
return reply.send({
ok: true,
settings: {
enabled: updated.enabled,
intervalSec: updated.intervalSec,
retentionDays: updated.retentionDays,
lastCollectedAt: updated.lastCollectedAt ?? null,
lastDurationMs: updated.lastDurationMs ?? null,
lastError: updated.lastError || null,
},
})
})
app.post("/traffic/collect-now", async (_req, reply) => {
await collectTrafficOnce()
const updated = getTrafficSettings()
return reply.send({
ok: true,
lastCollectedAt: updated.lastCollectedAt ?? null,
lastDurationMs: updated.lastDurationMs ?? null,
lastError: updated.lastError || null,
})
})
app.get("/traffic/servers", async (req, reply) => {
const q = req.query as { range?: string }
const minutes = rangeToMinutes(q.range)
const sinceIso = new Date(Date.now() - minutes * 60_000).toISOString()
const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()
const data = allServers.map((s): TrafficServerDto => {
const snap = latestSnapshot(s.id)
const status: TrafficServerDto["status"] =
snap?.status === "offline" ? "offline" : (snap?.status === "online" ? "online" : "degraded")
const rows = readServerSamplesInRange(s.id, sinceIso)
return buildServerTraffic(s, status, rows)
})
return reply.send({ servers: data })
})
app.get("/traffic/servers/:id/interfaces", async (req, reply) => {
const p = req.params as { id?: string | number }
const serverId = Number.parseInt(String(p.id ?? ""), 10)
if (!Number.isFinite(serverId)) return reply.status(400).send({ error: "id is required" })
const allRows = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()
const server = allRows[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
const sinceIso = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
const rows = readServerSamplesInRange(serverId, sinceIso)
const byIface = new Map<string, typeof rows>()
for (const r of rows) {
const arr = byIface.get(r.interfaceName) ?? []
arr.push(r)
byIface.set(r.interfaceName, arr)
}
const interfaces: TrafficInterfaceDto[] = [...byIface.entries()].map(([name, arr]) => {
const sorted = arr.sort((a, b) => a.sampledAt.localeCompare(b.sampledAt))
const last = sorted[sorted.length - 1]
return {
name,
running: Boolean(last?.running),
disabled: Boolean(last?.disabled),
rxNow: Math.round((last?.rxBps ?? 0) / 1_000_000),
txNow: Math.round((last?.txBps ?? 0) / 1_000_000),
}
}).sort((a, b) => (b.rxNow + b.txNow) - (a.rxNow + a.txNow))
return reply.send({ interfaces })
})
app.get("/traffic/servers/:id", async (req, reply) => {
const p = req.params as { id?: string | number }
const q = req.query as { range?: string; iface?: string }
const serverId = Number.parseInt(String(p.id ?? ""), 10)
if (!Number.isFinite(serverId)) return reply.status(400).send({ error: "id is required" })
const server = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()[0]
if (!server) return reply.status(404).send({ error: "Server not found" })
const minutes = rangeToMinutes(q.range)
const sinceIso = new Date(Date.now() - minutes * 60_000).toISOString()
const rows = readServerSamplesInRange(server.id, sinceIso)
const snap = latestSnapshot(server.id)
const status: TrafficServerDto["status"] =
snap?.status === "offline" ? "offline" : (snap?.status === "online" ? "online" : "degraded")
const data = buildServerTraffic(server, status, rows, q.iface && q.iface !== "__all__" ? q.iface : undefined)
return reply.send({ server: data })
})
}
export default trafficRoutes
+317
View File
@@ -0,0 +1,317 @@
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { eq } from "drizzle-orm"
import { db } from "../db/index.js"
import { servers } from "../db/schema.js"
import { MikrotikClient } from "../services/mikrotik.js"
import {
collectUptimeOnce,
readProbeRows,
readProbeSamplesSince,
readResourceSamplesSince,
readUptimeSettings,
replaceProbes,
updateUptimeSettings,
} from "../services/uptime-collector.js"
function rangeToMinutes(range: string | undefined): number {
switch ((range ?? "1h").toLowerCase()) {
case "5m": return 5
case "15m": return 15
case "1h": return 60
case "4h": return 240
case "24h": return 1440
default: return 60
}
}
function toSeries(values: number[], target = 40): number[] {
if (values.length === 0) return Array(target).fill(0)
if (values.length === target) return values
if (values.length > target) return values.slice(values.length - target)
return [...Array(target - values.length).fill(values[0] ?? 0), ...values]
}
function parseRateToMbps(raw: unknown): number {
const txt = String(raw ?? "").trim().toLowerCase()
if (!txt) return 0
const m = txt.match(/^(\d+(?:\.\d+)?)\s*(g|m|k)?(?:bps|bit\/s|bits\/s)?$/)
if (m) {
const n = Number.parseFloat(m[1])
const u = m[2] ?? ""
if (!Number.isFinite(n)) return 0
if (u === "g") return n * 1000
if (u === "m") return n
if (u === "k") return n / 1000
return n / 1_000_000
}
const n = Number.parseFloat(txt.replace(/[^\d.]/g, ""))
if (!Number.isFinite(n)) return 0
return n > 10000 ? n / 1_000_000 : n
}
const uptimeRoutes: FastifyPluginAsyncZod = async (app) => {
app.get("/uptime/settings", async (_req, reply) => {
const s = readUptimeSettings()
return reply.send({
enabled: s.enabled,
intervalSec: s.intervalSec,
retentionDays: s.retentionDays,
lastCollectedAt: s.lastCollectedAt ?? null,
lastDurationMs: s.lastDurationMs ?? null,
lastError: s.lastError || null,
})
})
app.put("/uptime/settings", async (req, reply) => {
const body = req.body as { enabled?: boolean; intervalSec?: number | string; retentionDays?: number | string }
const updated = updateUptimeSettings({
enabled: body.enabled,
intervalSec: body.intervalSec == null ? undefined : Math.max(5, Number.parseInt(String(body.intervalSec), 10) || 15),
retentionDays: body.retentionDays == null ? undefined : Math.max(1, Number.parseInt(String(body.retentionDays), 10) || 14),
})
return reply.send({
ok: true,
settings: {
enabled: updated.enabled,
intervalSec: updated.intervalSec,
retentionDays: updated.retentionDays,
lastCollectedAt: updated.lastCollectedAt ?? null,
lastDurationMs: updated.lastDurationMs ?? null,
lastError: updated.lastError || null,
},
})
})
app.post("/uptime/collect-now", async (_req, reply) => {
await collectUptimeOnce()
const s = readUptimeSettings()
return reply.send({
ok: true,
lastCollectedAt: s.lastCollectedAt ?? null,
lastDurationMs: s.lastDurationMs ?? null,
lastError: s.lastError || null,
})
})
app.get("/uptime/probes", async (_req, reply) => {
return reply.send({ probes: readProbeRows() })
})
app.put("/uptime/probes", async (req, reply) => {
const body = req.body as {
probes?: Array<{
id?: string
srcServerId?: string | number
srcInterface?: string
name?: string
target?: string
filter?: string
enabled?: boolean
}>
}
const normalized = (body.probes ?? [])
.map((p, i) => ({
id: p.id || `p-${Date.now()}-${i}`,
srcServerId: Number.parseInt(String(p.srcServerId ?? ""), 10),
srcInterface: String(p.srcInterface ?? "").trim(),
name: String(p.name ?? "").trim(),
target: String(p.target ?? "").trim(),
probeFilter: String(p.filter ?? "—"),
enabled: p.enabled !== false,
}))
.filter((p) => Number.isFinite(p.srcServerId) && p.name && p.target)
replaceProbes(normalized)
return reply.send({ ok: true })
})
app.get("/uptime/sources/:id/interfaces", async (req, reply) => {
const params = req.params as { id?: string | number }
const serverId = Number.parseInt(String(params.id ?? ""), 10)
if (!Number.isFinite(serverId)) return reply.status(400).send({ error: "Invalid server id" })
const srv = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()[0]
if (!srv) return reply.status(404).send({ error: "Server not found" })
try {
const rows = await MikrotikClient.fromServer(srv).getInterfaces()
const interfaces = rows
.map((r) => ({
name: String(r.name ?? "").trim(),
running: String(r.running ?? "false").toLowerCase() === "true",
disabled: String(r.disabled ?? "false").toLowerCase() === "true",
}))
.filter((r) => r.name.length > 0)
.sort((a, b) => a.name.localeCompare(b.name))
return reply.send({ interfaces })
} catch (e) {
const message = e instanceof Error ? e.message : "Failed to fetch interfaces"
return reply.status(502).send({ error: message })
}
})
app.post("/uptime/speed-test", async (req, reply) => {
const body = req.body as {
srcServerId?: string | number
dstServerId?: string | number
srcInterface?: string
dstInterface?: string
protocol?: "tcp" | "udp"
direction?: "transmit" | "receive" | "both"
durationSec?: string | number
}
const srcId = Number.parseInt(String(body.srcServerId ?? ""), 10)
const dstId = Number.parseInt(String(body.dstServerId ?? ""), 10)
if (!Number.isFinite(srcId) || !Number.isFinite(dstId)) {
return reply.status(400).send({ error: "Invalid src/dst server id" })
}
if (srcId === dstId) return reply.status(400).send({ error: "Source and destination must be different" })
const src = db.select().from(servers).where(eq(servers.id, srcId)).limit(1).all()[0]
const dst = db.select().from(servers).where(eq(servers.id, dstId)).limit(1).all()[0]
if (!src || !dst) return reply.status(404).send({ error: "Server not found" })
try {
const protocol = body.protocol === "udp" ? "udp" : "tcp"
const direction = body.direction === "transmit" || body.direction === "receive" ? body.direction : "both"
const durationSec = Math.max(3, Number.parseInt(String(body.durationSec ?? ""), 10) || 10)
const srcInterface = String(body.srcInterface ?? "").trim()
const dstInterface = String(body.dstInterface ?? "").trim()
const srcClient = MikrotikClient.fromServer(src)
const dstAddressRows = dstInterface
? await MikrotikClient.fromServer(dst).getIpAddresses().catch(() => [])
: []
const dstAddress = dstInterface
? String(
dstAddressRows.find((a) => String(a.interface ?? "") === dstInterface && String(a.address ?? "").includes("/"))?.address ??
"",
).split("/")[0]
: dst.host
if (dstInterface && !dstAddress) {
return reply.status(400).send({ error: `На интерфейсе назначения '${dstInterface}' нет IP-адреса` })
}
const initialAddress = dstAddress || dst.host
const rows = await srcClient.bandwidthTest({
address: initialAddress,
user: dst.username,
password: dst.password,
protocol,
direction,
durationSec,
})
const txSeries = rows
.map((r) => parseRateToMbps(r["tx-current"] ?? r["tx-10-second-average"] ?? r["tx-total-average"]))
.filter((v) => Number.isFinite(v) && v >= 0)
const rxSeries = rows
.map((r) => parseRateToMbps(r["rx-current"] ?? r["rx-10-second-average"] ?? r["rx-total-average"]))
.filter((v) => Number.isFinite(v) && v >= 0)
const last = rows[rows.length - 1] ?? {}
const txAvg = parseRateToMbps(last["tx-total-average"] ?? last["tx-10-second-average"])
const rxAvg = parseRateToMbps(last["rx-total-average"] ?? last["rx-10-second-average"])
return reply.send({
ok: true,
result: {
srcInterface: srcInterface || null,
dstInterface: dstInterface || null,
address: initialAddress,
protocol,
direction,
durationSec,
txAvgMbps: txAvg || (txSeries.length ? txSeries.reduce((a, b) => a + b, 0) / txSeries.length : 0),
rxAvgMbps: rxAvg || (rxSeries.length ? rxSeries.reduce((a, b) => a + b, 0) / rxSeries.length : 0),
txSeries,
rxSeries,
raw: rows,
},
})
} catch (e) {
const raw = e instanceof Error ? e.message : "Bandwidth test failed"
const message = /timed out|socket hang up|ECONNRESET/i.test(raw)
? "BTTest timeout/socket hang up: проверь доступность destination, /tool bandwidth-server, firewall и корректность интерфейсов"
: raw
return reply.status(502).send({ error: message })
}
})
app.get("/uptime/speed-test/endpoints/:id/interfaces", async (req, reply) => {
const params = req.params as { id?: string | number }
const serverId = Number.parseInt(String(params.id ?? ""), 10)
if (!Number.isFinite(serverId)) return reply.status(400).send({ error: "Invalid server id" })
const srv = db.select().from(servers).where(eq(servers.id, serverId)).limit(1).all()[0]
if (!srv) return reply.status(404).send({ error: "Server not found" })
try {
const client = MikrotikClient.fromServer(srv)
const [ifaces, ips] = await Promise.all([
client.getInterfaces(),
client.getIpAddresses(),
])
const interfaces = ifaces
.map((i) => {
const name = String(i.name ?? "").trim()
const addresses = ips
.filter((a) => String(a.interface ?? "") === name)
.map((a) => String(a.address ?? "").split("/")[0])
.filter((x) => x.length > 0)
return {
name,
running: String(i.running ?? "false").toLowerCase() === "true",
disabled: String(i.disabled ?? "false").toLowerCase() === "true",
addresses,
}
})
.filter((i) => i.name.length > 0)
return reply.send({ interfaces })
} catch (e) {
const message = e instanceof Error ? e.message : "Failed to fetch speed-test interfaces"
return reply.status(502).send({ error: message })
}
})
app.get("/uptime/overview", async (req, reply) => {
const q = req.query as { range?: string }
const minutes = rangeToMinutes(q.range)
const sinceIso = new Date(Date.now() - minutes * 60_000).toISOString()
const allServers = db.select().from(servers).all()
const probeRows = readProbeRows()
const probeSamples = readProbeSamplesSince(sinceIso)
const probes = probeRows.map((p) => {
const rows = probeSamples.filter((r) => r.probeId === p.id)
const last = rows[rows.length - 1]
const series = toSeries(rows.map((r) => r.rttMs ?? 0))
return {
id: p.id,
srcServerId: String(p.srcServerId),
srcInterface: p.srcInterface || "",
name: p.name,
target: p.target,
filter: p.probeFilter || "—",
rtt: last?.rttMs ?? null,
loss: last?.lossPct ?? 100,
status: (last?.status ?? "down") as "up" | "warn" | "down",
series,
enabled: p.enabled,
}
})
const resources = allServers.map((s) => {
const rows = readResourceSamplesSince(sinceIso, s.id)
const last = rows[rows.length - 1]
const cpuHistory = toSeries(rows.map((r) => r.cpuLoad), 40)
return {
serverId: String(s.id),
cpu: last?.cpuLoad ?? 0,
cpuHistory,
ramUsed: Math.max(0, ((last?.totalMemory ?? 0) - (last?.freeMemory ?? 0)) / (1024 * 1024)),
ramTotal: Math.max(0, (last?.totalMemory ?? 0) / (1024 * 1024)),
hddUsed: Math.max(0, ((last?.totalHddSpace ?? 0) - (last?.freeHddSpace ?? 0)) / (1024 * 1024)),
hddTotal: Math.max(0, (last?.totalHddSpace ?? 0) / (1024 * 1024)),
uptimeSeconds: last?.uptimeSeconds ?? 0,
boardName: last?.boardName || "RouterBOARD",
temp: undefined as number | undefined,
}
})
return reply.send({ probes, resources })
})
}
export default uptimeRoutes