Files
MikrotikManager/backend/src/modules/mcp/ospf-owner-graph.ts
T

75 lines
4.9 KiB
TypeScript

import { z } from "zod"
import type { ChangeEvidence } from "./action-types.js"
import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js"
import { configurationRows, resourceById, routerClient } from "./resources.js"
import { readOspfLinkCatalog } from "../../services/ospf-link-catalog.js"
import { fingerprint, McpError } from "./security.js"
const sid = z.number().int().positive().safe(), hash = z.string().regex(/^[a-f0-9]{64}$/)
const schema = z.object({ family: z.enum(["ipv4", "ipv6"]), sourceSecretProofs: z.array(z.object({ serverId: sid, proof: hash }).strict()).min(1).max(1000), instances: z.array(z.object({ serverId: sid, fingerprint: hash }).strict()).min(1).max(1000) }).strict()
type Graph = NonNullable<ChangeEvidence["ospfOwnerGraph"]>
interface GraphDependencies {
sources: (ids: number[], expected: Graph["sourceSecretProofs"]) => Promise<() => Promise<void>>;
instance: (id: number) => Promise<string>;
}
function validateGraph(graph: Graph, permittedIds: readonly number[]) {
const parsed = schema.safeParse(graph)
if (!parsed.success) throw new McpError("STATE_CONFLICT", "Недостоверный граф владельцев OSPF", 409)
const value = parsed.data, ids = value.instances.map(row => row.serverId)
const sourceIds = value.sourceSecretProofs.map(row => row.serverId)
if (new Set(ids).size !== ids.length || new Set(sourceIds).size !== sourceIds.length || ids.some(id => !permittedIds.includes(id)) || fingerprint([...ids].sort((a, b) => a - b)) !== fingerprint([...sourceIds].sort((a, b) => a - b))) throw new McpError("SERVER_DENIED", "Граф OSPF не совпадает с полной разрешённой областью источников", 409)
return { value, ids }
}
/** Operation-local source guard: memoize the bound context, never the result of
* its live DB/HMAC/epoch check. This performs no native graph polling. */
export function createOspfOwnerSourceGuard(graph: Graph | undefined, permittedIds: readonly number[], dependencies?: Pick<GraphDependencies, "sources">): () => Promise<void> {
if (!graph) return async () => {}
const { value, ids } = validateGraph(graph, permittedIds)
let context: Promise<() => Promise<void>> | undefined
return async () => {
context ??= dependencies ? dependencies.sources(ids, value.sourceSecretProofs) : currentSources(ids, value)
await (await context)()
}
}
export async function verifyOspfOwnerGraph(graph: Graph | undefined, permittedIds: readonly number[], authorize: () => Promise<unknown>, dependencies?: GraphDependencies) {
if (!graph) return
const { value, ids } = validateGraph(graph, permittedIds)
await authorize()
const assertSources = dependencies ? await dependencies.sources(ids, value.sourceSecretProofs) : await currentSources(ids, value)
await assertSources()
let rows = 0, bytes = 0
for (const expected of value.instances) {
await authorize()
await assertSources()
let actual: string
if (dependencies) actual = await dependencies.instance(expected.serverId)
else {
const { client } = await routerClient(expected.serverId)
const link = await readOspfLinkCatalog(client, value.family, async () => { await authorize(); await assertSources() })
rows += link.rows; bytes += link.bytes
if (rows > 10000 || bytes > 1048576) throw new McpError("STATE_UNAVAILABLE", "Граф владельцев OSPF превышает допустимый объём", 409)
actual = fingerprint({ native: fingerprint(configurationRows(resourceById("ospf_instance"), link.identity.raw)), identity: link.fingerprint })
}
if (actual !== expected.fingerprint) throw new McpError("STATE_CONFLICT", "После подготовки изменился граф владельцев Router ID OSPF", 409)
}
await assertSources()
await authorize()
}
export async function verifyOspfOwnerGraphAtPhase(graph: Graph | undefined, permittedIds: readonly number[], authorize: () => Promise<unknown>, phase: "admission" | "post-ack", dependencies?: GraphDependencies) {
try { await verifyOspfOwnerGraph(graph, permittedIds, authorize, dependencies) }
catch (error) {
if (phase === "post-ack" && error instanceof McpError && error.code === "STATE_CONFLICT") throw new McpError("VERIFICATION_FAILED", "После записи изменился подтверждённый контекст соседства OSPF; требуется сверка без повторной записи", 409)
throw error
}
}
async function currentSources(ids: number[], expected: Graph) {
const context = await createRoutingSourceContext(await readRoutingEndpoints(ids))
if (fingerprint(context.expected) !== fingerprint([...expected.sourceSecretProofs].sort((a, b) => a.serverId - b.serverId))) throw new McpError("STATE_CONFLICT", "Источник графа OSPF изменился после подготовки", 409)
return () => context.assertCurrent()
}