Files
MikrotikManager/backend/src/modules/mcp/routing-community-context-native.ts
T

68 lines
5.7 KiB
TypeScript

import http from "node:http"
import https from "node:https"
import type { RoutingEndpoint } from "./routing-observation-source.js"
import { McpError } from "./security.js"
import { isIP } from "node:net"
import { captureRoutingNetworkDestinationPins, type RoutingNetworkNativeDestinationPin } from "./routing-network-native-destination.js"
/** Trusted internal execution limits, never an HTTP tool input. */
export type RouteContextNativeSessionLimits = Readonly<{ deadline: number; maxCalls: number; maxBytes: number; pins?: readonly RoutingNetworkNativeDestinationPin[] }>
/** One acquisition/probe batch: actual UTF-8 bytes before JSON.parse, one
* deadline, no redirects/retries, and a fixed authenticated destination. */
export function routeContextClients(endpoints: readonly RoutingEndpoint[], signal?: AbortSignal, sessionLimits?: RouteContextNativeSessionLimits) {
const now = Date.now()
if (sessionLimits && (!Number.isFinite(sessionLimits.deadline) || sessionLimits.deadline <= now || sessionLimits.deadline > now + 120000 ||
!Number.isSafeInteger(sessionLimits.maxCalls) || sessionLimits.maxCalls < 1 || sessionLimits.maxCalls > 256 ||
!Number.isSafeInteger(sessionLimits.maxBytes) || sessionLimits.maxBytes < 1 || sessionLimits.maxBytes > 8 * 1048576)) throw new McpError("LIMIT_EXCEEDED", "Некорректный внутренний бюджет native session", 409)
const deadline = sessionLimits?.deadline ?? now + 60000, maxCalls = sessionLimits?.maxCalls ?? 2000, maxBytes = sessionLimits?.maxBytes ?? 8 * 1048576
const capturedEndpoints = sessionLimits?.pins === undefined ? endpoints : endpoints.map(endpoint => Object.freeze({ ...endpoint }))
const pins = sessionLimits?.pins === undefined ? undefined : captureRoutingNetworkDestinationPins(capturedEndpoints, sessionLimits.pins)
let bytes = 0, calls = 0
const read = <T>(endpoint: RoutingEndpoint, path: string, body?: Record<string, string | string[]>, timeoutMs = 10000): Promise<T> => new Promise((resolve, reject) => {
if (signal?.aborted || Date.now() >= deadline || bytes >= maxBytes || calls >= maxCalls) { reject(new McpError("READ_CANCELLED", "Лимит времени/запросов контекста пути", 409)); return }
calls++
const transport = endpoint.useSsl ? https : http
const pin = pins?.get(endpoint.id), host = isIP(endpoint.host) === 6 ? "[" + endpoint.host + "]" : endpoint.host
const req = transport.request({ hostname: pin?.address ?? endpoint.host, port: endpoint.port, path: "/rest" + path, method: body ? "POST" : "GET", signal,
...(pin ? { family: pin.family, servername: isIP(endpoint.host) ? undefined : endpoint.host } : {}),
rejectUnauthorized: endpoint.useSsl ? endpoint.verifySsl : undefined,
headers: { Authorization: "Basic " + Buffer.from(endpoint.username + ":" + endpoint.password).toString("base64"), "Content-Type": "application/json",
...(pin ? { Host: host + (endpoint.port === (endpoint.useSsl ? 443 : 80) ? "" : ":" + endpoint.port) } : {}) },
}, res => {
const chunks: Buffer[] = []; let received = 0
res.on("error", reject)
res.once("aborted", () => reject(new McpError("STATE_UNAVAILABLE", "Ответ контекста пути прерван", 409)))
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
const code = [401, 403, 407].includes(res.statusCode ?? 0) ? "SOURCE_AUTH_FAILED"
: [404, 408, 429, 500, 502, 503, 504].includes(res.statusCode ?? 0) ? "STATE_UNAVAILABLE" : "INVALID_NATIVE_RESPONSE"
reject(new McpError(code, "Источник контекста пути вернул неподдерживаемый ответ", 409)); res.destroy(); req.destroy(); return
}
if (Number(res.headers["content-length"] ?? 0) > 1048576) { reject(new McpError("LIMIT_EXCEEDED", "Бюджет байтов контекста пути превышен", 409)); res.destroy(); req.destroy(); return }
res.on("data", (chunk: Buffer) => {
received += chunk.length; bytes += chunk.length
if (received > 1048576 || bytes > maxBytes) { reject(new McpError("LIMIT_EXCEEDED", "Бюджет байтов контекста пути превышен", 409)); res.destroy(); req.destroy(); return }
chunks.push(chunk)
})
res.on("end", () => {
clearTimeout(timer)
try { resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")) as T) }
catch { reject(new McpError("INVALID_NATIVE_RESPONSE", "Источник контекста пути вернул некорректный JSON", 409)) }
})
})
const remaining = Math.max(1, deadline - Date.now()), batchDeadline = remaining <= timeoutMs
const timer = setTimeout(() => req.destroy(new McpError(batchDeadline ? "READ_CANCELLED" : "STATE_UNAVAILABLE", "Истёк срок чтения контекста пути", 409)), Math.min(timeoutMs, remaining))
req.once("error", error => { clearTimeout(timer); reject(error) })
req.once("close", () => clearTimeout(timer))
req.end(body ? JSON.stringify(body) : undefined)
})
const clients = new Map(capturedEndpoints.map(endpoint => [endpoint.id, {
get: <T>(path: string, timeoutMs = 10000) => read<T>(endpoint, path, undefined, timeoutMs),
post: <T>(path: string, body: Record<string, string | string[]>, timeoutMs = 10000) => {
if (!path.endsWith("/get") && !path.endsWith("/print") && !["/tool/ping", "/tool/traceroute"].includes(path)) throw new McpError("PERMISSION_DENIED", "Контекст пути допускает только чтение и ограниченные probes", 403)
return read<T>(endpoint, path, body, timeoutMs)
},
}]))
return Object.assign(clients, { readBudget: () => Object.freeze({ deadline, calls, bytes, maxCalls, maxBytes }) })
}