154 lines
9.1 KiB
TypeScript
154 lines
9.1 KiB
TypeScript
import { buildOspfOptimizationPlan, type OspfPreviewReadOptions } from "../../routes/ospf.js"
|
|
import { prepareLegacyOspfOptimization, type LegacyOspfPreparation } from "../../services/ospf-legacy-optimization.js"
|
|
import { validateOspfOptimizationPlan } from "../../services/ospf-optimizer-plan.js"
|
|
import { McpError, fingerprint, privateFingerprinter } from "./security.js"
|
|
import { getServerRowById } from "../servers/repository/servers-repository.js"
|
|
|
|
const templatePath = "/routing/ospf/interface-template"
|
|
const configPaths = new Set([templatePath, "/routing/ospf/area", "/routing/ospf/instance"])
|
|
const unusedPaths = new Set(["/routing/bfd/session", "/ip/route", "/ipv6/route"])
|
|
const neighborFields = [".id", "router-id", "interface", "state"]
|
|
const fail = () => new McpError("STATE_CONFLICT", "Источники legacy OSPF не подтверждены; подготовьте новый план", 409)
|
|
export interface LegacyOspfPrefix { baseline: LegacyOspfPreparation; completedCount: number; targets?:Record<string,number> }
|
|
|
|
/** Only keyed digests leave this collector. Native rows and SQL credentials stay in memory. */
|
|
export class LegacyOspfSourceCapture {
|
|
private entries = new Map<string, string>()
|
|
private inspected = new Set<string>()
|
|
private bytes = 0
|
|
private reads = 0
|
|
private closed = false
|
|
private baseline?: LegacyOspfPreparation
|
|
private costs = new Map<string, { initial: number; expected: number }>()
|
|
|
|
constructor(private readonly digest: (value: string) => string, prefix?: LegacyOspfPrefix) {
|
|
if (!prefix) return
|
|
const interfaces = validateOspfOptimizationPlan(prefix.baseline.interfaces)
|
|
if(prefix.targets&&(Object.keys(prefix.targets).length!==interfaces.length||interfaces.some(row=>!Number.isInteger(prefix.targets![row.id])||prefix.targets![row.id]<1||prefix.targets![row.id]>65535)))throw fail()
|
|
const desired=(row:typeof interfaces[number])=>prefix.targets?.[row.id]??row.optimalCost
|
|
const changed = interfaces.filter(row => row.currentCost !== desired(row))
|
|
if (!Number.isSafeInteger(prefix.completedCount) || prefix.completedCount < 0 || prefix.completedCount > changed.length || interfaces.length > 1000) throw fail()
|
|
this.baseline = { ...prefix.baseline, interfaces }
|
|
const completed = new Set(changed.slice(0, prefix.completedCount).map(row => row.id))
|
|
for (const row of interfaces) this.costs.set(row.id, { initial: row.currentCost, expected: completed.has(row.id) ? desired(row) : row.currentCost })
|
|
}
|
|
|
|
private bounded(value: unknown): string {
|
|
if (this.closed || ++this.reads > 512) throw fail()
|
|
let serialized: string
|
|
try { serialized = JSON.stringify(value) } catch { throw fail() }
|
|
if (typeof serialized !== "string") throw fail()
|
|
const size = Buffer.byteLength(serialized)
|
|
this.bytes += size
|
|
if (size > 1048576 || this.bytes > 8388608 || Array.isArray(value) && value.length > 10000) throw fail()
|
|
return serialized
|
|
}
|
|
|
|
private record(key: string, value: unknown) {
|
|
if (this.closed) throw fail()
|
|
const proof = this.digest(fingerprint(value))
|
|
const previous = this.entries.get(key)
|
|
if (previous !== undefined && previous !== proof) throw fail()
|
|
if (this.entries.size >= 256 && previous === undefined) throw fail()
|
|
this.entries.set(key, proof)
|
|
}
|
|
|
|
native(serverId: number, path: string, body: Record<string, string | string[]> | null, value: unknown) {
|
|
this.bounded(value)
|
|
if (!Number.isSafeInteger(serverId) || serverId <= 0) throw fail()
|
|
if (body) {
|
|
const parent = path.replace(/\/(get|print)$/, "")
|
|
if (!configPaths.has(parent) || path === parent) throw fail()
|
|
this.bounded(body)
|
|
this.record(`native:${serverId}:${path}:${fingerprint(body)}`, value)
|
|
return
|
|
}
|
|
if (!Array.isArray(value) || value.some(row => !row || typeof row !== "object" || Array.isArray(row) || typeof row[".id"] !== "string" || !row[".id"].trim())) throw fail()
|
|
if (new Set(value.map(row => row[".id"])).size !== value.length) throw fail()
|
|
this.inspected.add(`${serverId}:${path}`)
|
|
// The legacy ranker fetches these catalogs but does not consume their contents.
|
|
// Their successful bounded read is required; their runtime churn is not a configuration proof.
|
|
if (unusedPaths.has(path)) return
|
|
if (path === "/routing/ospf/neighbor") {
|
|
// Preserve native order: equal-state neighbors use the original stable tie order.
|
|
this.record(`native:${serverId}:${path}`, value.map(row => Object.fromEntries(neighborFields.filter(key => key in row).map(key => [key, row[key]]))))
|
|
return
|
|
}
|
|
if (!configPaths.has(path)) throw fail()
|
|
const rows = value.map(row => ({ ...row }))
|
|
if (path === templatePath && serverId === this.baseline?.serverId) {
|
|
for (const [id, cost] of this.costs) {
|
|
const row = rows.find(row => row[".id"] === id)
|
|
if (!row || ![cost.expected, String(cost.expected)].includes(row.cost)) throw fail()
|
|
row.cost = String(cost.initial)
|
|
}
|
|
}
|
|
this.record(`native:${serverId}:${path}`, rows.sort((a, b) => a[".id"].localeCompare(b[".id"])))
|
|
}
|
|
|
|
source(name: string, value: unknown) {
|
|
this.bounded(value)
|
|
if (!/^(enabled-servers|(?:latency|traffic|speed-probes):[1-9]\d*)$/.test(name)) throw fail()
|
|
if (!Array.isArray(value) || value.length > (name.startsWith("latency:") ? 1 : name === "enabled-servers" ? 1000 : 2000)) throw fail()
|
|
// Preserve SQL order because probe ties can depend on that order.
|
|
this.record(`sql:${name}`, value)
|
|
}
|
|
|
|
finish(plan: LegacyOspfPreparation) {
|
|
if (this.closed) throw fail()
|
|
const ranked = validateOspfOptimizationPlan(plan.interfaces)
|
|
if (ranked.length > 1000) throw fail()
|
|
if ([...configPaths, ...unusedPaths, "/routing/ospf/neighbor"].some(path => !this.inspected.has(`${plan.serverId}:${path}`))) throw fail()
|
|
if (ranked.length && ["enabled-servers", `latency:${plan.serverId}`, `traffic:${plan.serverId}`, `speed-probes:${plan.serverId}`].some(name => !this.entries.has(`sql:${name}`))) throw fail()
|
|
const normalized = ranked.map(row => {
|
|
if (!this.baseline) return row
|
|
const cost = this.costs.get(row.id)
|
|
if (!cost || row.currentCost !== cost.expected) throw fail()
|
|
return { ...row, currentCost: cost.initial }
|
|
})
|
|
if (this.baseline && normalized.length !== this.costs.size) throw fail()
|
|
this.bounded(normalized)
|
|
this.record("ranked", { ...plan, interfaces: normalized })
|
|
const entries = [...this.entries].sort(([a], [b]) => a.localeCompare(b))
|
|
const nativeProof=this.digest(fingerprint(entries.filter(([key])=>key.startsWith("native:"))))
|
|
this.closed = true
|
|
this.entries.clear()
|
|
this.inspected.clear()
|
|
return { proof: this.digest(fingerprint(entries)), nativeProof, sourceCount: entries.length, observedReads: this.reads }
|
|
}
|
|
}
|
|
|
|
/** Uses the actual REST ranker; authorization surrounds every SQL and native source read. */
|
|
export async function readLegacyOspfSealedSources(
|
|
server: Parameters<typeof buildOspfOptimizationPlan>[0], pingWeight: number,
|
|
options: OspfPreviewReadOptions & { serverIds: readonly number[]; authorize: () => Promise<unknown> }, prefix?: LegacyOspfPrefix,
|
|
) {
|
|
if (options.serverIds.length > 10 || options.serverIds.some(id => !Number.isSafeInteger(id) || id <= 0) || !options.serverIds.includes(server.id) || new Set(options.serverIds).size !== options.serverIds.length) throw fail()
|
|
const deadlineAt = Math.min(options.deadlineAt ?? Infinity, Date.now() + 45000)
|
|
if (!Number.isFinite(deadlineAt) || deadlineAt <= Date.now()) throw fail()
|
|
const signal = AbortSignal.any([AbortSignal.timeout(Math.max(1, Math.ceil(deadlineAt-Date.now()))), ...(options.signal ? [options.signal] : [])])
|
|
const authorize = async () => { signal.throwIfAborted(); await options.authorize(); signal.throwIfAborted() }
|
|
await authorize()
|
|
const capture = new LegacyOspfSourceCapture(await privateFingerprinter("ospf-legacy-application-sources-v1"), prefix)
|
|
const sources = new Map<number, typeof server>()
|
|
const verifySource = async (source: typeof server) => {
|
|
await authorize()
|
|
if (!options.serverIds.includes(source.id)) throw fail()
|
|
const fresh = await getServerRowById(source.id)
|
|
if (!fresh?.enabled || fingerprint(fresh) !== fingerprint(source)) throw fail()
|
|
sources.set(source.id, source)
|
|
await authorize()
|
|
}
|
|
const plan = await prepareLegacyOspfOptimization(server, pingWeight, () => buildOspfOptimizationPlan(server, pingWeight, {
|
|
...options,
|
|
deadlineAt, signal,
|
|
beforeSourceRead: async () => { await authorize(); await options.beforeSourceRead?.() },
|
|
onSourceRead: async (name, value) => { await authorize(); capture.source(name, value); await options.onSourceRead?.(name, value); await authorize() },
|
|
beforeRequest: async source => { await verifySource(source); await options.beforeRequest?.(source); await authorize() },
|
|
onNativeRead: async (source, path, body, value) => { await authorize(); capture.native(source.id, path, body, value); await options.onNativeRead?.(source, path, body, value); await authorize() },
|
|
}), authorize)
|
|
for (const source of sources.values()) await verifySource(source)
|
|
await authorize()
|
|
return { plan, ...capture.finish(plan) }
|
|
}
|