Files
MikrotikManager/backend/src/services/ipsec-server-delete.ts
T

73 lines
7.7 KiB
TypeScript

import { ipsecExternalPoolDependencyPaths, ipsecPoolDependencies } from "./ipsec-pool-dependencies.js"
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
import { McpError } from "../modules/mcp/security.js"
import { MikrotikClient } from "./mikrotik.js"
import { readIpsecPeerDeleteState, ipsecPeerDeleteProof, ipsecPeerDeleteRows, type IpsecPeerDeleteState } from "./ipsec-peer-delete.js"
import { sameWireguardEndpoint } from "./wireguard-source.js"
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
import { executeGuardedApplicationWrite } from "./config-mutation-policy.js"
import { captureAndAppendRevision } from "./config-revisions.js"
import { captureIpsecSnapshot } from "./ipsec-live.js"
import { planIpsecServerDelete, projectIpsecServerDelete, type IpsecServerDeleteCommand } from "./ipsec-server-delete-model.js"
// Draft guard only: add external consumers to the existing whole-state proof.
export async function readIpsecServerDeleteState(server:ServerRow,authorize:()=>Promise<unknown>=async()=>{}):Promise<IpsecPeerDeleteState>{
const deadline=Date.now()+45000
const check=async()=>{if(Date.now()>=deadline)throw new McpError("STATE_UNAVAILABLE","Истёк бюджет чтения IPsec",502);await authorize();const fresh=await getServerRowById(server.id);if(!fresh||!sameWireguardEndpoint(fresh,server))throw new McpError("STATE_CONFLICT","Источник IPsec изменился",409)}
const state=await readIpsecPeerDeleteState(server,check),client=MikrotikClient.fromServer(server)
for(const path of ipsecExternalPoolDependencyPaths){
await check();let raw:unknown
try{raw=await client.get<unknown>(path,Math.max(1,Math.min(10000,deadline-Date.now())),undefined,1048576)}catch{throw new McpError("STATE_UNAVAILABLE","Обязательный каталог потребителей IPv4 pool недоступен",502)}
await check()
state.catalogs[path]=ipsecPeerDeleteRows(raw)
if(Buffer.byteLength(JSON.stringify(state))>1048576||Object.values(state.catalogs).reduce((sum,rows)=>sum+rows.length,0)>10000)throw new McpError("STATE_UNAVAILABLE","Превышен полный бюджет зависимостей IPsec",502)
}
ipsecPoolDependencies(state.catalogs)
await check();state.proof=await ipsecPeerDeleteProof(state);return state
}
export async function ipsecServerDeleteStageProofs(state: IpsecPeerDeleteState, commands: IpsecServerDeleteCommand[]) {
if (commands.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Удаление IPsec превышает предел полного плана", 502)
const proofs = [state.proof]
for (const command of commands) { state = projectIpsecServerDelete(state, command); proofs.push(await ipsecPeerDeleteProof(state)) }
return proofs
}
export class IpsecServerDeleteExecutionError extends McpError {
constructor(code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", message: string, readonly confirmedWrites: number, readonly completedCommands: number, readonly commandCount: number) { super(code, message, 502) }
}
/** Full shared REST/MCP operation. The sealed manifest includes every indirect
* certificate removal; no CA command can expand its footprint after approval. */
export async function deleteIpsecServerGuarded(server: ServerRow, removeCertificates = true, expectedProof?: string, authorize: () => Promise<unknown> = async () => {}, options: { recordRevision?: typeof captureAndAppendRevision; receiptId?: string; checkpoint?: (value: { receiptId: string; commandCount: number; completedCommands: number; afterProof: string }) => Promise<unknown> } = {}) {
if (typeof removeCertificates !== "boolean") throw new McpError("INVALID_INPUT", "Некорректный режим удаления сертификатов", 400)
return withApplicationMutationLock(() => withConfigMutationLock([server.id], () => executeGuardedApplicationWrite({ kind: "ipsec_server", id: String(server.id) }, [server.id], async () => {
const source = async () => { await authorize(); const fresh = await getServerRowById(server.id); if (!fresh || !sameWireguardEndpoint(fresh, server)) throw new McpError("STATE_CONFLICT", "Источник IPsec изменился", 409) }
let state = await readIpsecServerDeleteState(server, source)
if (expectedProof !== undefined && state.proof !== expectedProof) throw new McpError("STATE_CONFLICT", "IPsec или зависимости изменились после подготовки", 409)
const plan = planIpsecServerDelete(state, removeCertificates), proofs = await ipsecServerDeleteStageProofs(state, plan.commands), client = MikrotikClient.fromServer(server)
const cascadeIndirectObjectCount = plan.commands.reduce((total, command) => total + (command.cascadeIds?.length ?? 0), 0)
let completedCommands = 0, confirmedWrites = 0
const stopped = (code: "MUTATION_OUTCOME_UNKNOWN" | "VERIFICATION_FAILED", message: string) => new IpsecServerDeleteExecutionError(code, message, confirmedWrites, completedCommands, plan.commands.length)
for (const command of plan.commands) {
let dispatched = false
try {
await client.delete(command.path + "/" + encodeURIComponent(command.id), 10000, async () => {
const fresh = await readIpsecServerDeleteState(server, source)
if (fresh.proof !== state.proof) throw new McpError("STATE_CONFLICT", "IPsec изменился после durable intent; DELETE не отправлен", 409)
await source(); dispatched = true
})
confirmedWrites++
} catch (error) {
if (!dispatched && !completedCommands && error instanceof McpError) throw error
throw stopped(dispatched ? "MUTATION_OUTCOME_UNKNOWN" : "VERIFICATION_FAILED", "Удаление сервера IPsec остановлено; повтор команды запрещён, требуется сверка")
}
try { state = await readIpsecServerDeleteState(server, source) } catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "DELETE отправлен, но read-back недоступен; повтор запрещён") }
if (state.proof !== proofs[completedCommands + 1]) throw stopped("VERIFICATION_FAILED", "Не подтверждено точное удаление manifest и сохранность остальных объектов IPsec; повтор запрещён")
completedCommands++
try { await source(); await options.checkpoint?.({ receiptId: options.receiptId ?? "", commandCount: plan.commands.length, completedCommands, afterProof: state.proof }) } catch { throw stopped("MUTATION_OUTCOME_UNKNOWN", "Удаление проверено, но checkpoint не сохранён; повтор запрещён") }
}
const reader = { get: async (path: string) => { await source(); if (!Object.hasOwn(state.catalogs, path)) throw new McpError("STATE_UNAVAILABLE", "Неизвестный каталог истории IPsec", 502); return structuredClone(state.catalogs[path]) } } as unknown as MikrotikClient
let historyRecorded = false
try { await source(); historyRecorded = (await (options.recordRevision ?? captureAndAppendRevision)({ serverId: server.id, section: "ipsec", source: "apply", capture: () => captureIpsecSnapshot(server, reader) })) !== null } catch { /* Never replay acknowledged DELETEs for history. */ }
return { ok: true, verified: true, receiptId: options.receiptId ?? null, removeCertificates, commandCount: plan.commands.length, completedCommands, confirmedWrites, affectedObjects: plan.objects.length, affectedObjectCount: plan.objects.length, cascadeIndirectObjectCount, afterProof: state.proof, historyRecorded, revisionRecorded: historyRecorded, state: "applied", automaticReplay: false, forwardingVerified: false }
})))
}