117 lines
11 KiB
TypeScript
117 lines
11 KiB
TypeScript
import { z } from "zod"
|
|
import { getServerRowById, type ServerRow } from "../modules/servers/repository/servers-repository.js"
|
|
import { fingerprint, McpError } from "../modules/mcp/security.js"
|
|
import { wireguardInterfaceCreateSchema, wireguardCreatePeerBody, wireguardCreateKey, wireguardCreateProtectionProof, readWireguardInterfaceCreateState } from "./wireguard-interface-create.js"
|
|
import { wireguardInterfaceDeleteProof, type WireguardInterfaceDeleteState } from "./wireguard-interface-delete.js"
|
|
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
|
|
import { wireguardConfigurationRows } from "./wireguard-peer-delete.js"
|
|
import { observedWireguardPeerKeepalive } from "./wireguard-peer-update.js"
|
|
import { observedBoolean } from "./ospf-observed-values.js"
|
|
import { MikrotikClient } from "./mikrotik.js"
|
|
import { withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
|
|
import { executeGuardedApplicationWrite } from "./config-mutation-policy.js"
|
|
import { captureAndAppendRevision } from "./config-revisions.js"
|
|
import { captureWireguardSnapshot } from "./wireguard-live.js"
|
|
import { markWireguardReadBackFailure } from "./wireguard-read-diagnostic.js"
|
|
|
|
export const wireguardPeerCreateSchema = wireguardInterfaceCreateSchema.shape.peer.unwrap().extend({ serverId: z.number().int().positive().safe(), interfaceName: wireguardInterfaceCreateSchema.shape.name }).strict()
|
|
export type WireguardPeerCreate = z.infer<typeof wireguardPeerCreateSchema>
|
|
type State = WireguardInterfaceDeleteState
|
|
type Row = Record<string, string>
|
|
const fail = (code: string, message: string) => new McpError(code, message, code === "INVALID_INPUT" ? 400 : ["STATE_UNAVAILABLE", "MUTATION_OUTCOME_UNKNOWN", "VERIFICATION_FAILED"].includes(code) ? 502 : 409)
|
|
export const wireguardPeerCreateStages = (input: WireguardPeerCreate) => input.disabled ? ["peer"] : ["peer", "peer-enable"]
|
|
export function wireguardPeerCreateBody(input: WireguardPeerCreate) {
|
|
return wireguardCreatePeerBody({ serverId: input.serverId, name: input.interfaceName, listenPort: 13231, mtu: 1420, peer: input })
|
|
}
|
|
export function assertWireguardPeerCreateAllowed(state: State, input: WireguardPeerCreate) {
|
|
const parents = state.base.interfaces.filter(row => row.name === input.interfaceName)
|
|
if (parents.length !== 1) throw fail("STATE_CONFLICT", "Родительский WireGuard не найден однозначно")
|
|
const parent = parents[0]
|
|
for (const flag of ["dynamic", "builtin", "default"]) if (parent[flag] !== undefined && observedBoolean(parent[flag]) !== false) throw fail("PROTECTED_OBJECT", "Системный или неподтверждённый родитель WireGuard")
|
|
if (observedBoolean(parent.disabled) === null) throw fail("STATE_UNAVAILABLE", "Не подтверждено состояние родителя WireGuard")
|
|
const generic = state.dependencies["/interface"].filter(row => row.name === parent.name || row[".id"] === parent[".id"])
|
|
if (generic.length !== 1 || generic[0].name !== parent.name || generic[0][".id"] !== parent[".id"]) throw fail("STATE_CONFLICT", "Расходятся native ID родителя WireGuard")
|
|
if (parent.name === "wg-flow" || parent.comment === "MikrotikManager traffic-flow overlay" || input.name === "mm-collector" || input.comment === "MM traffic-flow collector" || input.publicKey === state.base.flow.hostPublicKey) throw fail("PROTECTED_OBJECT", "WireGuard или peer зарезервирован NetFlow")
|
|
if (state.base.peers.some(row => [parent.name, parent[".id"]].includes(row.interface) && (row["public-key"] === input.publicKey || input.name && row.name === input.name))) throw fail("STATE_CONFLICT", "Peer с таким ключом или именем уже существует")
|
|
// Existing parent references are supported: creating a child neither removes
|
|
// nor renames the parent. Their complete proof must survive every stage.
|
|
return parent
|
|
}
|
|
function matches(row: Row, body: Row) {
|
|
return Object.entries(body).every(([key, value]) => {
|
|
if (key === "disabled") return observedBoolean(row[key]) === observedBoolean(value)
|
|
if (key === "endpoint-port") return /^\d+$/.test(row[key] ?? "") && Number(row[key]) === Number(value)
|
|
if (key === "persistent-keepalive") return observedWireguardPeerKeepalive(row[key] ?? "") === Number(value)
|
|
if (key === "allowed-address") { try { return fingerprint(row[key].split(",").map(canonicalBgpPolicyPrefix).sort()) === fingerprint(value.split(",").map(canonicalBgpPolicyPrefix).sort()) } catch { return false } }
|
|
if (key === "private-key" && value === "auto") return wireguardCreateKey.safeParse(row[key]).success
|
|
if (key === "private-key" && value === "none") return row[key] === "none" || row[key] === ""
|
|
return (row[key] ?? "") === value
|
|
})
|
|
}
|
|
/** Remove only the new native identity; every parent/foreign/opaque field stays sealed. */
|
|
export async function wireguardPeerCreatePrefix(state: State, input: WireguardPeerCreate, baseline: string, count: number, peerId?: string) {
|
|
if (!Number.isInteger(count) || count < 0 || count > wireguardPeerCreateStages(input).length) return false
|
|
if (count === 0) return state.proof === baseline
|
|
const parents = state.base.interfaces.filter(row => row.name === input.interfaceName)
|
|
if (parents.length !== 1) return false
|
|
const selected = state.base.peers.filter(row => [parents[0].name, parents[0][".id"]].includes(row.interface) && row["public-key"] === input.publicKey)
|
|
if (selected.length !== 1 || peerId !== undefined && selected[0][".id"] !== peerId) return false
|
|
const target = selected[0], body = wireguardPeerCreateBody(input)
|
|
body.interface = target.interface; body.disabled = String(count === 1)
|
|
if (!matches(target, body) || ["dynamic", "builtin", "default"].some(key => target[key] !== undefined && observedBoolean(target[key]) !== false)) return false
|
|
const next = structuredClone(state)
|
|
next.base.peers = next.base.peers.filter(row => row[".id"] !== target[".id"])
|
|
return await wireguardInterfaceDeleteProof(next) === baseline
|
|
}
|
|
export function wireguardPeerCreatePreserved(before: State, after: State, peerId: string) {
|
|
const old = before.base.peers.find(row => row[".id"] === peerId), current = after.base.peers.find(row => row[".id"] === peerId)
|
|
if (!old || !current) return false
|
|
const canonical = (row: Row) => wireguardConfigurationRows([{ ...row, disabled: String(observedBoolean(row.disabled)) }])
|
|
return fingerprint(canonical({ ...old, disabled: "false" })) === fingerprint(canonical(current))
|
|
}
|
|
export async function createWireguardPeer(server: ServerRow, raw: unknown, expectedProof?: string, authorize: () => Promise<unknown> = async () => {}, options: { recordRevision?: boolean } = {}) {
|
|
const parsed = wireguardPeerCreateSchema.safeParse(raw)
|
|
if (!parsed.success || parsed.data.serverId !== server.id) throw fail("INVALID_INPUT", "Некорректные параметры создания peer WireGuard")
|
|
const input = parsed.data
|
|
let protectionProof: string | undefined
|
|
const source = async () => {
|
|
await authorize()
|
|
const fresh = await getServerRowById(server.id)
|
|
if (!fresh?.enabled || fingerprint(fresh) !== fingerprint(server)) throw fail("STATE_CONFLICT", "Источник WireGuard изменился")
|
|
if (protectionProof !== undefined && await wireguardCreateProtectionProof(server.id) !== protectionProof) throw fail("STATE_CONFLICT", "Защиты WireGuard изменились")
|
|
}
|
|
return withApplicationMutationLock(() => withConfigMutationLock([server.id], () => executeGuardedApplicationWrite({ kind: "wireguard_peer", id: input.publicKey }, [server.id], async () => {
|
|
protectionProof = await wireguardCreateProtectionProof(server.id)
|
|
let state = await readWireguardInterfaceCreateState(server, source)
|
|
if (expectedProof && state.proof !== expectedProof) throw fail("STATE_CONFLICT", "WireGuard или зависимости изменились после подготовки")
|
|
assertWireguardPeerCreateAllowed(state, input)
|
|
const baseline = state.proof, stages = wireguardPeerCreateStages(input), client = MikrotikClient.fromServer(server)
|
|
let peerId: string | undefined
|
|
for (let index = 0; index < stages.length; index++) {
|
|
const fresh = await readWireguardInterfaceCreateState(server, source)
|
|
if (fresh.proof !== state.proof) throw fail(index ? "VERIFICATION_FAILED" : "STATE_CONFLICT", "WireGuard изменился между командами")
|
|
const dispatchFence = async () => {
|
|
const current = await readWireguardInterfaceCreateState(server, source)
|
|
if (current.proof !== fresh.proof) throw fail(index ? "VERIFICATION_FAILED" : "STATE_CONFLICT", "WireGuard изменился после native intent; команда не отправлена")
|
|
await source()
|
|
}
|
|
await source()
|
|
try {
|
|
if (index === 0) await client.put("/interface/wireguard/peers", wireguardPeerCreateBody(input), 15000, dispatchFence)
|
|
else await client.patch("/interface/wireguard/peers/" + encodeURIComponent(peerId!), { disabled: "false" }, 15000, dispatchFence)
|
|
} catch (error) { if (error instanceof McpError) throw error; throw fail("MUTATION_OUTCOME_UNKNOWN", "Исход создания peer неизвестен; выполнение остановлено без повтора") }
|
|
const prior = state
|
|
try { state = await readWireguardInterfaceCreateState(server, source) }
|
|
catch (error) {
|
|
throw markWireguardReadBackFailure(fail("MUTATION_OUTCOME_UNKNOWN", "Команда peer отправлена, read-back недоступен; повтор запрещён"), error)
|
|
}
|
|
if (!await wireguardPeerCreatePrefix(state, input, baseline, index + 1, peerId)) throw fail("VERIFICATION_FAILED", "Создание peer или сохранность конфигурации не подтверждены; повтор запрещён")
|
|
if (index && !wireguardPeerCreatePreserved(prior, state, peerId!)) throw fail("VERIFICATION_FAILED", "Подготовленный peer изменился при включении; повтор запрещён")
|
|
peerId ??= state.base.peers.find(row => row["public-key"] === input.publicKey && [input.interfaceName, state.base.interfaces.find(row => row.name === input.interfaceName)![".id"]].includes(row.interface))![".id"]
|
|
}
|
|
let revisionRecorded = false
|
|
try { if (options.recordRevision !== false) revisionRecorded = await captureAndAppendRevision({ serverId: server.id, section: "wireguard", source: "apply", capture: () => captureWireguardSnapshot(server, source) }) !== null } catch { /* A history failure never justifies replaying native creation. */ }
|
|
return { ok: true, verified: true, peerId: peerId!, afterProof: state.proof, commandCount: stages.length, revisionRecorded, forwardingVerified: false }
|
|
})))
|
|
}
|