feat(wireguard): implement WireGuard interface management and permissions
Docker images / prepare-release (push) Successful in 8s
Docker images / backend-image (push) Successful in 1m39s
Docker images / frontend-image (push) Successful in 2m56s
Docker images / notify-webhook (push) Skipped
Docker images / updater-image (push) Successful in 53s
Docker images / publish-release (push) Successful in 10s

Added comprehensive support for managing WireGuard interfaces, including CRUD operations and peer management. Updated permissions to include access control for WireGuard routes. Enhanced the UI components to display and interact with WireGuard configurations, improving user experience and functionality. Introduced new tests for WireGuard-related functionalities to ensure reliability.
This commit is contained in:
Denozordec
2026-09-05 02:10:55 +07:00
parent 883842636b
commit 15ad53af1f
25 changed files with 3122 additions and 231 deletions
+2
View File
@@ -23,6 +23,7 @@ import backupsRoutes from "./routes/backups.js"
import certificatesRoutes from "./routes/certificates.js"
import systemDatabaseRoutes from "./routes/system-database.js"
import eventsRoutes from "./routes/events.js"
import wireguardRoutes from "./routes/wireguard.js"
import { refreshScheduler, stopScheduler } from "./services/scheduler.js"
export async function buildApp(opts?: {
@@ -103,6 +104,7 @@ export async function buildApp(opts?: {
await app.register(certificatesRoutes, { prefix: "/api" })
await app.register(systemDatabaseRoutes, { prefix: "/api" })
await app.register(eventsRoutes, { prefix: "/api" })
await app.register(wireguardRoutes, { prefix: "/api" })
if (opts?.startScheduler !== false) {
refreshScheduler()
+8
View File
@@ -21,5 +21,13 @@ assert.equal(
permissionForRequest("GET", "/api/unknown-thing"),
"mm:dashboard:read",
)
assert.equal(
permissionForRequest("GET", "/api/wireguard"),
"mm:network:read",
)
assert.equal(
permissionForRequest("POST", "/api/wireguard/interfaces"),
"mm:network:write",
)
console.log("permissions.test.ts: ok")
+4 -2
View File
@@ -141,7 +141,8 @@ const RULES: Rule[] = [
p.startsWith("/api/recursive") ||
p.startsWith("/api/probes") ||
p.startsWith("/api/internet-path") ||
p.startsWith("/api/exec"),
p.startsWith("/api/exec") ||
p.startsWith("/api/wireguard"),
permission: "mm:network:read",
},
{
@@ -152,7 +153,8 @@ const RULES: Rule[] = [
p.startsWith("/api/recursive") ||
p.startsWith("/api/probes") ||
p.startsWith("/api/internet-path") ||
p.startsWith("/api/exec"),
p.startsWith("/api/exec") ||
p.startsWith("/api/wireguard"),
permission: "mm:network:write",
},
]
+4
View File
@@ -1,5 +1,6 @@
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { listCertificatesFromServers } from "../services/certificates-service.js"
import { countWireGuardInterfaces } from "../services/wireguard-live.js"
import { db } from "../db/index.js"
import {
filterRules,
@@ -18,6 +19,7 @@ const sidebarCountsRoutes: FastifyPluginAsyncZod = async (app) => {
uptimeSpeedProbesTotal,
recursiveRoutesTotal,
certificatesTotal,
wireguardTotal,
] = await Promise.all([
Promise.resolve(db.select().from(servers).all().length),
Promise.resolve(db.select().from(filterRules).all().length),
@@ -25,6 +27,7 @@ const sidebarCountsRoutes: FastifyPluginAsyncZod = async (app) => {
Promise.resolve(db.select().from(uptimeSpeedProbes).all().length),
Promise.resolve(db.select().from(recursiveRoutes).all().length),
listCertificatesFromServers().then((res) => res.certificates.length),
countWireGuardInterfaces().catch(() => 0),
])
return reply.send({
@@ -35,6 +38,7 @@ const sidebarCountsRoutes: FastifyPluginAsyncZod = async (app) => {
monitoringItems: uptimeProbesTotal + uptimeSpeedProbesTotal,
recursiveRoutes: recursiveRoutesTotal,
certificates: certificatesTotal,
wireguard: wireguardTotal,
})
})
}
+456
View File
@@ -0,0 +1,456 @@
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import {
wgCreateInterfaceSchema,
wgCreatePeerRequestSchema,
wgExportRequestSchema,
wgImportRequestSchema,
wgPatchInterfaceSchema,
wgPatchPeerSchema,
type WgCreatePeerRequest,
type WgIfaceDto,
} from "@mmapp/contracts/wireguard"
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
import {
generateMikrotikRsc,
generateNativeConf,
generatePeerClientConf,
parseWgConfig,
type WgParsedConfig,
} from "../services/wireguard-config.js"
import {
getEnabledServerById,
listWireGuardInterfaces,
} from "../services/wireguard-live.js"
function serverIdParam(v: string): string {
return decodeURIComponent(v)
}
function rosIdParam(v: string): string {
return decodeURIComponent(v)
}
function toRosBody(obj: Record<string, string | undefined>): Record<string, string> {
const out: Record<string, string> = {}
for (const [k, v] of Object.entries(obj)) {
if (v !== undefined && v !== "") out[k] = v
}
return out
}
function peerToRosBody(p: Omit<WgCreatePeerRequest, "serverId" | "interfaceName"> & { interfaceName: string }) {
return toRosBody({
interface: p.interfaceName,
"public-key": p.publicKey,
"allowed-address": p.allowedAddresses.join(","),
"endpoint-address": p.endpointAddress,
"endpoint-port": p.endpointPort != null ? String(p.endpointPort) : undefined,
"persistent-keepalive":
p.persistentKeepalive != null ? String(p.persistentKeepalive) : undefined,
comment: p.comment,
name: p.name,
"private-key": typeof p.privateKey === "string" ? p.privateKey : undefined,
"client-address": p.clientAddress,
"client-dns": p.clientDns,
"client-endpoint": p.clientEndpoint,
disabled: p.disabled === true ? "yes" : p.disabled === false ? "no" : undefined,
})
}
function previewFromParsed(parsed: WgParsedConfig) {
return {
format: parsed.format,
interface: {
name: parsed.interface.name,
listenPort: parsed.interface.listenPort,
mtu: parsed.interface.mtu,
privateKey: parsed.interface.privateKey,
comment: parsed.interface.comment,
address: parsed.interface.address,
disabled: parsed.interface.disabled,
},
peers: parsed.peers.map((p) => ({
publicKey: p.publicKey,
allowedAddresses: p.allowedAddresses,
endpointAddress: p.endpointAddress,
endpointPort: p.endpointPort,
persistentKeepalive: p.persistentKeepalive,
comment: p.comment,
name: p.name,
privateKey: p.privateKey,
clientAddress: p.clientAddress,
clientDns: p.clientDns,
clientEndpoint: p.clientEndpoint,
disabled: p.disabled,
})),
}
}
async function applyParsedConfig(
client: MikrotikClient,
parsed: WgParsedConfig,
): Promise<{ interfaceName: string; peersCreated: number }> {
const name = parsed.interface.name
const ifaceBody = toRosBody({
name,
"listen-port": String(parsed.interface.listenPort ?? 13231),
mtu: String(parsed.interface.mtu ?? 1420),
"private-key": parsed.interface.privateKey,
comment: parsed.interface.comment,
disabled: parsed.interface.disabled ? "yes" : undefined,
})
await client.put("/interface/wireguard", ifaceBody)
if (parsed.interface.address) {
await client.put("/ip/address", {
address: parsed.interface.address,
interface: name,
})
}
let peersCreated = 0
for (const p of parsed.peers) {
if (!p.publicKey) continue
await client.put(
"/interface/wireguard/peers",
peerToRosBody({
interfaceName: name,
publicKey: p.publicKey,
allowedAddresses: p.allowedAddresses.length ? p.allowedAddresses : ["0.0.0.0/0"],
endpointAddress: p.endpointAddress,
endpointPort: p.endpointPort,
persistentKeepalive: p.persistentKeepalive,
comment: p.comment,
name: p.name,
privateKey: p.privateKey,
clientAddress: p.clientAddress,
clientDns: p.clientDns,
clientEndpoint: p.clientEndpoint,
disabled: p.disabled,
}),
)
peersCreated += 1
}
return { interfaceName: name, peersCreated }
}
function findIface(
list: WgIfaceDto[],
serverId: string,
interfaceName: string,
): WgIfaceDto | undefined {
return list.find((i) => i.serverId === serverId && i.name === interfaceName)
}
const wireguardRoutes: FastifyPluginAsyncZod = async (app) => {
app.get("/wireguard", async (req, reply) => {
const q = req.query as { serverId?: string; includePrivateKey?: string }
const includePrivateKey = q.includePrivateKey === "1" || q.includePrivateKey === "true"
const result = await listWireGuardInterfaces({
serverId: q.serverId,
includePrivateKey,
})
return reply.send(result)
})
app.post("/wireguard/interfaces", async (req, reply) => {
const parsed = wgCreateInterfaceSchema.safeParse(req.body ?? {})
if (!parsed.success) {
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
}
const body = parsed.data
const server = getEnabledServerById(body.serverId)
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
const client = MikrotikClient.fromServer(server)
try {
await client.put(
"/interface/wireguard",
toRosBody({
name: body.name,
"listen-port": String(body.listenPort),
mtu: String(body.mtu),
comment: body.comment,
"private-key": body.privateKey,
disabled: body.disabled ? "yes" : undefined,
}),
)
if (body.address) {
await client.put("/ip/address", {
address: body.address,
interface: body.name,
})
}
if (body.peer) {
await client.put(
"/interface/wireguard/peers",
peerToRosBody({ ...body.peer, interfaceName: body.name }),
)
}
const list = await listWireGuardInterfaces({
serverId: String(server.id),
includePrivateKey: true,
})
const created = list.interfaces.find((i) => i.name === body.name)
return reply.status(201).send(created ?? { ok: true, name: body.name })
} catch (e) {
const msg = e instanceof MikrotikError ? e.message : e instanceof Error ? e.message : String(e)
return reply.status(502).send({ error: `RouterOS: ${msg}` })
}
})
app.patch("/wireguard/interfaces/:serverId/:rosId", async (req, reply) => {
const { serverId, rosId } = req.params as { serverId: string; rosId: string }
const parsed = wgPatchInterfaceSchema.safeParse(req.body ?? {})
if (!parsed.success) {
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
}
const server = getEnabledServerById(serverIdParam(serverId))
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
const client = MikrotikClient.fromServer(server)
const d = parsed.data
try {
await client.patch(
`/interface/wireguard/${encodeURIComponent(rosIdParam(rosId))}`,
toRosBody({
name: d.name,
"listen-port": d.listenPort != null ? String(d.listenPort) : undefined,
mtu: d.mtu != null ? String(d.mtu) : undefined,
comment: d.comment,
"private-key": d.privateKey,
disabled: d.disabled === true ? "yes" : d.disabled === false ? "no" : undefined,
}),
)
return reply.send({ ok: true })
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return reply.status(502).send({ error: `RouterOS: ${msg}` })
}
})
app.delete("/wireguard/interfaces/:serverId/:rosId", async (req, reply) => {
const { serverId, rosId } = req.params as { serverId: string; rosId: string }
const server = getEnabledServerById(serverIdParam(serverId))
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
const client = MikrotikClient.fromServer(server)
try {
await client.delete(`/interface/wireguard/${encodeURIComponent(rosIdParam(rosId))}`)
return reply.send({ ok: true })
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return reply.status(502).send({ error: `RouterOS: ${msg}` })
}
})
app.post("/wireguard/peers", async (req, reply) => {
const parsed = wgCreatePeerRequestSchema.safeParse(req.body ?? {})
if (!parsed.success) {
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
}
const body = parsed.data
const server = getEnabledServerById(body.serverId)
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
const client = MikrotikClient.fromServer(server)
try {
await client.put("/interface/wireguard/peers", peerToRosBody(body))
return reply.status(201).send({ ok: true })
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return reply.status(502).send({ error: `RouterOS: ${msg}` })
}
})
app.patch("/wireguard/peers/:serverId/:rosId", async (req, reply) => {
const { serverId, rosId } = req.params as { serverId: string; rosId: string }
const parsed = wgPatchPeerSchema.safeParse(req.body ?? {})
if (!parsed.success) {
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
}
const server = getEnabledServerById(serverIdParam(serverId))
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
const d = parsed.data
const client = MikrotikClient.fromServer(server)
try {
await client.patch(
`/interface/wireguard/peers/${encodeURIComponent(rosIdParam(rosId))}`,
toRosBody({
"public-key": d.publicKey,
"allowed-address": d.allowedAddresses?.join(","),
"endpoint-address": d.endpointAddress,
"endpoint-port": d.endpointPort != null ? String(d.endpointPort) : undefined,
"persistent-keepalive":
d.persistentKeepalive != null ? String(d.persistentKeepalive) : undefined,
comment: d.comment,
name: d.name,
"client-address": d.clientAddress,
"client-dns": d.clientDns,
"client-endpoint": d.clientEndpoint,
disabled: d.disabled === true ? "yes" : d.disabled === false ? "no" : undefined,
}),
)
return reply.send({ ok: true })
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return reply.status(502).send({ error: `RouterOS: ${msg}` })
}
})
app.delete("/wireguard/peers/:serverId/:rosId", async (req, reply) => {
const { serverId, rosId } = req.params as { serverId: string; rosId: string }
const server = getEnabledServerById(serverIdParam(serverId))
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
const client = MikrotikClient.fromServer(server)
try {
await client.delete(`/interface/wireguard/peers/${encodeURIComponent(rosIdParam(rosId))}`)
return reply.send({ ok: true })
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return reply.status(502).send({ error: `RouterOS: ${msg}` })
}
})
app.post("/wireguard/import", async (req, reply) => {
const parsed = wgImportRequestSchema.safeParse(req.body ?? {})
if (!parsed.success) {
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
}
const body = parsed.data
let config: WgParsedConfig
try {
config = parseWgConfig(body.content, body.format)
} catch (e) {
return reply.status(400).send({ error: e instanceof Error ? e.message : "Ошибка разбора конфига" })
}
const preview = previewFromParsed(config)
if (body.dryRun) {
return reply.send({ dryRun: true, preview })
}
const server = getEnabledServerById(body.serverId)
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
const client = MikrotikClient.fromServer(server)
try {
const applied = await applyParsedConfig(client, config)
return reply.send({ dryRun: false, preview, applied })
} catch (e) {
const msg = e instanceof Error ? e.message : String(e)
return reply.status(502).send({ error: `RouterOS: ${msg}`, preview })
}
})
app.post("/wireguard/export", async (req, reply) => {
const parsed = wgExportRequestSchema.safeParse(req.body ?? {})
if (!parsed.success) {
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
}
const body = parsed.data
const server = getEnabledServerById(body.serverId)
if (!server) return reply.status(404).send({ error: "Сервер не найден" })
const list = await listWireGuardInterfaces({
serverId: String(server.id),
includePrivateKey: body.includePrivateKey === true,
})
const iface = findIface(list.interfaces, String(server.id), body.interfaceName)
if (!iface) return reply.status(404).send({ error: "Интерфейс не найден" })
if (body.format === "rsc") {
const content = generateMikrotikRsc({
name: iface.name,
listenPort: iface.listenPort,
mtu: iface.mtu,
comment: iface.comment,
enabled: iface.enabled,
privateKey: body.includePrivateKey ? iface.privateKey : undefined,
publicKey: iface.publicKey,
address: iface.address,
serverName: iface.serverName,
peers: iface.peers.map((p) => ({
publicKey: p.publicKey,
allowedIps: p.allowedIps,
endpoint: p.endpoint,
persistentKeepalive: p.persistentKeepalive,
persistent: p.persistent,
comment: p.comment,
name: p.name,
clientAddress: p.clientAddress,
clientDns: p.clientDns,
clientEndpoint: p.clientEndpoint,
})),
})
return reply.send({
format: "rsc",
filename: `${iface.name}.rsc`,
content,
})
}
if (body.format === "conf") {
const content = generateNativeConf(
{
name: iface.name,
listenPort: iface.listenPort,
mtu: iface.mtu,
comment: iface.comment,
enabled: iface.enabled,
privateKey: iface.privateKey,
publicKey: iface.publicKey,
address: iface.address,
serverName: iface.serverName,
peers: iface.peers.map((p) => ({
publicKey: p.publicKey,
allowedIps: p.allowedIps,
endpoint: p.endpoint,
persistentKeepalive: p.persistentKeepalive,
persistent: p.persistent,
comment: p.comment,
})),
},
{ includePrivateKey: body.includePrivateKey === true },
)
return reply.send({
format: "conf",
filename: `${iface.name}.conf`,
content,
})
}
// peer-conf
const peer = body.peerId
? iface.peers.find((p) => p.id === body.peerId || p.rosId === body.peerId)
: iface.peers[0]
if (!peer) return reply.status(404).send({ error: "Пир не найден" })
if (!iface.publicKey) {
return reply.status(400).send({ error: "У интерфейса нет public-key" })
}
const endpoint =
peer.clientEndpoint ||
(peer.endpoint
? peer.endpoint
: undefined)
const content = generatePeerClientConf({
peerAddress: peer.clientAddress,
peerDns: peer.clientDns,
serverPublicKey: iface.publicKey,
allowedIps: peer.allowedIps.length ? peer.allowedIps : ["0.0.0.0/0"],
endpoint:
endpoint ||
(peer.clientEndpoint
? peer.clientEndpoint.includes(":")
? peer.clientEndpoint
: `${peer.clientEndpoint}:${iface.listenPort}`
: undefined),
persistentKeepalive: peer.persistentKeepalive ?? 25,
})
return reply.send({
format: "peer-conf",
filename: `${iface.name}-peer.conf`,
content,
})
})
}
export default wireguardRoutes
@@ -0,0 +1,100 @@
import assert from "node:assert/strict"
import {
detectWgConfigFormat,
generateMikrotikRsc,
generateNativeConf,
parseMikrotikRsc,
parseNativeConf,
parseWgConfig,
} from "./wireguard-config.js"
const sampleConf = `[Interface]
PrivateKey = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=
Address = 10.210.0.1/30
ListenPort = 13231
MTU = 1420
[Peer]
PublicKey = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb=
AllowedIPs = 10.210.0.2/32, 192.168.20.0/24
Endpoint = 10.0.1.1:13231
PersistentKeepalive = 25
`
const parsedConf = parseNativeConf(sampleConf)
assert.equal(parsedConf.format, "conf")
assert.equal(parsedConf.interface.listenPort, 13231)
assert.equal(parsedConf.interface.address, "10.210.0.1/30")
assert.equal(parsedConf.peers.length, 1)
assert.equal(parsedConf.peers[0]?.endpointAddress, "10.0.1.1")
assert.equal(parsedConf.peers[0]?.endpointPort, 13231)
assert.deepEqual(parsedConf.peers[0]?.allowedAddresses, ["10.210.0.2/32", "192.168.20.0/24"])
const roundConf = generateNativeConf({
name: "wg0",
listenPort: parsedConf.interface.listenPort ?? 13231,
mtu: parsedConf.interface.mtu ?? 1420,
privateKey: parsedConf.interface.privateKey,
address: parsedConf.interface.address,
peers: parsedConf.peers.map((p) => ({
publicKey: p.publicKey,
allowedIps: p.allowedAddresses,
endpoint: p.endpointAddress
? `${p.endpointAddress}:${p.endpointPort ?? 13231}`
: undefined,
persistentKeepalive: p.persistentKeepalive,
})),
})
const reparsed = parseNativeConf(roundConf)
assert.equal(reparsed.interface.privateKey, parsedConf.interface.privateKey)
assert.equal(reparsed.peers[0]?.publicKey, parsedConf.peers[0]?.publicKey)
const sampleRsc = `# WireGuard
/interface wireguard add \\
name=wg-msk-spb \\
listen-port=13231 \\
mtu=1420 \\
comment="MSK → SPB"
/ip address add \\
address=10.210.0.1/30 \\
interface=wg-msk-spb
/interface wireguard peers add \\
interface=wg-msk-spb \\
public-key="SPBPublicKeyBase64AAAAAAAAAAAAAAAAAAAAAA=" \\
allowed-address=10.210.0.2/32,192.168.20.0/24 \\
endpoint-address=10.0.1.1 \\
endpoint-port=13231 \\
persistent-keepalive=25
`
assert.equal(detectWgConfigFormat(sampleRsc), "rsc")
assert.equal(detectWgConfigFormat(sampleConf), "conf")
const parsedRsc = parseMikrotikRsc(sampleRsc)
assert.equal(parsedRsc.interface.name, "wg-msk-spb")
assert.equal(parsedRsc.interface.address, "10.210.0.1/30")
assert.equal(parsedRsc.peers.length, 1)
assert.equal(parsedRsc.peers[0]?.endpointPort, 13231)
const generatedRsc = generateMikrotikRsc({
name: parsedRsc.interface.name,
listenPort: parsedRsc.interface.listenPort ?? 13231,
mtu: parsedRsc.interface.mtu ?? 1420,
comment: parsedRsc.interface.comment,
address: parsedRsc.interface.address,
peers: parsedRsc.peers.map((p) => ({
publicKey: p.publicKey,
allowedIps: p.allowedAddresses,
endpoint: p.endpointAddress
? `${p.endpointAddress}:${p.endpointPort ?? 13231}`
: undefined,
persistentKeepalive: p.persistentKeepalive,
})),
})
const rscAgain = parseWgConfig(generatedRsc, "rsc")
assert.equal(rscAgain.interface.name, "wg-msk-spb")
assert.equal(rscAgain.peers[0]?.publicKey, parsedRsc.peers[0]?.publicKey)
console.log("wireguard-config tests ok")
+359
View File
@@ -0,0 +1,359 @@
/**
* WireGuard config codecs: native .conf ↔ MikroTik .rsc
*/
export type WgParsedPeer = {
publicKey: string
allowedAddresses: string[]
endpointAddress?: string
endpointPort?: number
persistentKeepalive?: number
comment?: string
name?: string
privateKey?: "auto" | "none" | string
clientAddress?: string
clientDns?: string
clientEndpoint?: string
disabled?: boolean
}
export type WgParsedInterface = {
name: string
listenPort?: number
mtu?: number
privateKey?: string
comment?: string
address?: string
disabled?: boolean
}
export type WgParsedConfig = {
format: "rsc" | "conf"
interface: WgParsedInterface
peers: WgParsedPeer[]
}
export type WgExportIface = {
name: string
listenPort: number
mtu: number
comment?: string
enabled?: boolean
privateKey?: string
publicKey?: string
address?: string
serverName?: string
peers: Array<{
publicKey: string
allowedIps: string[]
endpoint?: string
persistentKeepalive?: number
persistent?: boolean
comment?: string
name?: string
clientAddress?: string
clientDns?: string
clientEndpoint?: string
}>
}
function stripQuotes(v: string): string {
const t = v.trim()
if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
return t.slice(1, -1)
}
return t
}
function parseKvLine(line: string): Record<string, string> {
const out: Record<string, string> = {}
// Match key=value pairs; values may be quoted
const re = /([a-zA-Z0-9_-]+)=("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s\\]+)/g
let m: RegExpExecArray | null
while ((m = re.exec(line)) !== null) {
out[m[1]] = stripQuotes(m[2])
}
return out
}
function joinContinuedLines(text: string): string[] {
const raw = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n")
const lines: string[] = []
let buf = ""
for (const line of raw) {
const trimmedEnd = line.replace(/\s+$/, "")
if (trimmedEnd.endsWith("\\")) {
buf += trimmedEnd.slice(0, -1).trimEnd() + " "
continue
}
buf += trimmedEnd
if (buf.trim()) lines.push(buf.trim())
buf = ""
}
if (buf.trim()) lines.push(buf.trim())
return lines
}
export function detectWgConfigFormat(content: string): "rsc" | "conf" {
const t = content.trim()
if (/\[Interface\]/i.test(t) || /\[Peer\]/i.test(t)) return "conf"
if (/\/interface\s+wireguard/i.test(t) || /\/interface\/wireguard/i.test(t)) return "rsc"
if (/PrivateKey\s*=/i.test(t) || /PublicKey\s*=/i.test(t)) return "conf"
return "rsc"
}
export function parseNativeConf(content: string): WgParsedConfig {
const lines = content.replace(/\r\n/g, "\n").split("\n")
let section: "interface" | "peer" | null = null
const iface: WgParsedInterface = { name: "wg0" }
const peers: WgParsedPeer[] = []
let currentPeer: WgParsedPeer | null = null
const flushPeer = () => {
if (currentPeer?.publicKey) peers.push(currentPeer)
currentPeer = null
}
for (const raw of lines) {
const line = raw.trim()
if (!line || line.startsWith("#") || line.startsWith(";")) continue
if (/^\[Interface\]$/i.test(line)) {
flushPeer()
section = "interface"
continue
}
if (/^\[Peer\]$/i.test(line)) {
flushPeer()
section = "peer"
currentPeer = { publicKey: "", allowedAddresses: [] }
continue
}
const eq = line.indexOf("=")
if (eq < 0) continue
const key = line.slice(0, eq).trim().toLowerCase()
const value = line.slice(eq + 1).trim()
if (section === "interface") {
if (key === "privatekey") iface.privateKey = value
else if (key === "address") iface.address = value.split(",")[0]?.trim()
else if (key === "listenport") iface.listenPort = Number.parseInt(value, 10) || undefined
else if (key === "mtu") iface.mtu = Number.parseInt(value, 10) || undefined
else if (key === "name") iface.name = value || iface.name
} else if (section === "peer" && currentPeer) {
if (key === "publickey") currentPeer.publicKey = value
else if (key === "allowedips") {
currentPeer.allowedAddresses = value
.split(",")
.map((s) => s.trim())
.filter(Boolean)
} else if (key === "endpoint") {
const lastColon = value.lastIndexOf(":")
if (lastColon > 0 && !value.includes("]:")) {
currentPeer.endpointAddress = value.slice(0, lastColon)
currentPeer.endpointPort = Number.parseInt(value.slice(lastColon + 1), 10) || undefined
} else if (value.startsWith("[") && value.includes("]:")) {
const idx = value.indexOf("]:")
currentPeer.endpointAddress = value.slice(1, idx)
currentPeer.endpointPort = Number.parseInt(value.slice(idx + 2), 10) || undefined
} else {
currentPeer.endpointAddress = value
}
} else if (key === "persistentkeepalive") {
currentPeer.persistentKeepalive = Number.parseInt(value, 10) || undefined
} else if (key === "presharedkey") {
// ignore PSK for ROS import for now
}
}
}
flushPeer()
if (!iface.name) iface.name = "wg0"
return { format: "conf", interface: iface, peers }
}
export function parseMikrotikRsc(content: string): WgParsedConfig {
const lines = joinContinuedLines(content)
const iface: WgParsedInterface = { name: "wg0" }
const peers: WgParsedPeer[] = []
let foundIface = false
for (const line of lines) {
if (line.startsWith("#")) continue
const lower = line.toLowerCase()
if (
lower.startsWith("/interface wireguard add") ||
lower.startsWith("/interface/wireguard add")
) {
const kv = parseKvLine(line)
if (kv.name) iface.name = kv.name
if (kv["listen-port"]) iface.listenPort = Number.parseInt(kv["listen-port"], 10) || undefined
if (kv.mtu) iface.mtu = Number.parseInt(kv.mtu, 10) || undefined
if (kv["private-key"]) iface.privateKey = kv["private-key"]
if (kv.comment) iface.comment = kv.comment
if (kv.disabled === "yes") iface.disabled = true
foundIface = true
continue
}
if (
lower.startsWith("/interface wireguard peers add") ||
lower.startsWith("/interface/wireguard/peers add")
) {
const kv = parseKvLine(line)
const allowed = (kv["allowed-address"] ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean)
peers.push({
publicKey: kv["public-key"] ?? "",
allowedAddresses: allowed.length ? allowed : ["0.0.0.0/0"],
endpointAddress: kv["endpoint-address"],
endpointPort: kv["endpoint-port"]
? Number.parseInt(kv["endpoint-port"], 10) || undefined
: undefined,
persistentKeepalive: kv["persistent-keepalive"]
? Number.parseInt(kv["persistent-keepalive"], 10) || undefined
: undefined,
comment: kv.comment,
name: kv.name,
clientAddress: kv["client-address"],
clientDns: kv["client-dns"],
clientEndpoint: kv["client-endpoint"],
disabled: kv.disabled === "yes",
})
continue
}
if (lower.startsWith("/ip address add") || lower.startsWith("/ip/address add")) {
const kv = parseKvLine(line)
if (kv.address) iface.address = kv.address
continue
}
}
if (!foundIface && peers.length === 0) {
throw new Error("Не удалось распознать RouterOS WireGuard .rsc")
}
return { format: "rsc", interface: iface, peers }
}
export function parseWgConfig(
content: string,
format: "auto" | "rsc" | "conf" = "auto",
): WgParsedConfig {
const detected = format === "auto" ? detectWgConfigFormat(content) : format
if (detected === "conf") return parseNativeConf(content)
return parseMikrotikRsc(content)
}
export function generateNativeConf(iface: WgExportIface, opts?: { includePrivateKey?: boolean }): string {
const lines: string[] = []
lines.push(`[Interface]`)
if (opts?.includePrivateKey && iface.privateKey) {
lines.push(`PrivateKey = ${iface.privateKey}`)
} else if (iface.privateKey) {
lines.push(`PrivateKey = ${iface.privateKey}`)
} else {
lines.push(`# PrivateKey = <заполните приватный ключ с роутера>`)
}
if (iface.address) lines.push(`Address = ${iface.address}`)
lines.push(`ListenPort = ${iface.listenPort}`)
if (iface.mtu) lines.push(`MTU = ${iface.mtu}`)
lines.push(``)
for (const p of iface.peers) {
lines.push(`[Peer]`)
lines.push(`PublicKey = ${p.publicKey}`)
lines.push(`AllowedIPs = ${p.allowedIps.join(", ")}`)
if (p.endpoint) lines.push(`Endpoint = ${p.endpoint}`)
const ka = p.persistentKeepalive ?? (p.persistent ? 25 : undefined)
if (ka != null && ka > 0) lines.push(`PersistentKeepalive = ${ka}`)
if (p.comment) lines.push(`# ${p.comment}`)
lines.push(``)
}
return lines.join("\n").trimEnd() + "\n"
}
export function generatePeerClientConf(args: {
peerPrivateKey?: string
peerAddress?: string
peerDns?: string
serverPublicKey: string
allowedIps?: string[]
endpoint?: string
persistentKeepalive?: number
}): string {
const lines: string[] = []
lines.push(`[Interface]`)
lines.push(
args.peerPrivateKey
? `PrivateKey = ${args.peerPrivateKey}`
: `# PrivateKey = <ключ клиента>`,
)
if (args.peerAddress) lines.push(`Address = ${args.peerAddress}`)
if (args.peerDns) lines.push(`DNS = ${args.peerDns}`)
lines.push(``)
lines.push(`[Peer]`)
lines.push(`PublicKey = ${args.serverPublicKey}`)
lines.push(`AllowedIPs = ${(args.allowedIps?.length ? args.allowedIps : ["0.0.0.0/0"]).join(", ")}`)
if (args.endpoint) lines.push(`Endpoint = ${args.endpoint}`)
if (args.persistentKeepalive != null && args.persistentKeepalive > 0) {
lines.push(`PersistentKeepalive = ${args.persistentKeepalive}`)
}
lines.push(``)
return lines.join("\n")
}
export function generateMikrotikRsc(iface: WgExportIface): string {
const lines: string[] = []
lines.push(`# WireGuard — ${iface.name}${iface.serverName ? ` · ${iface.serverName}` : ""}`)
lines.push(`# RouterOS 7.x · MikrotikManager`)
lines.push(``)
lines.push(`/interface wireguard add \\`)
lines.push(` name=${iface.name} \\`)
lines.push(` listen-port=${iface.listenPort} \\`)
lines.push(` mtu=${iface.mtu} \\`)
if (iface.privateKey) lines.push(` private-key="${iface.privateKey}" \\`)
if (iface.comment) lines.push(` comment="${iface.comment.replace(/"/g, '\\"')}" \\`)
if (iface.enabled === false) lines.push(` disabled=yes \\`)
// remove trailing backslash on last iface param by rewriting last line
if (lines[lines.length - 1]?.endsWith(" \\")) {
lines[lines.length - 1] = lines[lines.length - 1]!.slice(0, -2)
}
lines.push(``)
if (iface.address) {
lines.push(`/ip address add \\`)
lines.push(` address=${iface.address} \\`)
lines.push(` interface=${iface.name}`)
lines.push(``)
}
for (const p of iface.peers) {
lines.push(`/interface wireguard peers add \\`)
lines.push(` interface=${iface.name} \\`)
lines.push(` public-key="${p.publicKey}" \\`)
lines.push(` allowed-address=${p.allowedIps.join(",")} \\`)
if (p.endpoint) {
const host = p.endpoint.includes(":") ? p.endpoint.slice(0, p.endpoint.lastIndexOf(":")) : p.endpoint
const port = p.endpoint.includes(":")
? p.endpoint.slice(p.endpoint.lastIndexOf(":") + 1)
: "13231"
lines.push(` endpoint-address=${host} \\`)
lines.push(` endpoint-port=${port} \\`)
}
const ka = p.persistentKeepalive ?? (p.persistent ? 25 : undefined)
if (ka != null && ka > 0) lines.push(` persistent-keepalive=${ka} \\`)
if (p.name) lines.push(` name=${p.name} \\`)
if (p.clientAddress) lines.push(` client-address=${p.clientAddress} \\`)
if (p.clientDns) lines.push(` client-dns=${p.clientDns} \\`)
if (p.clientEndpoint) lines.push(` client-endpoint=${p.clientEndpoint} \\`)
if (p.comment) lines.push(` comment="${p.comment.replace(/"/g, '\\"')}" \\`)
if (lines[lines.length - 1]?.endsWith(" \\")) {
lines[lines.length - 1] = lines[lines.length - 1]!.slice(0, -2)
}
lines.push(``)
}
return lines.join("\n")
}
+214
View File
@@ -0,0 +1,214 @@
import { eq } from "drizzle-orm"
import { db } from "../db/index.js"
import { servers } from "../db/schema.js"
import { MikrotikClient } from "./mikrotik.js"
import type { WgIfaceDto, WgPeerDto } from "@mmapp/contracts/wireguard"
type ServerRow = typeof servers.$inferSelect
interface RosWireGuard {
".id"?: string
name?: string
"listen-port"?: string
mtu?: string
"public-key"?: string
"private-key"?: string
running?: string
disabled?: string
comment?: string
}
interface RosWireGuardPeer {
".id"?: string
interface?: string
name?: string
"public-key"?: string
"endpoint-address"?: string
"endpoint-port"?: string
"allowed-address"?: string
"last-handshake"?: string
rx?: string
tx?: string
disabled?: string
comment?: string
"persistent-keepalive"?: string
"client-address"?: string
"client-dns"?: string
"client-endpoint"?: string
}
interface RosIpAddress {
".id"?: string
address?: string
interface?: string
disabled?: string
}
function parseBytes(v: string | undefined): number | undefined {
if (v == null || v === "") return undefined
const n = Number.parseInt(v, 10)
return Number.isFinite(n) ? n : undefined
}
function mapPeer(p: RosWireGuardPeer, idx: number): WgPeerDto {
const rosId = String(p[".id"] ?? `peer-${idx}`)
const allowed = (p["allowed-address"] ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean)
const epAddr = (p["endpoint-address"] ?? "").trim()
const epPort = (p["endpoint-port"] ?? "").trim()
const endpoint = epAddr ? (epPort ? `${epAddr}:${epPort}` : epAddr) : undefined
const ka = p["persistent-keepalive"]
? Number.parseInt(p["persistent-keepalive"], 10)
: undefined
return {
id: rosId,
rosId,
publicKey: p["public-key"] ?? "",
allowedIps: allowed,
endpoint,
latestHandshake: p["last-handshake"]?.trim() || undefined,
transferRx: parseBytes(p.rx),
transferTx: parseBytes(p.tx),
persistentKeepalive: Number.isFinite(ka) ? ka : undefined,
persistent: Number.isFinite(ka) && (ka as number) > 0,
comment: p.comment ?? undefined,
disabled: p.disabled === "true" || p.disabled === "yes",
name: p.name,
clientAddress: p["client-address"],
clientDns: p["client-dns"],
clientEndpoint: p["client-endpoint"],
}
}
function mapIface(
server: ServerRow,
w: RosWireGuard,
peers: WgPeerDto[],
address: string | undefined,
includePrivateKey: boolean,
): WgIfaceDto {
const rosId = String(w[".id"] ?? w.name ?? "wg")
const name = (w.name ?? "").trim() || rosId
const disabled = w.disabled === "true" || w.disabled === "yes"
const running = w.running === "true" || w.running === "yes"
return {
id: `${server.id}:${rosId}`,
rosId,
name,
serverId: String(server.id),
serverName: String(server.name ?? "").trim() || String(server.host ?? server.id),
serverCountry: server.country ?? undefined,
listenPort: Number.parseInt(w["listen-port"] ?? "13231", 10) || 13231,
mtu: Number.parseInt(w.mtu ?? "1420", 10) || 1420,
publicKey: w["public-key"] || undefined,
privateKey: includePrivateKey ? w["private-key"] || undefined : undefined,
address,
peers,
comment: w.comment ?? "",
enabled: !disabled,
status: disabled ? "down" : running ? "up" : "down",
}
}
async function fetchForServer(
server: ServerRow,
includePrivateKey: boolean,
): Promise<WgIfaceDto[]> {
const client = MikrotikClient.fromServer(server)
const [ifacesRaw, peersRaw, addrsRaw] = await Promise.all([
client.get<RosWireGuard[]>("/interface/wireguard"),
client.get<RosWireGuardPeer[]>("/interface/wireguard/peers"),
client.get<RosIpAddress[]>("/ip/address").catch(() => [] as RosIpAddress[]),
])
const peersByIface = new Map<string, WgPeerDto[]>()
peersRaw.forEach((p, idx) => {
const ifaceName = (p.interface ?? "").trim()
if (!ifaceName) return
const list = peersByIface.get(ifaceName) ?? []
list.push(mapPeer(p, idx))
peersByIface.set(ifaceName, list)
})
const addrByIface = new Map<string, string>()
for (const a of addrsRaw) {
if (a.disabled === "true" || a.disabled === "yes") continue
const iface = (a.interface ?? "").trim()
const addr = (a.address ?? "").trim()
if (iface && addr && !addrByIface.has(iface)) addrByIface.set(iface, addr)
}
return ifacesRaw.map((w) => {
const name = (w.name ?? "").trim()
return mapIface(
server,
w,
peersByIface.get(name) ?? [],
addrByIface.get(name),
includePrivateKey,
)
})
}
export type WgListResult = {
interfaces: WgIfaceDto[]
failures: Array<{ serverId: string; serverName?: string; error: string }>
}
export async function listWireGuardInterfaces(opts?: {
serverId?: string
includePrivateKey?: boolean
}): Promise<WgListResult> {
const includePrivateKey = opts?.includePrivateKey === true
let serverRows: ServerRow[]
if (opts?.serverId) {
const id = Number.parseInt(String(opts.serverId), 10)
if (!Number.isFinite(id)) {
return { interfaces: [], failures: [{ serverId: String(opts.serverId), error: "Некорректный serverId" }] }
}
const row = db.select().from(servers).where(eq(servers.id, id)).limit(1).all()[0]
serverRows = row ? [row] : []
} else {
serverRows = db.select().from(servers).where(eq(servers.enabled, true)).all()
}
const failures: WgListResult["failures"] = []
const results = await Promise.all(
serverRows.map(async (server) => {
try {
return await fetchForServer(server, includePrivateKey)
} catch (e) {
failures.push({
serverId: String(server.id),
serverName: server.name ?? undefined,
error: e instanceof Error ? e.message : String(e),
})
return [] as WgIfaceDto[]
}
}),
)
return { interfaces: results.flat(), failures }
}
export async function countWireGuardInterfaces(): Promise<number> {
try {
const result = await Promise.race([
listWireGuardInterfaces({ includePrivateKey: false }),
new Promise<null>((resolve) => setTimeout(() => resolve(null), 8_000)),
])
if (!result) return 0
return result.interfaces.length
} catch {
return 0
}
}
export function getEnabledServerById(serverId: string | number): ServerRow | null {
const id = typeof serverId === "number" ? serverId : Number.parseInt(String(serverId), 10)
if (!Number.isFinite(id)) return null
return db.select().from(servers).where(eq(servers.id, id)).limit(1).all()[0] ?? null
}
export { type RosWireGuard, type RosWireGuardPeer }