Клиент RouterOS открывал новое TCP-соединение на каждый запрос, а одна запись MCP делает 100–470 запросов. Замер на CHR: последовательный GET 105 -> 54 мс (CHR1) и 215 -> 114 мс (CHR2). Свободное соединение закрывается через 2 с простоя (RouterOS держит его 30 с), предел 2 сессии на роутер сохранён. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1440 lines
66 KiB
TypeScript
1440 lines
66 KiB
TypeScript
import http from "node:http"
|
||
import https from "node:https"
|
||
import { randomBytes } from "node:crypto"
|
||
import { dispatchBandwidthNativePermit, BandwidthAdmissionError, type BandwidthNativePermit } from "./bandwidth-admission.js"
|
||
import type { BandwidthNativeRequestBinder } from "./bandwidth-native-dispatch.js"
|
||
import { withConfigMutationLock, withApplicationMutationLock } from "./config-mutation-lock.js"
|
||
import { executeGuardedConfigurationWrite } from "./config-mutation-policy.js"
|
||
import { exportRouterConfiguration } from "./router-config-export.js"
|
||
import type { Server } from "../db/schema.js"
|
||
import { parseRosDataSizeBytes } from "./ros-metric-parse.js"
|
||
import { readOspfTemplateFlags } from "./ospf-template-flags.js"
|
||
import { readOspfEffectiveDisabled } from "./ospf-effective-disabled.js"
|
||
import { writeOspfTemplateCost, ospfCostConnectionProof, OspfCostWriteError } from "./ospf-template-cost-write.js"
|
||
import type {
|
||
RosIdentity, RosInterface, RosIpAddress, RosResource,
|
||
RosBgpSession,
|
||
RosOspfNeighbor, RosOspfArea, RosOspfInterfaceTemplate, RosOspfInstance,
|
||
RosBfdSession,
|
||
RosIpRoute, RosFirewallFilter, RosFirewallAddressList, RosLogEntry, RosPingResult,
|
||
FirewallFamily, FirewallTable,
|
||
} from "../types/server.js"
|
||
|
||
const MAX_ROS_BODY_BYTES = 8 * 1024 * 1024
|
||
// Shared pools bound concurrent REST logins across client instances. Reuse a
|
||
// connection within a burst of reads (one TCP/TLS handshake instead of one per
|
||
// request), but drop it after 2 s idle so RouterOS sessions are not held; RouterOS
|
||
// itself closes idle keep-alive connections after 30 s, so a reused socket is never stale.
|
||
export const ROS_IDLE_SOCKET_MS = 2000
|
||
const rosHttpAgent = new http.Agent({ keepAlive: true, timeout: ROS_IDLE_SOCKET_MS, maxSockets: 2 })
|
||
const rosHttpsAgent = new https.Agent({ keepAlive: true, timeout: ROS_IDLE_SOCKET_MS, maxSockets: 2 })
|
||
|
||
function watchRosResponseFailure(res: http.IncomingMessage, reject: (error: Error) => void): void {
|
||
res.once("aborted", () => reject(new Error("RouterOS response interrupted (ECONNRESET)")))
|
||
// IncomingMessage errors are separate from ClientRequest errors after headers arrive.
|
||
res.once("error", reject)
|
||
}
|
||
|
||
function appendRosBody(body: string, chunk: string, req?: http.ClientRequest): string {
|
||
if (Buffer.byteLength(body) + Buffer.byteLength(chunk) > MAX_ROS_BODY_BYTES) {
|
||
req?.destroy(new Error("RouterOS: ответ больше 8 МиБ"))
|
||
return body
|
||
}
|
||
return body + chunk
|
||
}
|
||
|
||
// ── connection params ─────────────────────────────────────────────────────────
|
||
|
||
export interface MikrotikConnectParams {
|
||
host: string
|
||
port: number
|
||
useSsl: boolean
|
||
verifySsl: boolean
|
||
username: string
|
||
password: string
|
||
apiPath?: string // defaults to "/rest"
|
||
routingEndpointEpoch?: string
|
||
/** Opt-in pinned diagnostic DNS; original host remains Host/TLS SNI. */
|
||
lookup?: typeof import("node:dns").lookup
|
||
servername?: string
|
||
}
|
||
|
||
// ── low-level HTTP helpers ────────────────────────────────────────────────────
|
||
|
||
const preHeaderGetResets = new WeakSet<Error>()
|
||
|
||
/** Transport provenance for scoped GET callers. The original error stays intact. */
|
||
export function isRouterOsPreHeaderGetReset(error: unknown): boolean {
|
||
return error instanceof Error && preHeaderGetResets.has(error)
|
||
}
|
||
|
||
function rosRequest(
|
||
params: MikrotikConnectParams,
|
||
path: string,
|
||
timeoutMs: number,
|
||
signal?: AbortSignal,
|
||
maxResponseBytes = MAX_ROS_BODY_BYTES,
|
||
): Promise<unknown> {
|
||
if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || maxResponseBytes > MAX_ROS_BODY_BYTES) return Promise.reject(new RangeError("Некорректный предел ответа RouterOS"))
|
||
return new Promise((resolve, reject) => {
|
||
const basePath = params.apiPath ?? "/rest"
|
||
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
||
|
||
const options: https.RequestOptions = {
|
||
hostname: params.host,
|
||
port: params.port,
|
||
path: basePath + path,
|
||
method: "GET",
|
||
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
||
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
||
signal,
|
||
lookup: params.lookup,
|
||
servername: params.servername,
|
||
}
|
||
|
||
const lib = params.useSsl ? https : http
|
||
options.agent = params.useSsl ? rosHttpsAgent : rosHttpAgent
|
||
|
||
let req: ReturnType<typeof lib.request> | undefined
|
||
let headersReceived = false, timedOut = false
|
||
const timer = setTimeout(() => {
|
||
timedOut = true
|
||
req?.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${timeoutMs / 1000}s`))
|
||
}, timeoutMs)
|
||
|
||
try {
|
||
req = lib.request(options, (res) => {
|
||
headersReceived = true
|
||
watchRosResponseFailure(res, error => { clearTimeout(timer); reject(error) })
|
||
let body = "", bytes = 0, failed = false
|
||
const failSize = () => {
|
||
failed = true
|
||
clearTimeout(timer)
|
||
const error = new Error("RouterOS: превышен предел байтов ответа")
|
||
reject(error)
|
||
res.destroy(error)
|
||
req?.destroy(error)
|
||
}
|
||
const length = res.headers["content-length"]
|
||
if (typeof length === "string" && /^\d+$/.test(length) && Number(length) > maxResponseBytes) { failSize(); return }
|
||
// Count transport bytes before decoding: multibyte text and split UTF-8 chunks share one budget.
|
||
const chunks: Buffer[] = []
|
||
res.on("data", (chunk: Buffer) => {
|
||
if (failed) return
|
||
bytes += chunk.length
|
||
if (bytes > maxResponseBytes) { failSize(); return }
|
||
chunks.push(chunk)
|
||
})
|
||
res.on("end", () => {
|
||
clearTimeout(timer)
|
||
if (failed) return
|
||
body = Buffer.concat(chunks, bytes).toString("utf8")
|
||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||
reject(new MikrotikError(res.statusCode ?? 0, path, body))
|
||
return
|
||
}
|
||
try {
|
||
resolve(JSON.parse(body))
|
||
} catch {
|
||
reject(new Error(`Invalid JSON from RouterOS: ${body.slice(0, 200)}`))
|
||
}
|
||
})
|
||
})
|
||
|
||
req.once("information", () => { headersReceived = true })
|
||
req.on("error", (err) => {
|
||
clearTimeout(timer)
|
||
if (!headersReceived && !timedOut && !signal?.aborted && (err as NodeJS.ErrnoException).code === "ECONNRESET") preHeaderGetResets.add(err)
|
||
reject(err)
|
||
})
|
||
|
||
req.end()
|
||
} catch(error) {clearTimeout(timer);reject(error)}
|
||
})
|
||
}
|
||
|
||
function rosPost(
|
||
params: MikrotikConnectParams,
|
||
path: string,
|
||
body: Record<string, string | string[]>,
|
||
timeoutMs: number,
|
||
externalSignal?: AbortSignal,
|
||
bindNativeRequest?: BandwidthNativeRequestBinder,
|
||
): Promise<unknown> {
|
||
return new Promise((resolve, reject) => {
|
||
const basePath = params.apiPath ?? "/rest"
|
||
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
||
const payload = JSON.stringify(body)
|
||
|
||
const options: https.RequestOptions = {
|
||
hostname: params.host,
|
||
port: params.port,
|
||
path: basePath + path,
|
||
method: "POST",
|
||
headers: {
|
||
Authorization: authHeader,
|
||
"Content-Type": "application/json",
|
||
"Content-Length": Buffer.byteLength(payload),
|
||
},
|
||
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
||
}
|
||
|
||
const lib = params.useSsl ? https : http
|
||
options.agent = params.useSsl ? rosHttpsAgent : rosHttpAgent
|
||
|
||
// An already-aborted signal can settle before the request is assigned.
|
||
// eslint-disable-next-line prefer-const
|
||
let req: ReturnType<typeof lib.request> | undefined
|
||
|
||
let settled = false
|
||
const settle = (fn: () => void) => {
|
||
if (settled) return
|
||
settled = true
|
||
if (req) {
|
||
req.setTimeout(0)
|
||
req.removeListener("timeout", onSocketTimeout)
|
||
}
|
||
externalSignal?.removeEventListener("abort", onExternalAbort)
|
||
fn()
|
||
}
|
||
|
||
const onExternalAbort = () => {
|
||
req?.destroy(new DOMException("Aborted", "AbortError"))
|
||
}
|
||
|
||
const onSocketTimeout = () => {
|
||
req?.destroy()
|
||
settle(() => reject(new Error(`Connection to ${params.host}:${params.port} timed out after ${timeoutMs / 1000}s`)))
|
||
}
|
||
|
||
if (externalSignal?.aborted) {
|
||
settle(() => reject(new DOMException("Aborted", "AbortError")))
|
||
return
|
||
}
|
||
externalSignal?.addEventListener("abort", onExternalAbort)
|
||
|
||
req = lib.request(options, (res) => {
|
||
watchRosResponseFailure(res, error => settle(() => reject(error)))
|
||
let buf = ""
|
||
res.setEncoding("utf8")
|
||
res.on("data", (chunk: string) => { buf = appendRosBody(buf, chunk, req) })
|
||
res.on("end", () => {
|
||
settle(() => {
|
||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||
reject(new MikrotikError(res.statusCode ?? 0, path, buf)); return
|
||
}
|
||
// A settings command with no return data can acknowledge with an empty body.
|
||
if (!buf.trim() && (path === "/ip/settings/set" || path === "/ipv6/settings/set")) {
|
||
resolve([])
|
||
return
|
||
}
|
||
try { resolve(JSON.parse(buf)) } catch {
|
||
reject(new Error(`Invalid JSON from RouterOS: ${buf.slice(0, 200)}`))
|
||
}
|
||
})
|
||
})
|
||
})
|
||
req.setTimeout(timeoutMs)
|
||
req.on("timeout", onSocketTimeout)
|
||
req.on("error", (err) => {
|
||
settle(() => reject(err))
|
||
})
|
||
if (!bindNativeRequest) {
|
||
req.write(payload)
|
||
req.end()
|
||
return
|
||
}
|
||
let bytesStarted = false
|
||
const sendBytesOnce = () => {
|
||
try {
|
||
if (bytesStarted) throw new BandwidthAdmissionError("REFUSED")
|
||
bytesStarted = true
|
||
externalSignal?.throwIfAborted()
|
||
req!.write(payload)
|
||
req!.end()
|
||
} catch (error) {
|
||
req!.destroy()
|
||
settle(() => reject(error))
|
||
throw error
|
||
}
|
||
}
|
||
try {
|
||
// The private gate may defer bytes until socket-ready reauthorization.
|
||
bindNativeRequest(req, sendBytesOnce)
|
||
} catch (error) {
|
||
req.destroy()
|
||
settle(() => reject(error))
|
||
}
|
||
})
|
||
}
|
||
|
||
function rosPut(
|
||
params: MikrotikConnectParams,
|
||
path: string,
|
||
body: Record<string, string>,
|
||
timeoutMs: number,
|
||
signal?: AbortSignal,
|
||
): Promise<unknown> {
|
||
return new Promise((resolve, reject) => {
|
||
const basePath = params.apiPath ?? "/rest"
|
||
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
||
const payload = JSON.stringify(body)
|
||
|
||
const options: https.RequestOptions = {
|
||
hostname: params.host,
|
||
port: params.port,
|
||
path: basePath + path,
|
||
method: "PUT",
|
||
signal,
|
||
headers: {
|
||
Authorization: authHeader,
|
||
"Content-Type": "application/json",
|
||
"Content-Length": Buffer.byteLength(payload),
|
||
},
|
||
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
||
}
|
||
|
||
const lib = params.useSsl ? https : http
|
||
options.agent = params.useSsl ? rosHttpsAgent : rosHttpAgent
|
||
const timer = setTimeout(() => {
|
||
req.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${timeoutMs / 1000}s`))
|
||
}, timeoutMs)
|
||
|
||
const req = lib.request(options, (res) => {
|
||
watchRosResponseFailure(res, error => { clearTimeout(timer); reject(error) })
|
||
let buf = ""
|
||
res.setEncoding("utf8")
|
||
res.on("data", (chunk: string) => { buf = appendRosBody(buf, chunk, req) })
|
||
res.on("end", () => {
|
||
clearTimeout(timer)
|
||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||
reject(new MikrotikError(res.statusCode ?? 0, path, buf))
|
||
return
|
||
}
|
||
try {
|
||
resolve(buf.trim() ? JSON.parse(buf) : {})
|
||
} catch {
|
||
reject(new Error(`Invalid JSON from RouterOS: ${buf.slice(0, 200)}`))
|
||
}
|
||
})
|
||
})
|
||
|
||
req.on("error", (err) => {
|
||
clearTimeout(timer)
|
||
reject(err)
|
||
})
|
||
req.write(payload)
|
||
req.end()
|
||
})
|
||
}
|
||
|
||
function rosDelete(
|
||
params: MikrotikConnectParams,
|
||
path: string,
|
||
timeoutMs: number,
|
||
onAcknowledgedBody?: (body: string) => void,
|
||
signal?: AbortSignal,
|
||
): Promise<void> {
|
||
return new Promise((resolve, reject) => {
|
||
const basePath = params.apiPath ?? "/rest"
|
||
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
||
|
||
const options: https.RequestOptions = {
|
||
hostname: params.host,
|
||
port: params.port,
|
||
path: basePath + path,
|
||
method: "DELETE",
|
||
signal,
|
||
headers: { Authorization: authHeader, "Content-Type": "application/json" },
|
||
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
||
}
|
||
|
||
const lib = params.useSsl ? https : http
|
||
options.agent = params.useSsl ? rosHttpsAgent : rosHttpAgent
|
||
const timer = setTimeout(() => {
|
||
req.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${timeoutMs / 1000}s`))
|
||
}, timeoutMs)
|
||
|
||
const req = lib.request(options, (res) => {
|
||
watchRosResponseFailure(res, error => { clearTimeout(timer); reject(error) })
|
||
let body = ""
|
||
res.setEncoding("utf8")
|
||
res.on("data", (chunk: string) => { body = appendRosBody(body, chunk, req) })
|
||
res.on("end", () => {
|
||
clearTimeout(timer)
|
||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||
reject(new MikrotikError(res.statusCode ?? 0, path, body)); return
|
||
}
|
||
try { onAcknowledgedBody?.(body); resolve() } catch (error) { reject(error) }
|
||
})
|
||
})
|
||
|
||
req.on("error", (err) => {
|
||
clearTimeout(timer)
|
||
reject(err)
|
||
})
|
||
req.end()
|
||
})
|
||
}
|
||
|
||
/** Запрос к RouterOS с сырым (не обязательно JSON) ответом — для содержимого файлов. */
|
||
function rosRawRequest(
|
||
params: MikrotikConnectParams,
|
||
opts: { method: "GET" | "POST"; path: string; body?: Record<string, string | string[]>; timeoutMs: number; signal?: AbortSignal; maxResponseBytes?: number },
|
||
): Promise<Buffer> {
|
||
return new Promise((resolve, reject) => {
|
||
const basePath = params.apiPath ?? "/rest"
|
||
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
||
const payload = opts.body ? JSON.stringify(opts.body) : undefined
|
||
|
||
const options: https.RequestOptions = {
|
||
hostname: params.host,
|
||
port: params.port,
|
||
path: basePath + opts.path,
|
||
method: opts.method,
|
||
headers: {
|
||
Authorization: authHeader,
|
||
...(payload
|
||
? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) }
|
||
: {}),
|
||
},
|
||
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
||
}
|
||
|
||
const lib = params.useSsl ? https : http
|
||
options.agent = params.useSsl ? rosHttpsAgent : rosHttpAgent
|
||
|
||
let settled = false
|
||
const finish = (work: () => void) => {
|
||
if (settled) return
|
||
settled = true; clearTimeout(timer); opts.signal?.removeEventListener("abort", abort); work()
|
||
}
|
||
const abort = () => req.destroy(new DOMException("Aborted", "AbortError"))
|
||
const limit = opts.maxResponseBytes ?? MAX_ROS_BODY_BYTES
|
||
const req = lib.request(options, (res) => {
|
||
watchRosResponseFailure(res, error => finish(() => reject(error)))
|
||
const chunks: Buffer[] = []
|
||
let bytes = 0
|
||
res.on("data", (chunk: Buffer) => {
|
||
if (settled) return
|
||
bytes += chunk.length
|
||
if (bytes > limit) { req.destroy(new Error("RouterOS raw response exceeds the byte limit")); return }
|
||
chunks.push(chunk)
|
||
})
|
||
res.on("end", () => {
|
||
if (settled) return
|
||
const buf = Buffer.concat(chunks)
|
||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||
finish(() => reject(new MikrotikError(res.statusCode ?? 0, opts.path, buf.toString("utf8").slice(0, 200))))
|
||
return
|
||
}
|
||
finish(() => resolve(buf))
|
||
})
|
||
})
|
||
|
||
const timer = setTimeout(() => {
|
||
req.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${opts.timeoutMs / 1000}s`))
|
||
}, opts.timeoutMs)
|
||
req.on("close", () => { clearTimeout(timer); opts.signal?.removeEventListener("abort", abort) })
|
||
req.on("error", (err) => {
|
||
finish(() => reject(err))
|
||
})
|
||
if (opts.signal?.aborted) { abort(); return }
|
||
opts.signal?.addEventListener("abort", abort, { once: true })
|
||
if (payload) req.write(payload)
|
||
req.end()
|
||
})
|
||
}
|
||
|
||
function rosPatch(
|
||
params: MikrotikConnectParams,
|
||
path: string,
|
||
body: Record<string, string>,
|
||
timeoutMs: number,
|
||
signal?: AbortSignal,
|
||
): Promise<unknown> {
|
||
return new Promise((resolve, reject) => {
|
||
const basePath = params.apiPath ?? "/rest"
|
||
const authHeader = "Basic " + Buffer.from(`${params.username}:${params.password}`).toString("base64")
|
||
const payload = JSON.stringify(body)
|
||
|
||
const options: https.RequestOptions = {
|
||
hostname: params.host,
|
||
port: params.port,
|
||
path: basePath + path,
|
||
method: "PATCH",
|
||
signal,
|
||
headers: {
|
||
Authorization: authHeader,
|
||
"Content-Type": "application/json",
|
||
"Content-Length": Buffer.byteLength(payload),
|
||
},
|
||
rejectUnauthorized: params.useSsl ? params.verifySsl : undefined,
|
||
}
|
||
|
||
const lib = params.useSsl ? https : http
|
||
options.agent = params.useSsl ? rosHttpsAgent : rosHttpAgent
|
||
const timer = setTimeout(() => {
|
||
req.destroy(new Error(`Connection to ${params.host}:${params.port} timed out after ${timeoutMs / 1000}s`))
|
||
}, timeoutMs)
|
||
|
||
const req = lib.request(options, (res) => {
|
||
watchRosResponseFailure(res, error => { clearTimeout(timer); reject(error) })
|
||
let buf = ""
|
||
res.setEncoding("utf8")
|
||
res.on("data", (chunk: string) => { buf = appendRosBody(buf, chunk, req) })
|
||
res.on("end", () => {
|
||
clearTimeout(timer)
|
||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||
reject(new MikrotikError(res.statusCode ?? 0, path, buf)); return
|
||
}
|
||
if (buf.trim() === "") {
|
||
resolve({})
|
||
return
|
||
}
|
||
try { resolve(JSON.parse(buf)) } catch {
|
||
reject(new Error("Некорректное JSON-подтверждение RouterOS: результат изменения неизвестен"))
|
||
}
|
||
})
|
||
})
|
||
|
||
req.on("error", (err) => {
|
||
clearTimeout(timer)
|
||
reject(err)
|
||
})
|
||
req.write(payload)
|
||
req.end()
|
||
})
|
||
}
|
||
|
||
/**
|
||
* RouterOS REST для одиночных меню (`/system/resource`, `/system/identity`) отдаёт JSON-массив из одного объекта `[{...}]`,
|
||
* а не сам объект. Без распаковки поля читаются с массива → всегда undefined и в БД уходят нули при «успехе».
|
||
* @see https://help.mikrotik.com/docs/spaces/ROS/pages/47579162/REST+API
|
||
*/
|
||
function unwrapRestSingle<T extends object>(raw: unknown): T {
|
||
if (Array.isArray(raw)) {
|
||
const first = raw[0]
|
||
if (first && typeof first === "object") return first as T
|
||
throw new Error("RouterOS REST: пустой массив вместо записи")
|
||
}
|
||
if (raw && typeof raw === "object") return raw as T
|
||
throw new Error("RouterOS REST: неожиданное тело ответа")
|
||
}
|
||
|
||
function routerFileBasename(fileName: string): string {
|
||
return fileName.replace(/^\/+/, "").split("/").pop() ?? fileName
|
||
}
|
||
|
||
function matchesUploadedFile(entryName: string, requested: string): boolean {
|
||
const base = routerFileBasename(requested)
|
||
return entryName === requested
|
||
|| entryName === base
|
||
|| entryName === `flash/${base}`
|
||
|| entryName.endsWith(`/${base}`)
|
||
}
|
||
|
||
/** Лимит команды `/file/get`: выше 61439 байт RouterOS молча отдаёт 0 байт. */
|
||
const MAX_FILE_GET_BYTES = 61439
|
||
/** Exact-ID /file/get supports strictly less than 61439 decoded bytes. */
|
||
export const MAX_OWNED_FILE_BYTES = MAX_FILE_GET_BYTES - 1
|
||
|
||
const RET_MARKER = Buffer.from('"ret":', "latin1")
|
||
const CONTENTS_MARKER = Buffer.from('"contents":', "latin1")
|
||
|
||
function assertRosFileReadable(entry: { name: string; size: number }): void {
|
||
if (entry.size >= MAX_FILE_GET_BYTES) {
|
||
throw new Error(
|
||
`Файл ${routerFileBasename(entry.name)} больше ${MAX_FILE_GET_BYTES / 1024} КБ — `
|
||
+ "RouterOS REST отдаёт содержимое только до 60 КБ (используйте SCP/FTP)",
|
||
)
|
||
}
|
||
}
|
||
|
||
/** Превью ответа RouterOS для диагностики: непечатаемые байты → `\uXXXX`. */
|
||
function rosResponsePreview(raw: Buffer, limit = 200): string {
|
||
const slice = raw.subarray(0, limit)
|
||
let out = ""
|
||
for (const byte of slice) {
|
||
if (byte >= 0x20 && byte < 0x7f) out += String.fromCharCode(byte)
|
||
else out += `\\u${byte.toString(16).padStart(4, "0")}`
|
||
}
|
||
return out
|
||
}
|
||
|
||
/**
|
||
* RouterOS REST отдаёт содержимое файла в JSON-подобной обёртке, но строку — в single-byte
|
||
* кодировке и экранирует лишь часть символов, из-за чего `JSON.parse` падает
|
||
* (см. https://forum.mikrotik.com/t/bug-rest-endpoint-producing-invalid-json/177486).
|
||
* Значение извлекаем напрямую из сырых байтов, без парсинга всего ответа.
|
||
* Команда `get` кладёт результат в поле `ret` (`!done=ret=...`), команда `print` — в `contents`.
|
||
* @see https://help.mikrotik.com/docs/spaces/ROS/pages/47579160/API
|
||
* @see https://help.mikrotik.com/docs/spaces/ROS/pages/2555971/Files
|
||
*/
|
||
export function extractRosContentsField(raw: Buffer, field: "contents" | "data" = "contents"): Buffer {
|
||
const start = field === "data"
|
||
? findRosStringField(raw, Buffer.from('"data":', "latin1"))
|
||
: findRosStringField(raw, RET_MARKER) ?? findRosStringField(raw, CONTENTS_MARKER)
|
||
if (start == null) {
|
||
if (field === "data") throw new Error("Ответ RouterOS не содержит строковое поле data")
|
||
throw new Error(`ответ не содержит поле ret/contents (${rosResponsePreview(raw)})`)
|
||
}
|
||
|
||
const out: number[] = []
|
||
let i = start
|
||
while (i < raw.length) {
|
||
const byte = raw[i]
|
||
if (byte === 0x22) return Buffer.from(out) // закрывающая кавычка
|
||
if (byte !== 0x5c) { // обычный байт
|
||
out.push(byte)
|
||
i += 1
|
||
continue
|
||
}
|
||
const esc = raw[i + 1]
|
||
if (esc === undefined) break
|
||
i += 2
|
||
switch (esc) {
|
||
case 0x22: out.push(0x22); break // \"
|
||
case 0x5c: out.push(0x5c); break // \\
|
||
case 0x2f: out.push(0x2f); break // \/
|
||
case 0x62: out.push(0x08); break // \b
|
||
case 0x66: out.push(0x0c); break // \f
|
||
case 0x6e: out.push(0x0a); break // \n
|
||
case 0x72: out.push(0x0d); break // \r
|
||
case 0x74: out.push(0x09); break // \t
|
||
case 0x75: { // \uXXXX
|
||
const hex = raw.subarray(i, i + 4).toString("latin1")
|
||
if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw new Error("некорректный \\u-escape в содержимом файла")
|
||
i += 4
|
||
for (const b of Buffer.from(String.fromCharCode(parseInt(hex, 16)), "utf8")) out.push(b)
|
||
break
|
||
}
|
||
default: out.push(esc)
|
||
}
|
||
}
|
||
throw new Error("строка содержимого файла не закрыта")
|
||
}
|
||
|
||
/**
|
||
* Ищет ключ JSON и возвращает индекс первого байта строкового значения (после открывающей кавычки).
|
||
* Возвращает null, если ключа нет или за ним не строка.
|
||
*/
|
||
function findRosStringField(raw: Buffer, marker: Buffer): number | null {
|
||
let from = 0
|
||
for (;;) {
|
||
const at = raw.indexOf(marker, from)
|
||
if (at < 0) return null
|
||
let i = at + marker.length
|
||
while (i < raw.length && isRosJsonSpace(raw[i])) i += 1
|
||
if (raw[i] === 0x22) return i + 1
|
||
from = at + marker.length
|
||
}
|
||
}
|
||
|
||
function isRosJsonSpace(byte: number): boolean {
|
||
return byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d
|
||
}
|
||
|
||
export function firewallRestPath(
|
||
family: FirewallFamily,
|
||
table: FirewallTable | "address-list",
|
||
): string {
|
||
const root = family === "ip6" ? "/ipv6/firewall" : "/ip/firewall"
|
||
return `${root}/${table}`
|
||
}
|
||
|
||
export { encodeRosId } from "./routeros-native-paths.js"
|
||
|
||
// ── MikrotikClient ─────────────────────────────────────────────────────────────
|
||
|
||
/** Имя параметра из ошибки RouterOS `unknown parameter <name>` (400) — для деградации запроса. */
|
||
function unknownParameterName(error: MikrotikError): string | undefined {
|
||
if (error.statusCode !== 400) return undefined
|
||
const match = error.body.match(/unknown parameter\s+"?([A-Za-z0-9_-]+)"?/i)
|
||
return match?.[1]
|
||
}
|
||
|
||
/**
|
||
* RouterOS отклоняет `export-passphrase` короче 8 символов:
|
||
* `Failure: If used, passphrase must be at least 8 chars long!`.
|
||
* Та же ошибка приходит, если политика `sensitive` не даёт применить sensitive-параметр.
|
||
*/
|
||
export function isPassphraseTooShortError(error: unknown): boolean {
|
||
return (
|
||
error instanceof MikrotikError &&
|
||
error.statusCode === 400 &&
|
||
/passphrase/i.test(error.body) &&
|
||
/at least\s*8/i.test(error.body)
|
||
)
|
||
}
|
||
|
||
/** Пароль .p12, который RouterOS примет гарантированно (≥8 символов). */
|
||
function generateExportPassphrase(): string {
|
||
return randomBytes(12).toString("base64url")
|
||
}
|
||
|
||
const EXPORT_PASSPHRASE_HINT =
|
||
"RouterOS отклонил пароль .p12. Экспорт приватного ключа (export-passphrase — sensitive-параметр) " +
|
||
"разрешён только пользователю, у которого в политике группы есть «sensitive». " +
|
||
"Проверьте: /user print → группа API-пользователя → /user group print; добавьте sensitive в policy группы " +
|
||
"(в группе full она уже есть)."
|
||
|
||
export class MikrotikClient {
|
||
private readonly requireBandwidthPermit:boolean
|
||
constructor(private readonly params: MikrotikConnectParams, private readonly serverId?: number, options?:{requireBandwidthPermit:true}) {
|
||
if(options!==undefined&&(Object.keys(options).join(",")!=="requireBandwidthPermit"||options.requireBandwidthPermit!==true))throw new BandwidthAdmissionError("INVALID_INPUT")
|
||
this.requireBandwidthPermit=options?.requireBandwidthPermit===true
|
||
if(this.requireBandwidthPermit)this.params=Object.freeze({...params})
|
||
}
|
||
|
||
private mutation<T>(method: string, path: string, work: (signal?: AbortSignal) => Promise<T>): Promise<T> {
|
||
const serverId = this.serverId
|
||
// Endpoint parameters (including an incidental params.id) never establish
|
||
// the managed source of a configuration write. Production factories pass
|
||
// the actual selected server row's ID as the explicit constructor binding.
|
||
if (typeof serverId !== "number" || !Number.isSafeInteger(serverId) || serverId <= 0) {
|
||
return Promise.reject(Object.assign(new Error("Для изменения RouterOS требуется привязка к управляемому серверу"), { code: "MIKROTIK_MANAGED_SOURCE_REQUIRED" }))
|
||
}
|
||
return withConfigMutationLock([serverId], () => executeGuardedConfigurationWrite(serverId, method, path, work))
|
||
}
|
||
|
||
/** Convenience factory from a DB Server row */
|
||
static fromServer(server: Server, options?:{requireBandwidthPermit:true}): MikrotikClient {
|
||
return new MikrotikClient({
|
||
host: server.host,
|
||
port: server.port,
|
||
useSsl: server.useSsl,
|
||
verifySsl: server.verifySsl,
|
||
username: server.username,
|
||
password: server.password,
|
||
routingEndpointEpoch: server.routingEndpointEpoch,
|
||
}, server.id, options)
|
||
}
|
||
|
||
/** Optional live admission runs once immediately before constructing the GET.
|
||
* It is not a socket-send hook: DNS/TLS and agent queueing follow admission. */
|
||
async get<T>(path: string, timeoutMs = 10_000, signal?: AbortSignal, maxResponseBytes?: number, beforeDispatch?: () => Promise<unknown>): Promise<T> {
|
||
if (beforeDispatch) {
|
||
signal?.throwIfAborted()
|
||
await beforeDispatch()
|
||
signal?.throwIfAborted()
|
||
}
|
||
return rosRequest(this.params, path, timeoutMs, signal, maxResponseBytes) as Promise<T>
|
||
}
|
||
|
||
async post<T>(path: string, body: Record<string, string | string[]>, timeoutMs = 15_000, signal?: AbortSignal, beforeDispatch?: () => Promise<unknown>, bandwidthPermit?:BandwidthNativePermit): Promise<T> {
|
||
signal?.throwIfAborted()
|
||
const bandwidthPrefix=/(?:^|\/)tool\/bandwidth-test(?:\/|$)/i
|
||
// A malformed query escape must not hide an otherwise valid command path.
|
||
// Classify its raw prefix even when percent decoding later fails.
|
||
let bandwidthPath=false
|
||
// rosPost concatenates apiPath + path. Check that final request target as
|
||
// well, otherwise a custom base can split the command across both inputs.
|
||
for(const target of [path,(this.params.apiPath??"/rest")+path]){
|
||
const pathOnly=target.split(/[?#]/,1)[0].replace(/\/{2,}/g,"/")
|
||
bandwidthPath||=bandwidthPrefix.test(pathOnly)
|
||
try{
|
||
let decoded=pathOnly
|
||
for(let pass=0;pass<2;pass++){
|
||
// Decode segments independently: a literal percent in an unrelated
|
||
// proxy prefix must not hide an encoded command further down.
|
||
decoded=decoded.split("/").map(segment=>{try{return decodeURIComponent(segment)}catch{return segment}}).join("/")
|
||
const normalized=decoded.replace(/\/{2,}/g,"/")
|
||
bandwidthPath||=bandwidthPrefix.test(normalized)||bandwidthPrefix.test(new URL(normalized,"http://router.invalid").pathname)
|
||
}
|
||
}catch{/* The raw canonical prefix remains guarded on malformed escapes. */}
|
||
}
|
||
const guardedBandwidth=bandwidthPermit!==undefined||this.requireBandwidthPermit&&bandwidthPath
|
||
if(guardedBandwidth&&bandwidthPermit===undefined)throw new BandwidthAdmissionError("REFUSED")
|
||
let nativeBody=body
|
||
if(guardedBandwidth){
|
||
if(!body||Object.getPrototypeOf(body)!==Object.prototype)throw new BandwidthAdmissionError("REFUSED")
|
||
const descriptors=Object.getOwnPropertyDescriptors(body)
|
||
if(Object.values(descriptors).some(value=>!("value" in value)||!value.enumerable||typeof value.value!=="string"))throw new BandwidthAdmissionError("REFUSED")
|
||
nativeBody=Object.freeze(Object.fromEntries(Object.entries(descriptors).map(([key,value])=>[key,value.value as string])))
|
||
}
|
||
const work = async (leaseSignal?: AbortSignal) => {
|
||
const nativeSignal = leaseSignal && signal ? AbortSignal.any([leaseSignal, signal]) : leaseSignal ?? signal
|
||
nativeSignal?.throwIfAborted();await beforeDispatch?.();nativeSignal?.throwIfAborted()
|
||
// Private dispatcher owns any permit-bound gate through actual socket
|
||
// handoff. Public post arguments, mutation audit and response stay intact.
|
||
if(guardedBandwidth)return dispatchBandwidthNativePermit(bandwidthPermit,this,path,nativeBody,signal, bind => {
|
||
nativeSignal?.throwIfAborted()
|
||
return rosPost(this.params,path,nativeBody,timeoutMs,nativeSignal,bind) as Promise<T>
|
||
})
|
||
return rosPost(this.params,path,nativeBody,timeoutMs,nativeSignal) as Promise<T>
|
||
}
|
||
// POST read selectors belong in the body. A suffix in a query string or
|
||
// fragment must never exempt a write pathname from the mutation guard.
|
||
const readCommand = !/[?#]/.test((this.params.apiPath ?? "/rest") + path) && (
|
||
path.endsWith("/get") || path.endsWith("/print") || path.endsWith("/monitor") ||
|
||
["/ping", "/tool/ping", "/tool/traceroute", "/interface/monitor-traffic"].includes(path))
|
||
// The private permit dispatcher independently authenticates exact source,
|
||
// body and bandwidth path before sending. This existing id-less diagnostic
|
||
// path grants no unscoped configuration write or legacy bandwidth bypass.
|
||
if (guardedBandwidth && this.serverId === undefined) return work()
|
||
return readCommand ? work() : this.mutation("POST", path, work)
|
||
}
|
||
|
||
async put<T>(path: string, body: Record<string, string>, timeoutMs = 15_000, beforeDispatch?:()=>Promise<unknown>): Promise<T> {
|
||
return this.mutation("PUT", path, async signal => { await beforeDispatch?.(); signal?.throwIfAborted(); return rosPut(this.params, path, body, timeoutMs, signal) as Promise<T> })
|
||
}
|
||
|
||
async delete(path: string, timeoutMs = 10_000, beforeDispatch?:()=>Promise<unknown>, onAcknowledgedBody?: (body: string) => void): Promise<void> {
|
||
return this.mutation("DELETE", path, async signal => { await beforeDispatch?.(); signal?.throwIfAborted(); return rosDelete(this.params, path, timeoutMs, onAcknowledgedBody, signal) })
|
||
}
|
||
|
||
async patch<T>(path: string, body: Record<string, string>, timeoutMs = 15_000, beforeDispatch?: () => Promise<unknown>): Promise<T> {
|
||
return this.mutation("PATCH", path, async signal => {
|
||
await beforeDispatch?.()
|
||
signal?.throwIfAborted()
|
||
return rosPatch(this.params, path, body, timeoutMs, signal) as Promise<T>
|
||
})
|
||
}
|
||
|
||
// ── typed helpers ──────────────────────────────────────────────────────────
|
||
|
||
async getIdentity(): Promise<RosIdentity> {
|
||
const raw = await this.get<unknown>("/system/identity")
|
||
return unwrapRestSingle<RosIdentity>(raw)
|
||
}
|
||
|
||
async getResource(): Promise<RosResource> {
|
||
const raw = await this.get<unknown>("/system/resource")
|
||
if (Array.isArray(raw)) {
|
||
if (raw.length === 0) throw new Error("RouterOS REST: пустой массив вместо записи /system/resource")
|
||
if (raw.length === 1) return unwrapRestSingle<RosResource>(raw[0])
|
||
/** Несколько объектов: взять строку с total-memory (агрегат), а не дочернюю запись с «чужим» uptime. */
|
||
const objs = raw.filter((x): x is Record<string, unknown> => x != null && typeof x === "object" && !Array.isArray(x))
|
||
/** На части железа несколько строк; «первая с непустым total-memory» может парситься в 0 — берём запись с максимальным RAM. */
|
||
let best: Record<string, unknown> | undefined
|
||
let bestBytes = -1
|
||
for (const o of objs) {
|
||
const tm = parseRosDataSizeBytes(o["total-memory"])
|
||
const fm = parseRosDataSizeBytes(o["free-memory"])
|
||
const score = tm > 0 ? tm : fm
|
||
if (score > bestBytes) {
|
||
bestBytes = score
|
||
best = o
|
||
}
|
||
}
|
||
const main = objs.find((o) => {
|
||
const tm = o["total-memory"]
|
||
return tm != null && String(tm).trim() !== ""
|
||
})
|
||
return ((bestBytes > 0 ? best : undefined) ?? main ?? objs[0]) as unknown as RosResource
|
||
}
|
||
return unwrapRestSingle<RosResource>(raw)
|
||
}
|
||
|
||
async getInterfaces(): Promise<RosInterface[]> {
|
||
return this.get<RosInterface[]>("/interface")
|
||
}
|
||
|
||
async getIpAddresses(): Promise<RosIpAddress[]> {
|
||
return this.get<RosIpAddress[]>("/ip/address")
|
||
}
|
||
|
||
async getBgpSessions(): Promise<RosBgpSession[]> {
|
||
return this.get<RosBgpSession[]>("/routing/bgp/session")
|
||
}
|
||
|
||
/** Returns the raw (un-typed) BGP session objects — used for debugging */
|
||
async getBgpSessionsRaw(): Promise<unknown[]> {
|
||
return this.get<unknown[]>("/routing/bgp/session")
|
||
}
|
||
|
||
// ── OSPF ──────────────────────────────────────────────────────────────────
|
||
|
||
async getOspfNeighbors(): Promise<RosOspfNeighbor[]> {
|
||
return this.get<RosOspfNeighbor[]>("/routing/ospf/neighbor")
|
||
}
|
||
|
||
async getOspfAreas(): Promise<RosOspfArea[]> {
|
||
return readOspfEffectiveDisabled<RosOspfArea>(await this.get<unknown>("/routing/ospf/area"), id =>
|
||
this.post("/routing/ospf/area/get", { ".id": id, "value-name": "disabled" }))
|
||
}
|
||
|
||
async getOspfInterfaceTemplates(beforeRead: () => Promise<unknown> = async () => {}): Promise<RosOspfInterfaceTemplate[]> {
|
||
await beforeRead()
|
||
return readOspfTemplateFlags<RosOspfInterfaceTemplate>(await this.get<unknown>("/routing/ospf/interface-template"), (id, key) =>
|
||
this.post("/routing/ospf/interface-template/get", { ".id": id, "value-name": key }), beforeRead, async () => {
|
||
await beforeRead()
|
||
const present = await this.post<unknown>("/routing/ospf/interface-template/print", { ".proplist": [".id"], ".query": ["passive"] })
|
||
await beforeRead()
|
||
const absent = await this.post<unknown>("/routing/ospf/interface-template/print", { ".proplist": [".id"], ".query": ["passive", "#!"] })
|
||
return { present, absent }
|
||
})
|
||
}
|
||
|
||
async getOspfInstances(): Promise<RosOspfInstance[]> {
|
||
return readOspfEffectiveDisabled<RosOspfInstance>(await this.get<unknown>("/routing/ospf/instance"), id =>
|
||
this.post("/routing/ospf/instance/get", { ".id": id, "value-name": "disabled" }))
|
||
}
|
||
|
||
async getBfdSessions(): Promise<RosBfdSession[]> {
|
||
return this.get<RosBfdSession[]>("/routing/bfd/session")
|
||
}
|
||
|
||
async setOspfInterfaceTemplateCost(templateId: string, cost: number, expectedCost?: number, expectedServerProof?: string, beforeWrite?: () => Promise<unknown>): Promise<void> {
|
||
const safeId = templateId.startsWith("*") ? templateId : `*${templateId.replace(/^\*/, "")}`
|
||
const assertSource = async () => {
|
||
if (expectedServerProof !== undefined && (this.serverId === undefined || expectedServerProof !== await ospfCostConnectionProof(this.serverId, this.params))) throw new OspfCostWriteError("Источник OSPF изменился после подготовки плана", false)
|
||
if (this.serverId === undefined) return
|
||
const { pool } = await import("../db/index.js")
|
||
const row = (await pool.query("SELECT host,port,use_ssl,verify_ssl,username,password,enabled,routing_endpoint_epoch FROM servers WHERE id=$1", [this.serverId])).rows[0]
|
||
if (!row || row.enabled !== true || row.host !== this.params.host || Number(row.port) !== this.params.port || row.use_ssl !== this.params.useSsl || row.verify_ssl !== this.params.verifySsl || row.username !== this.params.username || row.password !== this.params.password || row.routing_endpoint_epoch !== this.params.routingEndpointEpoch) throw new OspfCostWriteError("Параметры подключения OSPF изменились; запись не отправлена", false)
|
||
}
|
||
const work = async () => { await writeOspfTemplateCost(safeId, cost, { expectedCost,
|
||
// The cost writer preserves raw native fields, including omitted defaults.
|
||
// It needs no per-row disabled getter and performs two bounded GETs only.
|
||
read: async () => { await assertSource(); return this.get<unknown>("/routing/ospf/interface-template") },
|
||
write: async (id, next) => {
|
||
await assertSource()
|
||
return this.patch(`/routing/ospf/interface-template/${encodeURIComponent(id)}`, { cost: String(next) },15000,beforeWrite?async()=>{
|
||
try{await beforeWrite()}catch{throw new OspfCostWriteError("Допуск или источники OSPF изменились перед отправкой; запись не отправлена",false)}
|
||
await assertSource()
|
||
}:undefined)
|
||
} }) }
|
||
await (this.serverId === undefined ? work() : withApplicationMutationLock(() => withConfigMutationLock([this.serverId!], work)))
|
||
}
|
||
|
||
// ── extra endpoints for exec route ────────────────────────────────────────
|
||
|
||
async getIpRoutes(): Promise<RosIpRoute[]> {
|
||
return this.get<RosIpRoute[]>("/ip/route")
|
||
}
|
||
|
||
async getIpv6Routes(): Promise<RosIpRoute[]> {
|
||
return this.get<RosIpRoute[]>("/ipv6/route")
|
||
}
|
||
|
||
async getFirewallFilters(): Promise<RosFirewallFilter[]> {
|
||
return this.getFirewallRules("ip", "filter")
|
||
}
|
||
|
||
async getFirewallRules(family: FirewallFamily, table: FirewallTable): Promise<RosFirewallFilter[]> {
|
||
return this.get<RosFirewallFilter[]>(firewallRestPath(family, table))
|
||
}
|
||
|
||
async getFirewallAddressList(family: FirewallFamily): Promise<RosFirewallAddressList[]> {
|
||
return this.get<RosFirewallAddressList[]>(firewallRestPath(family, "address-list"))
|
||
}
|
||
|
||
async getLogBuffer(): Promise<RosLogEntry[]> {
|
||
const entries = await this.get<unknown>("/log?buffer=memory&.proplist=.id,time,topics,message", 8_000)
|
||
if (!Array.isArray(entries) || entries.some(e => !e || [".id", "time", "topics", "message"].some(k => typeof e[k] !== "string"))) {
|
||
throw new Error("RouterOS: некорректный буфер логов")
|
||
}
|
||
return entries as RosLogEntry[]
|
||
}
|
||
|
||
async getLogs(limit = 50): Promise<RosLogEntry[]> {
|
||
if (!Number.isSafeInteger(limit) || limit < 1) {
|
||
throw new RangeError("limit должен быть положительным целым числом.")
|
||
}
|
||
// REST query parameters filter properties; limit is not a print row limit.
|
||
// Read only the default buffer and retain its latest entries in native order.
|
||
const entries = await this.getLogBuffer()
|
||
return entries.slice(-Math.min(limit, 200))
|
||
}
|
||
|
||
async ping(
|
||
address: string,
|
||
count = 4,
|
||
interfaceName?: string,
|
||
options?: { interval?: string; signal?: AbortSignal; beforeDispatch?: () => Promise<unknown> },
|
||
): Promise<RosPingResult[]> {
|
||
const body: Record<string, string> = {
|
||
address,
|
||
count: String(count),
|
||
}
|
||
if (options?.interval && options.interval.trim()) body.interval = options.interval.trim()
|
||
else body.interval = "0.2s"
|
||
if (interfaceName && interfaceName.trim()) body.interface = interfaceName.trim()
|
||
return this.post<RosPingResult[]>("/tool/ping", body, 20_000, options?.signal, options?.beforeDispatch)
|
||
}
|
||
|
||
async bandwidthTest(params: {
|
||
address: string
|
||
user: string
|
||
password: string
|
||
protocol?: "tcp" | "udp"
|
||
direction?: "transmit" | "receive" | "both"
|
||
durationSec?: number
|
||
maxMbps?: number
|
||
}, signal?: AbortSignal, beforeDispatch?: () => Promise<unknown>, bandwidthPermit?:BandwidthNativePermit): Promise<Array<Record<string, string>>> {
|
||
if(params.maxMbps!==undefined&&(!Number.isSafeInteger(params.maxMbps)||params.maxMbps<1||params.maxMbps>1000))throw new Error("Лимит скорости должен быть целым числом от 1 до 1000 Мбит/с")
|
||
const body: Record<string, string> = {
|
||
address: params.address,
|
||
user: params.user,
|
||
password: params.password,
|
||
protocol: params.protocol ?? "tcp",
|
||
direction: params.direction ?? "both",
|
||
duration: `${Math.max(3, params.durationSec ?? 10)}s`,
|
||
}
|
||
if(params.maxMbps!==undefined){body["local-tx-speed"]=String(params.maxMbps*1000000);body["remote-tx-speed"]=String(params.maxMbps*1000000)}
|
||
return this.post<Array<Record<string, string>>>("/tool/bandwidth-test", body, 30_000, signal, beforeDispatch, bandwidthPermit)
|
||
}
|
||
|
||
async getCertificates(): Promise<Array<Record<string, string | undefined>>> {
|
||
const raw = await this.get<unknown>("/certificate")
|
||
if (!Array.isArray(raw)) return []
|
||
return raw.filter((row): row is Record<string, string | undefined> => row != null && typeof row === "object")
|
||
}
|
||
|
||
async listFiles(): Promise<Array<{ id: string; name: string; size: number }>> {
|
||
const raw = await this.get<unknown>("/file")
|
||
if (!Array.isArray(raw)) return []
|
||
return raw
|
||
.filter((row): row is Record<string, unknown> => row != null && typeof row === "object")
|
||
.map((row) => ({
|
||
id: String(row[".id"] ?? ""),
|
||
name: String(row.name ?? ""),
|
||
size: Number(row.size ?? 0),
|
||
}))
|
||
.filter((row) => row.name.length > 0 && row.id.length > 0)
|
||
}
|
||
|
||
/** Поиск файла в `/file` по полному имени, базовому имени или `flash/<base>`. */
|
||
private async findFileEntry(name: string): Promise<{ id: string; name: string; size: number } | undefined> {
|
||
const base = routerFileBasename(name)
|
||
const files = await this.listFiles()
|
||
return files.find((file) => file.name === name)
|
||
?? files.find((file) => file.name === base)
|
||
?? files.find((file) => file.name === `flash/${base}`)
|
||
?? files.find((file) => routerFileBasename(file.name) === base)
|
||
}
|
||
|
||
private async resolveUploadedFileName(requested: string): Promise<string> {
|
||
const files = await this.listFiles()
|
||
const match = files.find((file) => matchesUploadedFile(file.name, requested))
|
||
if (!match) {
|
||
throw new Error(`Файл ${routerFileBasename(requested)} не найден на RouterOS после загрузки`)
|
||
}
|
||
return match.name
|
||
}
|
||
|
||
async uploadTextFile(fileName: string, contents: string, timeoutMs = 30_000): Promise<string> {
|
||
const payload = contents.endsWith("\n") ? contents : `${contents}\n`
|
||
return this.resolveUploadedFileName(await this.writeTextFile(routerFileBasename(fileName), payload, timeoutMs))
|
||
}
|
||
|
||
async uploadConfigurationScript(fileName: string, contents: string, timeoutMs = 30_000): Promise<string> {
|
||
const payload = contents.endsWith("\n") ? contents : `${contents}\n`
|
||
const expected = Buffer.from(payload, "utf8")
|
||
if (expected.length > MAX_ROS_BODY_BYTES) throw new Error("Файл восстановления RouterOS больше 8 МиБ")
|
||
const name = await this.writeTextFile(routerFileBasename(fileName), payload, timeoutMs)
|
||
const rows = (await this.listFiles()).filter(row => row.name === name)
|
||
const file = rows[0]
|
||
if (rows.length !== 1 || !/^\*[a-z0-9]+$/i.test(file.id) || file.size !== expected.length) {
|
||
throw new Error("RouterOS не подтвердил имя, ID или размер файла восстановления")
|
||
}
|
||
const actual = await this.downloadConfigurationFile(file)
|
||
if (!actual.equals(expected)) throw new Error("Содержимое файла восстановления RouterOS отличается от резервной копии")
|
||
return name
|
||
}
|
||
|
||
private async writeTextFile(normalized: string, payload: string, timeoutMs: number): Promise<string> {
|
||
const candidates = [`flash/${normalized}`, normalized]
|
||
let lastError: unknown
|
||
|
||
for (const name of candidates) {
|
||
let uploaded = true
|
||
try {
|
||
await this.put("/file", { name, contents: payload }, timeoutMs)
|
||
} catch (error) {
|
||
if (!(error instanceof MikrotikError) || ![404, 405].includes(error.statusCode)) throw error
|
||
uploaded = false
|
||
lastError = error
|
||
}
|
||
if (uploaded) return name
|
||
|
||
try {
|
||
await this.post("/file/add", { name, contents: payload, type: "file" }, timeoutMs)
|
||
} catch (error) {
|
||
if (!(error instanceof MikrotikError) || ![404, 405].includes(error.statusCode)) throw error
|
||
lastError = error
|
||
continue
|
||
}
|
||
return name
|
||
}
|
||
|
||
throw lastError instanceof Error
|
||
? lastError
|
||
: new Error(`Не удалось загрузить файл ${normalized} на RouterOS`)
|
||
}
|
||
|
||
async importUploadedFile(fileName: string): Promise<unknown> {
|
||
try {
|
||
return await this.post("/import", { "file-name": fileName }, 120_000)
|
||
} catch (error) {
|
||
if (!(error instanceof MikrotikError) || ![404, 405].includes(error.statusCode)) throw error
|
||
return await this.post("/execute", { script: `/import file-name="${fileName}"` }, 120_000)
|
||
}
|
||
}
|
||
|
||
async importCertificate(params: {
|
||
fileName: string
|
||
name: string
|
||
trusted?: boolean
|
||
trustStore?: string
|
||
passphrase?: string
|
||
}): Promise<unknown> {
|
||
const body: Record<string, string> = {
|
||
"file-name": params.fileName,
|
||
name: params.name,
|
||
trusted: params.trusted === false ? "no" : "yes",
|
||
"trust-store": params.trustStore?.trim() || "www,api",
|
||
}
|
||
if (params.passphrase?.trim()) body.passphrase = params.passphrase.trim()
|
||
return this.post("/certificate/import", body, 60_000)
|
||
}
|
||
|
||
async applyCertificateToServices(certName: string): Promise<void> {
|
||
const body = {
|
||
disabled: "no",
|
||
certificate: certName,
|
||
}
|
||
for (const serviceName of ["www-ssl", "api-ssl"]) {
|
||
await this.patchIpService(serviceName, body)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Чтение содержимого файла RouterOS. Путь `GET /file/<name>` не существует — RouterOS
|
||
* отвечает `no such command prefix`; используются команды `get`/`print`.
|
||
* @see https://help.mikrotik.com/docs/spaces/ROS/pages/2555971/Files
|
||
*/
|
||
private async readFileContents(
|
||
target: { id?: string; name?: string },
|
||
timeoutMs = 30_000,
|
||
): Promise<Buffer> {
|
||
const readOnce = async (id?: string, name?: string): Promise<Buffer> => {
|
||
const strategies: Array<{ path: string; body: Record<string, string | string[]> }> = []
|
||
if (id) {
|
||
strategies.push({ path: "/file/get", body: { ".id": id, "value-name": "contents" } })
|
||
strategies.push({ path: "/file/get", body: { ".id": id, ".proplist": "contents" } })
|
||
}
|
||
if (name) {
|
||
strategies.push({ path: "/file/print", body: { ".proplist": "contents", ".query": [`name=${name}`] } })
|
||
}
|
||
if (strategies.length === 0) throw new Error("не задан файл для чтения")
|
||
|
||
let lastError: unknown
|
||
for (const strategy of strategies) {
|
||
try {
|
||
const raw = await rosRawRequest(this.params, {
|
||
method: "POST",
|
||
path: strategy.path,
|
||
body: strategy.body,
|
||
timeoutMs,
|
||
})
|
||
const content = extractRosContentsField(raw)
|
||
if (content.length > 0) return content
|
||
lastError = new Error("RouterOS вернул пустое содержимое файла")
|
||
} catch (error) {
|
||
lastError = error
|
||
}
|
||
}
|
||
throw lastError instanceof Error ? lastError : new Error("не удалось прочитать содержимое файла")
|
||
}
|
||
|
||
try {
|
||
return await readOnce(target.id, target.name)
|
||
} catch (error) {
|
||
// `.id` мог устареть (файл пересоздан) — пробуем один раз найти его заново по имени.
|
||
if (!target.name) throw error
|
||
const fresh = await this.findFileEntry(target.name)
|
||
if (!fresh || fresh.id === target.id) throw error
|
||
return readOnce(fresh.id, fresh.name)
|
||
}
|
||
}
|
||
|
||
/** Скачивание содержимого файла RouterOS: `/file/get` + побайтовый разбор (лимит 60 КБ). */
|
||
async downloadFile(
|
||
target: { name: string; id?: string; size?: number },
|
||
timeoutMs = 30_000,
|
||
): Promise<Buffer> {
|
||
const entry = target.id
|
||
? { id: target.id, name: target.name, size: target.size ?? 0 }
|
||
: await this.findFileEntry(target.name)
|
||
if (!entry) throw new Error(`Файл ${routerFileBasename(target.name)} не найден на RouterOS`)
|
||
assertRosFileReadable(entry)
|
||
return this.readFileContents({ id: entry.id, name: entry.name }, timeoutMs)
|
||
}
|
||
|
||
/** Private export reader: exact-ID contents requests; only an explicit
|
||
* unsupported value-name parameter permits the older .proplist spelling.
|
||
* Metadata and grants are checked around every request; never retarget by name. */
|
||
async downloadOwnedFile(target: { id: string; name: string; size: number }, control: { authorize: () => Promise<unknown>; signal?: AbortSignal; timeoutMs?: number }): Promise<Buffer> {
|
||
if (!/^\*[a-z0-9]+$/i.test(target.id) || !target.name || /[\x00-\x1f\x7f]/.test(target.name) || !Number.isSafeInteger(target.size) || target.size <= 0 || target.size > MAX_OWNED_FILE_BYTES) throw new Error("Private export must have an exact ID/name and size between 1 and 61438 bytes")
|
||
const duration = control.timeoutMs ?? 30000
|
||
if (!Number.isSafeInteger(duration) || duration <= 0 || duration > 45000) throw new Error("Invalid private export deadline")
|
||
const deadline = Date.now() + duration, timerSignal = AbortSignal.timeout(duration)
|
||
const signal = control.signal ? AbortSignal.any([control.signal, timerSignal]) : timerSignal
|
||
const authorize = async () => {
|
||
signal.throwIfAborted()
|
||
let abort!: () => void
|
||
const cancelled = new Promise<never>((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }) })
|
||
try { await Promise.race([control.authorize(), cancelled]); signal.throwIfAborted() }
|
||
finally { signal.removeEventListener("abort", abort) }
|
||
}
|
||
const remaining = () => { signal.throwIfAborted(); const ms = deadline - Date.now(); if (ms <= 0) throw new Error("Private export deadline expired"); return ms }
|
||
const metadata = async () => {
|
||
await authorize()
|
||
const rows = await this.get<unknown>("/file", remaining(), signal, 1048576)
|
||
await authorize()
|
||
if (!Array.isArray(rows) || rows.length > 2000) throw new Error("Private export metadata unavailable")
|
||
const matches = rows.filter(row => row && typeof row === "object" && (row[".id"]?.toLowerCase() === target.id.toLowerCase() || row.name === target.name))
|
||
if (matches.length !== 1 || matches[0][".id"] !== target.id || matches[0].name !== target.name || Number(matches[0].size) !== target.size) throw new Error("Private export ID/name/size changed")
|
||
return JSON.stringify(matches[0])
|
||
}
|
||
const before = await metadata()
|
||
const read = async (body: Record<string, string>) => {
|
||
await authorize()
|
||
const raw = await rosRawRequest(this.params, { method: "POST", path: "/file/get", body, timeoutMs: remaining(), signal, maxResponseBytes: target.size * 6 + 4096 })
|
||
try { await authorize(); return raw }
|
||
catch (error) { raw.fill(0); throw error }
|
||
}
|
||
let raw: Buffer
|
||
try { raw = await read({ ".id": target.id, "value-name": "contents" }) }
|
||
catch (error) {
|
||
// A known parameter rejection confirms that the contents read did not run.
|
||
// Authentication, timeout, broken response, missing item and unknown errors stop.
|
||
let unsupported = false
|
||
if (error instanceof MikrotikError && [400, 404].includes(error.statusCode)) {
|
||
try { const detail = JSON.parse(error.body)?.detail; unsupported = typeof detail === "string" && /^(?:unknown|unsupported) (?:parameter|argument)[: ]+["']?value-name["']?[.!]?$/i.test(detail.trim()) } catch { /* Unknown response is never a compatibility signal. */ }
|
||
}
|
||
if (!unsupported) throw error
|
||
if (await metadata() !== before) throw new Error("Private export metadata changed before compatibility read")
|
||
raw = await read({ ".id": target.id, ".proplist": "contents" })
|
||
}
|
||
let content: Buffer | undefined, transferred = false
|
||
try {
|
||
try { content = extractRosContentsField(raw) }
|
||
catch { throw new Error("Private export contents response is invalid") }
|
||
if (content.length !== target.size) throw new Error("Private export decoded size mismatch")
|
||
if (await metadata() !== before) throw new Error("Private export metadata changed during download")
|
||
await authorize()
|
||
transferred = true
|
||
return content
|
||
} finally {
|
||
raw.fill(0)
|
||
if (!transferred) content?.fill(0)
|
||
}
|
||
}
|
||
|
||
/** Native text exports larger than /file/get's limit use bounded byte offsets. */
|
||
private async downloadConfigurationFile(target: { id: string; name: string; size: number }): Promise<Buffer> {
|
||
if (!Number.isSafeInteger(target.size) || target.size > MAX_ROS_BODY_BYTES) {
|
||
throw new Error("Экспорт конфигурации больше 8 МиБ или размер не подтверждён")
|
||
}
|
||
const deadline = Date.now() + 120_000
|
||
const remaining = () => {
|
||
const ms = deadline - Date.now()
|
||
if (ms <= 0) throw new Error("Истекло время чтения экспорта RouterOS")
|
||
return Math.min(ms, 30_000)
|
||
}
|
||
const metadata = async () => {
|
||
const rows = await this.get<Array<Record<string, unknown>>>("/file", remaining())
|
||
if (!Array.isArray(rows)) throw new Error("Не подтверждён список файлов экспорта")
|
||
const matches = rows.filter(row => row?.[".id"] === target.id || row?.name === target.name)
|
||
const row = matches[0]
|
||
if (matches.length !== 1 || row[".id"] !== target.id || row.name !== target.name || Number(row.size) !== target.size) {
|
||
throw new Error("Файл экспорта изменился во время чтения")
|
||
}
|
||
return JSON.stringify([row["last-modified"] ?? null, row["creation-time"] ?? null])
|
||
}
|
||
const before = await metadata(), chunks: Buffer[] = []
|
||
for (let offset = 0; offset < target.size;) {
|
||
const length = Math.min(32768, target.size - offset)
|
||
const raw = await rosRawRequest(this.params, {
|
||
method: "POST", path: "/file/read",
|
||
body: { file: target.name, offset: String(offset), "chunk-size": String(length) },
|
||
timeoutMs: remaining(),
|
||
})
|
||
const chunk = extractRosContentsField(raw, "data")
|
||
if (chunk.length !== length) throw new Error("RouterOS вернул неполную порцию экспорта")
|
||
chunks.push(chunk); offset += chunk.length
|
||
}
|
||
if (await metadata() !== before) throw new Error("Файл экспорта изменился во время чтения")
|
||
return Buffer.concat(chunks, target.size)
|
||
}
|
||
|
||
/** Удаление файла RouterOS по `.id` или имени (для временных артефактов экспорта). */
|
||
async removeFile(idOrName: string, timeoutMs = 10_000): Promise<void> {
|
||
const id = idOrName.startsWith("*")
|
||
? idOrName
|
||
: (await this.findFileEntry(idOrName))?.id
|
||
if (!id) return
|
||
await this.delete(`/file/${encodeURIComponent(id)}`, timeoutMs)
|
||
}
|
||
|
||
/**
|
||
* POST с деградацией по несовместимым параметрам: набор полей `/certificate/*` зависит от версии
|
||
* RouterOS (напр. `comment`, `days-valid`). При 400 «unknown parameter X» убираем X и повторяем.
|
||
*/
|
||
private async postTolerant(
|
||
path: string,
|
||
body: Record<string, string>,
|
||
timeoutMs: number,
|
||
maxAttempts = 4,
|
||
): Promise<unknown> {
|
||
const payload: Record<string, string> = { ...body }
|
||
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
||
try {
|
||
return await this.post(path, payload, timeoutMs)
|
||
} catch (error) {
|
||
const param = error instanceof MikrotikError ? unknownParameterName(error) : undefined
|
||
if (!param || !(param in payload)) throw error
|
||
delete payload[param]
|
||
}
|
||
}
|
||
throw new Error(`RouterOS: не удалось выполнить ${path} (несовместимые параметры): ${Object.keys(body).join(", ")}`)
|
||
}
|
||
|
||
/** Создание ключевой пары + заявки: /certificate add (поля common-name, key-size, key-usage…). */
|
||
async addCertificate(body: Record<string, string>, timeoutMs = 30_000): Promise<unknown> {
|
||
return this.postTolerant("/certificate/add", body, timeoutMs)
|
||
}
|
||
|
||
/** Подпись сертификата локальным CA; sign небыстрый — увеличенный таймаут. */
|
||
async signCertificate(params: {
|
||
name: string
|
||
ca?: string
|
||
daysValid?: number
|
||
}, timeoutMs = 120_000): Promise<unknown> {
|
||
const body: Record<string, string> = { name: params.name }
|
||
if (params.ca) body.ca = params.ca
|
||
if (params.daysValid != null) body["days-valid"] = String(params.daysValid)
|
||
try {
|
||
return await this.postTolerant("/certificate/sign", body, timeoutMs)
|
||
} catch (e) {
|
||
// Некоторые версии REST принимают цель подписи только как .id.
|
||
const certs = await this.getCertificates()
|
||
const row = certs.find((c) => String(c.name ?? "") === params.name)
|
||
const id = row?.[".id"]
|
||
if (!id) throw e
|
||
return await this.postTolerant("/certificate/sign", { ".id": id, ...body }, timeoutMs)
|
||
}
|
||
}
|
||
|
||
/** Экспорт сертификата в файл на роутере (pkcs12/pem); возвращает созданный файл. */
|
||
async exportCertificate(params: {
|
||
name: string
|
||
type: "pkcs12" | "pem"
|
||
passphrase?: string
|
||
}, timeoutMs = 60_000): Promise<{ fileName: string; fileId: string; size: number }> {
|
||
const body: Record<string, string> = { name: params.name, type: params.type }
|
||
if (params.passphrase?.trim()) body["export-passphrase"] = params.passphrase.trim()
|
||
let raw: unknown
|
||
try {
|
||
raw = await this.postTolerant("/certificate/export-certificate", body, timeoutMs)
|
||
} catch (e) {
|
||
const certs = await this.getCertificates()
|
||
const id = certs.find((c) => String(c.name ?? "") === params.name)?.[".id"]
|
||
if (!id) throw e
|
||
raw = await this.postTolerant("/certificate/export-certificate", { ".id": id, ...body }, timeoutMs)
|
||
}
|
||
void raw
|
||
// RouterOS создаёт cert_export_<name>.p12 либо <name>.p12 — ищем по списку файлов.
|
||
const ext = params.type === "pkcs12" ? "p12" : "crt"
|
||
const wanted = [`${params.name}.${ext}`, `cert_export_${params.name}.${ext}`]
|
||
const files = await this.listFiles()
|
||
const hit = files.find((f) => wanted.includes(f.name))
|
||
?? files.find((f) => f.name.endsWith(`.${ext}`) && f.name.includes(params.name))
|
||
if (!hit) throw new Error(`Файл экспорта ${params.name}.${ext} не найден на RouterOS`)
|
||
return { fileName: hit.name, fileId: hit.id, size: hit.size }
|
||
}
|
||
|
||
/** Скачивание .p12 (сертификат + ключ + цепочка) как бинарный Buffer. */
|
||
async exportCertificatePkcs12(params: { name: string; passphrase?: string }): Promise<{ fileName: string; content: Buffer; passphrase: string }> {
|
||
let passphrase = params.passphrase?.trim() || generateExportPassphrase()
|
||
let exported: { fileName: string; fileId: string; size: number }
|
||
try {
|
||
exported = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase })
|
||
} catch (error) {
|
||
if (!isPassphraseTooShortError(error)) throw error
|
||
// RouterOS мог отклонить пароль пользователя — повторяем со сгенерированным и отдаём его в бандл.
|
||
const forced = generateExportPassphrase()
|
||
try {
|
||
exported = await this.exportCertificate({ name: params.name, type: "pkcs12", passphrase: forced })
|
||
passphrase = forced
|
||
} catch (retryError) {
|
||
if (isPassphraseTooShortError(retryError)) throw new Error(EXPORT_PASSPHRASE_HINT)
|
||
throw retryError
|
||
}
|
||
}
|
||
const content = await this.downloadFile({
|
||
name: exported.fileName,
|
||
id: exported.fileId,
|
||
size: exported.size,
|
||
})
|
||
// Временный файл экспорта на роутере больше не нужен (best-effort, не влияет на результат).
|
||
await this.removeFile(exported.fileId).catch(() => undefined)
|
||
return { fileName: exported.fileName, content, passphrase }
|
||
}
|
||
|
||
async removeCertificate(nameOrId: string, timeoutMs = 30_000): Promise<void> {
|
||
const certs = await this.getCertificates()
|
||
const row = certs.find((c) => String(c.name ?? "") === nameOrId || c[".id"] === nameOrId)
|
||
const id = row?.[".id"]
|
||
if (!id) return
|
||
await this.delete(`/certificate/${encodeURIComponent(id)}`, timeoutMs)
|
||
}
|
||
|
||
private async patchIpService(serviceName: string, body: Record<string, string>): Promise<void> {
|
||
const pathByName = `/ip/service/${encodeURIComponent(serviceName)}`
|
||
try {
|
||
await this.patch(pathByName, body, 30_000)
|
||
return
|
||
} catch {
|
||
const services = await this.get<Array<Record<string, string | undefined>>>("/ip/service")
|
||
const row = services.find((service) => String(service.name ?? "") === serviceName)
|
||
const id = row?.[".id"]
|
||
if (!id) throw new Error(`Сервис RouterOS ${serviceName} не найден`)
|
||
await this.patch(`/ip/service/${encodeURIComponent(id)}`, body, 30_000)
|
||
}
|
||
}
|
||
|
||
async exportConfigScript(): Promise<string> {
|
||
return exportRouterConfiguration({
|
||
list: () => this.get<unknown>("/file"),
|
||
export: name => this.post("/export", { file: name }, 120_000),
|
||
download: file => this.downloadConfigurationFile(file),
|
||
remove: id => this.removeFile(id),
|
||
})
|
||
}
|
||
|
||
}
|
||
|
||
// ── Error type ─────────────────────────────────────────────────────────────────
|
||
|
||
/** HTTP 401 alone does not distinguish wrong credentials from a refused login. */
|
||
export function routerOsAccessHint(statusCode: number, body: string): string | undefined {
|
||
if (statusCode === 401) return "RouterOS отклонил авторизацию: проверьте учётные данные, права API/REST и ограничения входа"
|
||
if (statusCode === 403) return "RouterOS запретил доступ к REST API"
|
||
if (statusCode === 500) {
|
||
try {
|
||
const detail: unknown = JSON.parse(body)?.detail
|
||
if (typeof detail === "string" && /^too many concurrent logins(?:\s*\(\d+\))?$/i.test(detail.trim())) {
|
||
return "RouterOS занят: превышен лимит одновременных входов"
|
||
}
|
||
} catch { /* Keep an unrecognized response unchanged. */ }
|
||
}
|
||
return undefined
|
||
}
|
||
|
||
export class MikrotikError extends Error {
|
||
constructor(
|
||
public readonly statusCode: number,
|
||
public readonly path: string,
|
||
public readonly body: string,
|
||
) {
|
||
const hint = routerOsAccessHint(statusCode, body)
|
||
super(`${hint ? `${hint}. ` : ""}RouterOS API error ${statusCode} on ${path}: ${body}`)
|
||
this.name = "MikrotikError"
|
||
}
|
||
}
|