46 lines
2.5 KiB
TypeScript
46 lines
2.5 KiB
TypeScript
import { request } from "node:http"
|
|
import { trafficFlowHostStatusSchema, type TrafficFlowHostStatus } from "@mmapp/contracts/traffic-flow"
|
|
|
|
export type FlowAgentSnapshot = {
|
|
collectorIp: string; prefix: string; flowListenPort: number; wgListenPort: number
|
|
hostPublicKey: string; hostPrivateKey: string
|
|
peers: { serverId: number; publicKey: string; allowedIps: string[]; endpoint?: string }[]
|
|
}
|
|
|
|
export const agentSocket = () => process.env.FLOW_AGENT_SOCKET?.trim() || ""
|
|
export const emptyHostStatus = (configured: boolean, error: string | null = null): TrafficFlowHostStatus => ({
|
|
configured, reachable: false, interfaceUp: false, configMatches: null,
|
|
publicKey: "", listenPort: 0, addresses: [], peers: [], error,
|
|
})
|
|
|
|
export function callFlowAgent(path: "/status" | "/check" | "/apply", snapshot?: FlowAgentSnapshot, socketPath = agentSocket()): Promise<TrafficFlowHostStatus> {
|
|
if (!socketPath) return Promise.reject(new Error("Автоматизация хоста NetFlow не настроена"))
|
|
const body = snapshot ? JSON.stringify(snapshot) : undefined
|
|
return new Promise((resolve, reject) => {
|
|
const fail = () => reject(new Error("Агент NetFlow недоступен или вернул некорректный ответ; проверьте контейнер mmapp-netflow-agent"))
|
|
const req = request({ socketPath, path, method: body ? "POST" : "GET", headers: body ? { "content-type": "application/json", "content-length": Buffer.byteLength(body) } : {} }, res => {
|
|
let text = ""
|
|
res.setEncoding("utf8")
|
|
res.on("data", (chunk: string) => { text += chunk; if (text.length > 262144) req.destroy() })
|
|
res.on("error", fail)
|
|
res.on("end", () => {
|
|
try {
|
|
const raw: unknown = JSON.parse(text)
|
|
if (res.statusCode !== 200) {
|
|
// The local controller deliberately emits sanitized errors only.
|
|
const error = raw as { error?: unknown }
|
|
reject(new Error(typeof error.error === "string" ? error.error.slice(0, 500) : "Агент NetFlow отклонил настройки"))
|
|
return
|
|
}
|
|
resolve(trafficFlowHostStatusSchema.parse({ ...(raw as object), configured: true, reachable: true, error: null }))
|
|
} catch { fail() }
|
|
})
|
|
})
|
|
// An absolute deadline also covers a peer that keeps sending small chunks.
|
|
const timer = setTimeout(() => req.destroy(), path === "/apply" ? 90_000 : 30_000)
|
|
req.on("close", () => clearTimeout(timer))
|
|
req.on("error", fail)
|
|
req.end(body)
|
|
})
|
|
}
|