231 lines
8.9 KiB
TypeScript
231 lines
8.9 KiB
TypeScript
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
|
import { z } from "zod"
|
|
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
|
|
import { getEnabledServerById } from "../services/wireguard-live.js"
|
|
import {
|
|
captureGreSnapshot,
|
|
fetchGreState,
|
|
formatKeepalive,
|
|
listGreTunnels,
|
|
parseKeepalive,
|
|
} from "../services/gre-live.js"
|
|
import {
|
|
canonicalGreSnapshot,
|
|
parseGreSnapshot,
|
|
planGreCreate,
|
|
planGreDelete,
|
|
planGreRestore,
|
|
} from "../services/entity-snapshots.js"
|
|
import { executeRosOps } from "../services/ros-ops.js"
|
|
import {
|
|
captureAndAppendRevision,
|
|
listRevisions,
|
|
loadRevisionForRestore,
|
|
type ConfigRevisionSource,
|
|
} from "../services/config-revisions.js"
|
|
import { parseDbServerId } from "../utils/server-id.js"
|
|
|
|
const TunnelWriteSchema = z.object({
|
|
serverId: z.string().min(1),
|
|
name: z.string().min(1),
|
|
rosId: z.string().optional(),
|
|
localAddress: z.string().optional(),
|
|
remoteAddress: z.string().min(1),
|
|
localInnerIp: z.string().optional(),
|
|
remoteInnerIp: z.string().optional(),
|
|
comment: z.string().optional(),
|
|
enabled: z.boolean().optional(),
|
|
mtu: z.number().optional(),
|
|
keepaliveInterval: z.number().optional(),
|
|
keepaliveRetries: z.number().optional(),
|
|
dscp: z.union([z.literal("inherit"), z.number(), z.string()]).optional(),
|
|
clampTcpMss: z.boolean().optional(),
|
|
allowFastPath: z.boolean().optional(),
|
|
ipsecSecret: z.string().optional(),
|
|
})
|
|
|
|
const TunnelKeySchema = z.object({
|
|
serverId: z.string().min(1),
|
|
rosId: z.string().optional(),
|
|
name: z.string().optional(),
|
|
disabled: z.boolean().optional(),
|
|
})
|
|
|
|
const RevisionIdParamSchema = z.object({ id: z.string().min(1) })
|
|
|
|
function rosErr(e: unknown): string {
|
|
if (e instanceof MikrotikError) return e.message
|
|
if (e instanceof Error) return e.message
|
|
return String(e)
|
|
}
|
|
|
|
async function recordGre(
|
|
server: NonNullable<Awaited<ReturnType<typeof getEnabledServerById>>>,
|
|
source: ConfigRevisionSource,
|
|
) {
|
|
await captureAndAppendRevision({
|
|
serverId: server.id,
|
|
section: "gre",
|
|
source,
|
|
capture: () => captureGreSnapshot(server),
|
|
})
|
|
}
|
|
|
|
function tunnelFromBody(body: z.infer<typeof TunnelWriteSchema> & { keepaliveInterval?: number; keepaliveRetries?: number }) {
|
|
const dscp = body.dscp == null
|
|
? "inherit"
|
|
: typeof body.dscp === "number"
|
|
? String(body.dscp)
|
|
: body.dscp
|
|
const keepalive = body.keepaliveInterval === undefined && body.keepaliveRetries === undefined
|
|
? undefined
|
|
: formatKeepalive(body.keepaliveInterval ?? 0, body.keepaliveRetries ?? 10)
|
|
return canonicalGreSnapshot({
|
|
tunnels: [{
|
|
name: body.name,
|
|
localAddress: body.localAddress ?? "",
|
|
remoteAddress: body.remoteAddress,
|
|
localInnerIp: body.localInnerIp ?? "",
|
|
remoteInnerIp: body.remoteInnerIp ?? "",
|
|
comment: body.comment ?? "",
|
|
disabled: body.enabled === false,
|
|
mtu: body.mtu ?? 1476,
|
|
keepalive: keepalive ?? "0",
|
|
dscp,
|
|
clampTcpMss: body.clampTcpMss,
|
|
allowFastPath: body.allowFastPath,
|
|
ipsecSecret: body.ipsecSecret ?? "",
|
|
}],
|
|
}).tunnels[0]!
|
|
}
|
|
|
|
const greRoutes: FastifyPluginAsyncZod = async (app) => {
|
|
app.get("/gre/tunnels", async (req, reply) => {
|
|
const q = req.query as { serverId?: string | number }
|
|
const sid = parseDbServerId(q.serverId)
|
|
if (q.serverId !== undefined && sid === null) return reply.status(400).send({ error: "Некорректный serverId GRE" })
|
|
const result = await listGreTunnels({ serverId: sid !== null ? String(sid) : undefined })
|
|
return reply.send(result)
|
|
})
|
|
|
|
app.post("/gre/tunnels", async (req, reply) => {
|
|
const parsed = TunnelWriteSchema.safeParse(req.body ?? {})
|
|
if (!parsed.success) {
|
|
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
|
}
|
|
const body = parsed.data
|
|
const server = await getEnabledServerById(body.serverId)
|
|
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
|
|
const client = MikrotikClient.fromServer(server)
|
|
try {
|
|
const tunnel = tunnelFromBody(body)
|
|
await executeRosOps(client, planGreCreate(tunnel))
|
|
await recordGre(server, "apply")
|
|
const state = await fetchGreState(server)
|
|
const created = state.tunnels.find((t) => t.name === tunnel.name)
|
|
return reply.status(201).send(created ?? { ok: true, name: tunnel.name })
|
|
} catch (e) {
|
|
return reply.status(502).send({ error: `RouterOS: ${rosErr(e)}` })
|
|
}
|
|
})
|
|
|
|
app.patch("/gre/tunnels", async (req, reply) => {
|
|
const parsed = TunnelWriteSchema.partial().required({ serverId: true }).safeParse(req.body ?? {})
|
|
if (!parsed.success) {
|
|
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
|
}
|
|
const body = parsed.data
|
|
const server = await getEnabledServerById(body.serverId)
|
|
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
|
|
try {
|
|
const state = await fetchGreState(server)
|
|
const live = state.gre.find((g) =>
|
|
(body.rosId && g.rosId === body.rosId) || (body.name && g.name === body.name),
|
|
)
|
|
if (!live) return reply.status(404).send({ error: "Туннель не найден" })
|
|
const merged = tunnelFromBody({
|
|
serverId: body.serverId,
|
|
name: body.name || live.name,
|
|
localAddress: body.localAddress ?? live.localAddress,
|
|
remoteAddress: body.remoteAddress || live.remoteAddress,
|
|
localInnerIp: body.localInnerIp ?? state.addrs.find((a) => a.interfaceName === live.name)?.address ?? "",
|
|
remoteInnerIp: body.remoteInnerIp,
|
|
comment: body.comment ?? live.comment,
|
|
enabled: body.enabled ?? !live.disabled,
|
|
mtu: body.mtu ?? live.mtu,
|
|
keepaliveInterval: body.keepaliveInterval ?? parseKeepalive(live.keepalive).interval,
|
|
keepaliveRetries: body.keepaliveRetries ?? parseKeepalive(live.keepalive).retries,
|
|
dscp: body.dscp ?? live.dscp,
|
|
clampTcpMss: body.clampTcpMss ?? live.clampTcpMss,
|
|
allowFastPath: body.allowFastPath ?? live.allowFastPath,
|
|
ipsecSecret: body.ipsecSecret ?? live.ipsecSecret,
|
|
})
|
|
const ops = planGreRestore(
|
|
{ tunnels: state.snapshot.tunnels.map((t) => t.name === live.name ? merged : t) },
|
|
{ gre: state.gre, addrs: state.addrs },
|
|
)
|
|
await executeRosOps(state.client, ops)
|
|
await recordGre(server, "apply")
|
|
return reply.send({ ok: true })
|
|
} catch (e) {
|
|
return reply.status(502).send({ error: `RouterOS: ${rosErr(e)}` })
|
|
}
|
|
})
|
|
|
|
app.delete("/gre/tunnels", async (req, reply) => {
|
|
const parsed = TunnelKeySchema.safeParse(req.body ?? {})
|
|
if (!parsed.success) {
|
|
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
|
}
|
|
const body = parsed.data
|
|
const server = await getEnabledServerById(body.serverId)
|
|
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
|
|
try {
|
|
const state = await fetchGreState(server)
|
|
const live = state.gre.find((g) =>
|
|
(body.rosId && g.rosId === body.rosId) || (body.name && g.name === body.name),
|
|
)
|
|
if (!live) return reply.status(404).send({ error: "Туннель не найден" })
|
|
await executeRosOps(state.client, planGreDelete(live.name, { gre: state.gre, addrs: state.addrs }))
|
|
await recordGre(server, "apply")
|
|
return reply.send({ ok: true })
|
|
} catch (e) {
|
|
return reply.status(502).send({ error: `RouterOS: ${rosErr(e)}` })
|
|
}
|
|
})
|
|
|
|
app.get("/gre/revisions", async (req, reply) => {
|
|
const q = req.query as { serverId?: string | number }
|
|
const serverId = parseDbServerId(q.serverId)
|
|
if (serverId === null) return reply.status(400).send({ error: "serverId is required" })
|
|
const revisions = await listRevisions(serverId, "gre")
|
|
return reply.send({ revisions })
|
|
})
|
|
|
|
app.post("/gre/revisions/:id/restore", {
|
|
schema: { params: RevisionIdParamSchema },
|
|
}, async (req, reply) => {
|
|
const { id } = req.params
|
|
const body = req.body as { serverId?: string | number } | undefined
|
|
const loaded = await loadRevisionForRestore({
|
|
id,
|
|
section: "gre",
|
|
requestedServerId: parseDbServerId(body?.serverId),
|
|
})
|
|
if (!loaded.ok) return reply.status(loaded.status).send({ error: loaded.error })
|
|
try {
|
|
const desired = parseGreSnapshot(loaded.row.payload)
|
|
const state = await fetchGreState(loaded.server)
|
|
const ops = planGreRestore(desired, { gre: state.gre, addrs: state.addrs })
|
|
await executeRosOps(state.client, ops)
|
|
await recordGre(loaded.server, "rollback")
|
|
const next = await fetchGreState(loaded.server)
|
|
return reply.send({ ok: true, tunnels: next.tunnels })
|
|
} catch (e) {
|
|
return reply.status(502).send({ error: `RouterOS: ${rosErr(e)}` })
|
|
}
|
|
})
|
|
}
|
|
|
|
export default greRoutes
|