80 lines
7.2 KiB
TypeScript
80 lines
7.2 KiB
TypeScript
import { serverProbeExecutionRequest, type ServerProbeRequest } from "./server-probe-execution-model.js"
|
||
import type { ServerProbeReceipt } from "./server-probe-execution.js"
|
||
|
||
/** REST compatibility boundary only. MCP continues using the strict schema.
|
||
* Inert: imports do not open the database, DNS, RouterOS or a journal. */
|
||
export class ServerProbeRestContractError extends Error {
|
||
constructor(readonly statusCode: number, readonly code: string, message: string) { super(message) }
|
||
}
|
||
const knownKeys = new Set(Object.keys(serverProbeExecutionRequest.shape))
|
||
export function normalizeServerProbeRestRequest(raw: unknown): ServerProbeRequest {
|
||
const candidate = raw && typeof raw === "object" && !Array.isArray(raw)
|
||
? Object.fromEntries(Object.entries(raw).filter(([key]) => knownKeys.has(key))) : raw
|
||
const parsed = serverProbeExecutionRequest.safeParse(candidate)
|
||
if (!parsed.success) throw new ServerProbeRestContractError(400, "INVALID_INPUT", "Некорректные параметры диагностики: " + [...new Set(parsed.error.issues.map(issue => issue.path.join(".") || "body"))].join(", "))
|
||
return parsed.data
|
||
}
|
||
export function parseServerProbeRestServerId(raw: string): number {
|
||
const value = /^[1-9][0-9]*$/.test(raw) ? Number(raw) : NaN
|
||
if (!Number.isSafeInteger(value)) throw new ServerProbeRestContractError(400, "INVALID_INPUT", "Invalid server id")
|
||
return value
|
||
}
|
||
export interface ServerProbeRestPeerMetadata { id: number; host: string; enabled: boolean }
|
||
export interface ServerProbeRestPeerReader {
|
||
/** SQL must restrict to allowed IDs BEFORE reading metadata. Never return
|
||
* credentials. An existing disabled explicit peer must still be returned. */
|
||
byId(id: number, allowedServerIds: readonly number[]): Promise<ServerProbeRestPeerMetadata | undefined>
|
||
/** Return enabled matches in the same repository order as legacy .find().
|
||
* SQL must restrict scope BEFORE lookup; do not fetch all server secrets. */
|
||
enabledByHost(host: string, allowedServerIds: readonly number[]): Promise<readonly ServerProbeRestPeerMetadata[]>
|
||
}
|
||
/** Exact legacy selection: existing explicit ID wins (even disabled); a
|
||
* missing ID falls back to first enabled case-insensitive trimmed host match.
|
||
* Scope is supplied by trusted authority, never by request JSON. */
|
||
export async function resolveServerProbeRestBandwidthPeer(remoteHost: string, explicitId: number | undefined, allowedServerIds: readonly number[], reader: ServerProbeRestPeerReader): Promise<ServerProbeRestPeerMetadata> {
|
||
if (!allowedServerIds.every(id => Number.isSafeInteger(id) && id > 0) || explicitId !== undefined && (!Number.isSafeInteger(explicitId) || explicitId <= 0)) throw new ServerProbeRestContractError(400, "INVALID_INPUT", "Некорректные параметры диагностики: dstServerId")
|
||
const safe = (row: ServerProbeRestPeerMetadata) => {
|
||
if (!Number.isSafeInteger(row.id) || !allowedServerIds.includes(row.id) || typeof row.host !== "string" || typeof row.enabled !== "boolean") throw new ServerProbeRestContractError(403, "PERMISSION_DENIED", "Нет актуального допуска диагностики обоих серверов")
|
||
return { id: row.id, host: row.host, enabled: row.enabled }
|
||
}
|
||
let selected: ServerProbeRestPeerMetadata | undefined
|
||
if (explicitId !== undefined) {
|
||
const row = await reader.byId(explicitId, allowedServerIds)
|
||
if (row) { selected = safe(row); if (selected.id !== explicitId) throw new ServerProbeRestContractError(409, "STATE_CONFLICT", "Назначение BW-теста изменилось") }
|
||
}
|
||
if (!selected) {
|
||
const normalized = remoteHost.trim().toLowerCase(), rows = await reader.enabledByHost(normalized, allowedServerIds)
|
||
for (const row of rows) { const checked = safe(row); if (!checked.enabled || checked.host.trim().toLowerCase() !== normalized) throw new ServerProbeRestContractError(409, "STATE_CONFLICT", "Назначение BW-теста изменилось"); if (!selected) selected = checked }
|
||
}
|
||
if (!selected) throw new ServerProbeRestContractError(400, "DESTINATION_UNAVAILABLE", "Не найден сервер назначения для bandwidth-test: добавьте узел с host = GRE remote или укажите dstServerId")
|
||
if (!selected.enabled) throw new ServerProbeRestContractError(409, "DESTINATION_DISABLED", "Устройство назначения выключено. BW-тест недоступен.")
|
||
return selected
|
||
}
|
||
export type ServerProbeRestReply = { statusCode: number; body: { output: string } | { error: string } }
|
||
/** Receipt must already have passed the executor's private binding, durable
|
||
* journal and redaction checks. Never accept raw provider output here. */
|
||
export function serverProbeRestReceiptReply(receipt: ServerProbeReceipt): ServerProbeRestReply {
|
||
if (receipt.state !== "completed" || receipt.httpStatus !== 200 || typeof receipt.output !== "string") return serverProbeRestErrorReply({ code: receipt.errorCode, statusCode: receipt.httpStatus })
|
||
if (/^;;\s*ERROR:/im.test(receipt.output) || /^error:/i.test(receipt.output.trimStart())) return { statusCode: 502, body: { error: receipt.output } }
|
||
return { statusCode: 200, body: { output: receipt.output } }
|
||
}
|
||
/** Safe public messages only; provider error.message must never be forwarded. */
|
||
export function serverProbeRestErrorReply(failure: { code?: string; statusCode?: number }): ServerProbeRestReply {
|
||
if (failure instanceof ServerProbeRestContractError) return { statusCode: failure.statusCode, body: { error: failure.message } }
|
||
const known: Record<string, [number, string]> = {
|
||
NOT_FOUND: [404, "Server not found"],
|
||
SOURCE_UNAVAILABLE: [409, "Устройство выключено. Диагностика недоступна."],
|
||
DESTINATION_DISABLED: [409, "Устройство назначения выключено. BW-тест недоступен."],
|
||
DESTINATION_UNAVAILABLE: [400, "Не найден сервер назначения для bandwidth-test: добавьте узел с host = GRE remote или укажите dstServerId"],
|
||
INVALID_INPUT: [400, "Некорректные параметры диагностики"],
|
||
CANCELLED: [502, "Запрос отменён (клиент закрыл соединение или истёк лимит времени для traceroute)."],
|
||
MEASUREMENT_UNKNOWN: [502, "Устройство не подтвердило структурированные измерения диагностики"],
|
||
PERMISSION_DENIED: [403, "Нет актуального допуска диагностики обоих серверов"],
|
||
STATE_CONFLICT: [409, "Источник или назначение диагностики изменились"],
|
||
JOURNAL_UNKNOWN: [503, "Исход диагностики неизвестен; автоматический повтор запрещён"],
|
||
REPLAY_FORBIDDEN: [409, "Попытка диагностики уже использована; автоматический повтор запрещён"],
|
||
}
|
||
const [statusCode, error] = known[failure.code ?? ""] ?? [502, "Не удалось получить подтверждённый результат диагностики"]
|
||
return { statusCode, body: { error } }
|
||
}
|