Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6123660346 | ||
|
|
b680f882cc | ||
|
|
5e0c16e808 | ||
|
|
66509b26bd | ||
|
|
15ad53af1f |
@@ -17,13 +17,14 @@ import {
|
||||
import {
|
||||
BoxIcon, PlayIcon, StopCircleIcon, SearchIcon,
|
||||
MoreHorizontalIcon, Trash2Icon, PencilIcon, PowerIcon,
|
||||
CodeXmlIcon, CopyIcon, CheckIcon, ActivityIcon, ServerIcon,
|
||||
CodeXmlIcon, ActivityIcon, ServerIcon,
|
||||
TerminalIcon, AlertCircleIcon,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||
SheetDescription, SheetFooter, SheetClose,
|
||||
} from "@/components/ui/sheet"
|
||||
import { CodeExportSheet } from "@/components/reui-kit/code-export-sheet"
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -104,57 +105,23 @@ function generateContainerRsc(c: RouterContainer): string {
|
||||
function ExportSheet({ open, container, onClose }: {
|
||||
open: boolean; container: RouterContainer | null; onClose: () => void
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const code = useMemo(() => container ? generateContainerRsc(container) : "", [container])
|
||||
|
||||
function handleCopy() {
|
||||
navigator.clipboard.writeText(code).then(() => {
|
||||
setCopied(true); setTimeout(() => setCopied(false), 2000)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={(v) => { if (!v) onClose() }}>
|
||||
<SheetContent className="flex flex-col overflow-hidden p-0 gap-0 sm:max-w-2xl">
|
||||
<SheetHeader className="shrink-0 px-6 pt-5 pb-4 border-b">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<SheetTitle>Экспорт Container</SheetTitle>
|
||||
<SheetDescription>RouterOS 7.4+ · /container · /interface/veth</SheetDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="shrink-0" onClick={handleCopy}>
|
||||
{copied ? <><CheckIcon className="size-3.5 text-emerald-500" />Скопировано</> : <><CopyIcon className="size-3.5" />Копировать</>}
|
||||
</Button>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<pre className="px-6 py-5 text-[12px] font-mono leading-relaxed text-foreground/85 whitespace-pre select-all">
|
||||
{code.split("\n").map((line, i) => {
|
||||
const isComment = line.startsWith("#")
|
||||
const isCmd = /^\//.test(line.trimStart())
|
||||
const isParam = /^\s+[a-z]/.test(line)
|
||||
return (
|
||||
<span key={i} className={
|
||||
isComment ? "text-muted-foreground"
|
||||
: isCmd ? "text-sky-400"
|
||||
: isParam ? "text-violet-300"
|
||||
: "text-foreground"
|
||||
}>
|
||||
{line}{"\n"}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</pre>
|
||||
</div>
|
||||
<SheetFooter className="shrink-0 px-6 py-4 border-t flex-row gap-2">
|
||||
<SheetClose render={<Button variant="outline" className="flex-1" />}>Закрыть</SheetClose>
|
||||
<Button className="flex-1" onClick={handleCopy}>
|
||||
{copied ? <CheckIcon className="size-4" /> : <CopyIcon className="size-4" />}
|
||||
{copied ? "Скопировано" : "Копировать .rsc"}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<CodeExportSheet
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="Экспорт Container"
|
||||
description="RouterOS 7.4+ · /container · /interface/veth"
|
||||
formats={[
|
||||
{
|
||||
id: "rsc",
|
||||
label: "MikroTik .rsc",
|
||||
filename: `${container?.name ?? "container"}.rsc`,
|
||||
code,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import Link from "next/link"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { FormToggle } from "@/components/form-kit"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { Frame, FramePanel } from "@/components/reui/frame"
|
||||
import { IconTile } from "@/components/reui/icon-tile"
|
||||
@@ -104,7 +104,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "traffic") {
|
||||
const t = snap as TrafficRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
{t.skipped ? (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">Прогон пропущен: предыдущий сбор трафика ещё выполнялся.</p>
|
||||
) : null}
|
||||
@@ -126,7 +126,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "uptime_resources") {
|
||||
const u = snap as ResourcesRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
{u.skipped ? (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">Прогон пропущен: сбор ресурсов уже выполняется.</p>
|
||||
) : null}
|
||||
@@ -148,7 +148,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "servers_rest_ping") {
|
||||
const s = snap as ServersRestPingRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
{s.skipped ? (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">Прогон пропущен: предыдущая проверка API ещё выполнялась.</p>
|
||||
) : null}
|
||||
@@ -171,7 +171,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "uptime_ping") {
|
||||
const p = snap as PingRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
{p.skipped ? (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">Прогон пропущен: сбор ping уже выполняется.</p>
|
||||
) : null}
|
||||
@@ -196,7 +196,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "uptime_speed") {
|
||||
const s = snap as SpeedScheduledRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Прогоны speed на <span className="font-mono tabular-nums">{new Date(s.sampledAt).toLocaleString("ru-RU")}</span> — по очереди для каждой включённой пробы
|
||||
</p>
|
||||
@@ -209,7 +209,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "gre_bgp") {
|
||||
const g = snap as GreBgpSnapshotRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
{g.skipped ? (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">Прогон пропущен: предыдущий сбор GRE/BGP ещё выполнялся.</p>
|
||||
) : null}
|
||||
@@ -235,7 +235,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
</div>
|
||||
</dl>
|
||||
{g.errors?.length ? (
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200 space-y-1">
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200 flex flex-col gap-1">
|
||||
{g.errors.map((e, i) => (
|
||||
<p key={i} className="break-words">
|
||||
{e}
|
||||
@@ -249,7 +249,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "internet_path") {
|
||||
const p = snap as InternetPathRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Снимок internet-path на{" "}
|
||||
<span className="font-mono tabular-nums">{new Date(p.sampledAt).toLocaleString("ru-RU")}</span>
|
||||
@@ -276,7 +276,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "certificates_renew") {
|
||||
const c = snap as CertificatesRenewRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
{c.skipped ? (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">Прогон пропущен: предыдущая проверка ещё выполнялась или задача отключена.</p>
|
||||
) : null}
|
||||
@@ -299,7 +299,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
</div>
|
||||
</dl>
|
||||
{c.errors.length ? (
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200 space-y-1">
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200 flex flex-col gap-1">
|
||||
{c.errors.map((e, i) => (
|
||||
<p key={i} className="break-words">{e}</p>
|
||||
))}
|
||||
@@ -311,7 +311,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "backups") {
|
||||
const b = snap as BackupsRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
<dl className="grid grid-cols-2 gap-3 text-xs sm:grid-cols-4">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">Слот расписания</dt>
|
||||
@@ -331,7 +331,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
</div>
|
||||
</dl>
|
||||
{b.errors?.length ? (
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200 space-y-1">
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200 flex flex-col gap-1">
|
||||
{b.errors.map((e, i) => (
|
||||
<p key={i} className="break-words">{e}</p>
|
||||
))}
|
||||
@@ -343,7 +343,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
if (snap.job === "alert_engine") {
|
||||
const a = snap as AlertEngineRunSnapshot
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Снимок на{" "}
|
||||
<span className="font-mono tabular-nums">{new Date(a.sampledAt).toLocaleString("ru-RU")}</span>
|
||||
@@ -370,7 +370,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
{a.errors?.length ? (
|
||||
<Alert variant="destructive" className="py-2">
|
||||
<AlertCircleIcon />
|
||||
<AlertDescription className="space-y-1 text-xs">
|
||||
<AlertDescription className="flex flex-col gap-1 text-xs">
|
||||
{a.errors.map((e, i) => (
|
||||
<p key={i} className="break-words">
|
||||
{e}
|
||||
@@ -380,7 +380,7 @@ function SnapshotTables({ snap }: { snap: SchedulerRunSnapshot }) {
|
||||
</Alert>
|
||||
) : null}
|
||||
{a.ruleDiag && a.ruleDiag.length > 0 ? (
|
||||
<div className="rounded-md border border-border bg-muted/20 px-3 py-2 space-y-2">
|
||||
<div className="rounded-md border border-border bg-muted/20 px-3 py-2 flex flex-col gap-2">
|
||||
<p className="text-[11px] font-medium text-muted-foreground">По правилам (почему не ушло в Telegram)</p>
|
||||
<DataPageCard className="border-0 shadow-none bg-transparent">
|
||||
<AlertEngineRuleDiagGrid ruleDiag={a.ruleDiag} />
|
||||
@@ -398,39 +398,39 @@ function RunRowDetail({ r }: { r: SchedulerRunRowDto }) {
|
||||
const jobDesc = SCHEDULER_JOB_DESCRIPTIONS[r.jobKey] ?? "—"
|
||||
const snapshot = useMemo(() => parseSchedulerRunSnapshot(r.resultJson ?? null), [r.resultJson])
|
||||
return (
|
||||
<div className="space-y-4 text-sm">
|
||||
<div className="flex flex-col gap-4 text-sm">
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-3">
|
||||
<div className="space-y-1">
|
||||
<div className="flex flex-col gap-1">
|
||||
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">ID записи</dt>
|
||||
<dd className="font-mono text-xs break-all bg-muted/60 rounded-md px-2 py-1.5 border border-border">{r.id}</dd>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="flex flex-col gap-1">
|
||||
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Ключ задачи</dt>
|
||||
<dd className="font-mono text-xs">{r.jobKey}</dd>
|
||||
</div>
|
||||
<div className="sm:col-span-2 space-y-1">
|
||||
<div className="sm:col-span-2 flex flex-col gap-1">
|
||||
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Название и назначение</dt>
|
||||
<dd>
|
||||
<span className="font-medium">{jobTitle}</span>
|
||||
<p className="text-xs text-muted-foreground mt-1 leading-relaxed">{jobDesc}</p>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="flex flex-col gap-1">
|
||||
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Старт</dt>
|
||||
<dd className="tabular-nums text-xs">{new Date(r.startedAt).toLocaleString("ru-RU")}</dd>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="flex flex-col gap-1">
|
||||
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Завершение</dt>
|
||||
<dd className="tabular-nums text-xs">{new Date(r.finishedAt).toLocaleString("ru-RU")}</dd>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="flex flex-col gap-1">
|
||||
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Длительность</dt>
|
||||
<dd className="tabular-nums">
|
||||
<span className="font-mono">{r.durationMs}</span> мс
|
||||
<span className="text-muted-foreground text-xs ml-2">({fmtMs(r.durationMs)})</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="flex flex-col gap-1">
|
||||
<dt className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Результат</dt>
|
||||
<dd>
|
||||
<Badge
|
||||
@@ -447,7 +447,7 @@ function RunRowDetail({ r }: { r: SchedulerRunRowDto }) {
|
||||
</div>
|
||||
</dl>
|
||||
{r.error ? (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="text-xs font-medium text-destructive">Текст ошибки</p>
|
||||
<pre
|
||||
className="text-xs font-mono whitespace-pre-wrap break-words rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 max-h-48 overflow-y-auto"
|
||||
@@ -461,7 +461,7 @@ function RunRowDetail({ r }: { r: SchedulerRunRowDto }) {
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Результаты измерений</p>
|
||||
{snapshot ? (
|
||||
<SnapshotTables snap={snapshot} />
|
||||
@@ -1090,7 +1090,7 @@ export default function DataCollectionPage() {
|
||||
</div>
|
||||
<DataCollectionSchedulerDataGrid rows={schedulerGridRows} />
|
||||
<Separator />
|
||||
<div className="space-y-3 px-5 py-4">
|
||||
<div className="flex flex-col gap-3 px-5 py-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground mb-1.5">Хранение сэмплов трафика (дней)</p>
|
||||
@@ -1142,7 +1142,7 @@ export default function DataCollectionPage() {
|
||||
{schedulerSaveBusy ? <LoaderCircleIcon className="size-4 animate-spin mr-2" /> : null}
|
||||
Сохранить настройки планировщика
|
||||
</Button>
|
||||
<div className="text-xs text-muted-foreground space-y-0.5 pt-1 border-t border-border/60">
|
||||
<div className="text-xs text-muted-foreground flex flex-col gap-0.5 pt-1 border-t border-border/60">
|
||||
<p>
|
||||
Трафик — последний сбор:{" "}
|
||||
{trafficCollector?.lastCollectedAt
|
||||
|
||||
+20
-89
@@ -35,6 +35,7 @@ import {
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
|
||||
import { toast } from "sonner"
|
||||
import { CodeExportSheet } from "@/components/reui-kit/code-export-sheet"
|
||||
|
||||
// ── helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -754,13 +755,11 @@ function PreviewModal({ open, serverId, rulesets, onClose, serversList, tunnelsL
|
||||
tunnelsList: GreTunnel[]
|
||||
recRoutesByServer: Record<string, RecursiveRouteLite[]>
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
const singleRuleset = useMemo(
|
||||
() => rulesets.filter(r => r.serverId === serverId),
|
||||
[rulesets, serverId],
|
||||
)
|
||||
const server = serversList.find(s => s.id === serverId)
|
||||
const server = serversList.find(s => s.id === serverId)
|
||||
const totalRules = singleRuleset.reduce((s, r) => s + r.rules.length, 0)
|
||||
|
||||
const config = useMemo(
|
||||
@@ -771,93 +770,25 @@ function PreviewModal({ open, serverId, rulesets, onClose, serversList, tunnelsL
|
||||
[open, singleRuleset, serversList, tunnelsList, recRoutesByServer],
|
||||
)
|
||||
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText(config).catch(() => {})
|
||||
setCopied(true); setTimeout(() => setCopied(false), 2000)
|
||||
}
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onClose} />
|
||||
<div className="relative z-10 w-full max-w-2xl mx-4 bg-card rounded-xl border shadow-2xl flex flex-col max-h-[85vh]">
|
||||
|
||||
{/* header */}
|
||||
<div className="flex items-center justify-between px-5 py-3.5 border-b shrink-0">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<FileCodeIcon className="size-4 text-muted-foreground" />
|
||||
<span className="text-sm font-semibold">RouterOS config</span>
|
||||
{server && (
|
||||
<span className="flex items-center gap-1 text-[11px] text-muted-foreground bg-muted px-2 py-0.5 rounded-full">
|
||||
<Flag code={server.country} size={11} />
|
||||
<span className="font-mono">{server.name}</span>
|
||||
<span>· {totalRules} правил</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onClose}><XIcon className="size-4" /></Button>
|
||||
</div>
|
||||
|
||||
{/* code */}
|
||||
<div className="flex-1 overflow-y-auto p-4 min-h-0">
|
||||
<pre className="text-xs font-mono bg-[#0d1117] rounded-lg p-4 leading-[1.6] whitespace-pre overflow-x-auto">
|
||||
{config.split("\n").map((line, i) => {
|
||||
const trimmed = line.trimStart()
|
||||
const cls =
|
||||
// section dividers
|
||||
trimmed.startsWith("# ═") || trimmed.startsWith("# ─")
|
||||
? "text-[#444c56]" :
|
||||
// inline comments inside rule body
|
||||
trimmed.startsWith("# ")
|
||||
? "text-[#8b949e]" :
|
||||
// RouterOS scripting keywords
|
||||
trimmed.startsWith(":local") || trimmed.startsWith(":log") || trimmed.startsWith(":foreach")
|
||||
? "text-[#d2a8ff]" :
|
||||
// :if identity branch / closing brace
|
||||
trimmed.startsWith(":if") || (trimmed === "}" && line.length < 3)
|
||||
? "text-[#ff7b72] font-semibold" :
|
||||
// filter rule add command
|
||||
trimmed.startsWith("/routing filter rule")
|
||||
? "text-[#79c0ff]" :
|
||||
// rule body: if/else if branches
|
||||
trimmed.startsWith("if (") || trimmed.startsWith("} else if")
|
||||
? "text-[#ff7b72]" :
|
||||
// rule body: blackhole action
|
||||
trimmed.startsWith("set type blackhole")
|
||||
? "text-[#ff7b72] font-semibold" :
|
||||
// rule body: set actions
|
||||
trimmed.startsWith("set gw") || trimmed.startsWith("set gateway") || trimmed.startsWith("set out-interface")
|
||||
? "text-[#a5d6ff]" :
|
||||
// rule body: accept / rule close
|
||||
trimmed.startsWith("accept") || trimmed === `}"` || trimmed.startsWith(`rule="`)
|
||||
? "text-[#79c0ff]" :
|
||||
// named params
|
||||
trimmed.match(/^(chain|comment|bgp-communities)=/)
|
||||
? "text-[#a5d6ff]" :
|
||||
"text-[#c9d1d9]"
|
||||
return <span key={i} className={cn("block", cls)}>{line || " "}</span>
|
||||
})}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
{/* footer */}
|
||||
<div className="px-5 py-4 border-t bg-muted/30 shrink-0 space-y-3">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-1 text-xs text-muted-foreground">
|
||||
<p>1. Скопируйте скрипт в буфер обмена</p>
|
||||
<p>3. Вставьте в терминал и нажмите Enter</p>
|
||||
<p>2. Подключитесь к любому MikroTik (SSH / Winbox)</p>
|
||||
<p>4. Скрипт сам определит свои правила по identity</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={onClose} className="flex-1">Закрыть</Button>
|
||||
<Button onClick={handleCopy} className="flex-1">
|
||||
{copied ? <CheckIcon className="size-4" /> : <CopyIcon className="size-4" />}
|
||||
{copied ? "Скопировано!" : "Скопировать"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<CodeExportSheet
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="RouterOS config"
|
||||
description={
|
||||
server
|
||||
? `${server.name} · ${totalRules} правил`
|
||||
: "Экспорт правил фильтрации"
|
||||
}
|
||||
formats={[
|
||||
{
|
||||
id: "rsc",
|
||||
label: "RouterOS",
|
||||
filename: `filters-${server?.name ?? "server"}.rsc`,
|
||||
code: config,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -34,12 +34,13 @@ import { cn } from "@/lib/utils"
|
||||
import {
|
||||
PlusIcon, SearchIcon, ShieldIcon, ShieldOffIcon,
|
||||
ListFilterIcon, ArrowRightLeftIcon, WrenchIcon, LayersIcon,
|
||||
MoreHorizontalIcon, PencilIcon, Trash2Icon, CopyIcon, CodeXmlIcon,
|
||||
CheckIcon, PowerIcon, CheckCircleIcon,
|
||||
MoreHorizontalIcon, PencilIcon, Trash2Icon, CodeXmlIcon,
|
||||
PowerIcon, CheckCircleIcon,
|
||||
PlayIcon, SquareIcon, RotateCcwIcon, ZapIcon,
|
||||
CheckCircle2Icon, XCircleIcon, MinusCircleIcon, SkipForwardIcon,
|
||||
SlidersHorizontalIcon,
|
||||
} from "lucide-react"
|
||||
import { CodeExportSheet } from "@/components/reui-kit/code-export-sheet"
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -602,68 +603,28 @@ function RuleSheet({ open, onClose, initialRule, chainGroup }: {
|
||||
function ExportSheet({ open, onClose, rules }: {
|
||||
open: boolean; onClose: () => void; rules: FirewallRule[]
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
// Derived from open — new timestamp each time modal opens, undefined when closed
|
||||
const timestamp = useMemo(
|
||||
() => open ? new Date().toLocaleString("ru") : undefined,
|
||||
[open],
|
||||
[open],
|
||||
)
|
||||
|
||||
const code = useMemo(() => generateRsc(rules, timestamp), [rules, timestamp])
|
||||
|
||||
function handleCopy() {
|
||||
const full = generateRsc(rules, new Date().toLocaleString("ru"))
|
||||
navigator.clipboard.writeText(full).then(() => {
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={(v) => { if (!v) onClose() }}>
|
||||
<SheetContent className="flex flex-col overflow-hidden p-0 gap-0 sm:max-w-2xl">
|
||||
<SheetHeader className="shrink-0 px-6 pt-5 pb-4 border-b">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<SheetTitle>Экспорт Firewall</SheetTitle>
|
||||
<SheetDescription>RouterOS .rsc · /ip firewall filter, nat, mangle</SheetDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="shrink-0" onClick={handleCopy}>
|
||||
{copied
|
||||
? <><CheckIcon className="size-3.5 text-emerald-500" />Скопировано</>
|
||||
: <><CopyIcon className="size-3.5" />Копировать</>}
|
||||
</Button>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<pre className="px-6 py-5 text-[12px] font-mono leading-relaxed text-foreground/85 whitespace-pre select-all">
|
||||
{code.split("\n").map((line, i) => {
|
||||
const isComment = line.startsWith("#")
|
||||
const isSection = isComment && line.includes("──")
|
||||
const isKey = /^\s+[a-z]/.test(line)
|
||||
return (
|
||||
<span key={i} className={
|
||||
isSection ? "text-muted-foreground/50"
|
||||
: isComment ? "text-muted-foreground"
|
||||
: isKey ? "text-sky-400/90"
|
||||
: "text-foreground"
|
||||
}>
|
||||
{line}{"\n"}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</pre>
|
||||
</div>
|
||||
<SheetFooter className="shrink-0 px-6 py-4 border-t flex-row gap-2">
|
||||
<SheetClose render={<Button variant="outline" className="flex-1" />}>Закрыть</SheetClose>
|
||||
<Button className="flex-1" onClick={handleCopy}>
|
||||
{copied ? <CheckIcon className="size-4" /> : <CopyIcon className="size-4" />}
|
||||
{copied ? "Скопировано" : "Копировать .rsc"}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<CodeExportSheet
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="Экспорт Firewall"
|
||||
description="RouterOS .rsc · /ip firewall filter, nat, mangle"
|
||||
formats={[
|
||||
{
|
||||
id: "rsc",
|
||||
label: "MikroTik .rsc",
|
||||
filename: `firewall-${new Date().toISOString().slice(0, 10)}.rsc`,
|
||||
code,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+47
-85
@@ -31,9 +31,10 @@ import {
|
||||
PlusIcon, RefreshCwIcon, MoreHorizontalIcon,
|
||||
LockIcon, LockOpenIcon, ShieldCheckIcon, NetworkIcon,
|
||||
EyeIcon, EyeOffIcon, ChevronDownIcon, ChevronRightIcon,
|
||||
CodeXmlIcon, PencilIcon, PowerIcon, Trash2Icon, CopyIcon, CheckIcon,
|
||||
CodeXmlIcon, PencilIcon, PowerIcon, Trash2Icon,
|
||||
DatabaseIcon,
|
||||
} from "lucide-react"
|
||||
import { CodeExportSheet } from "@/components/reui-kit/code-export-sheet"
|
||||
|
||||
// ─── label maps ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -244,7 +245,6 @@ export default function GrePage() {
|
||||
const [tunnelOpen, setTunnelOpen] = useState(false)
|
||||
const [poolOpen, setPoolOpen] = useState(false)
|
||||
const [codePreviewTunnel, setCodePreviewTunnel] = useState<GreTunnel | null>(null)
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
const [tForm, setTForm] = useState(defaultTunnelForm)
|
||||
const [pForm, setPForm] = useState(defaultPoolForm)
|
||||
@@ -366,13 +366,10 @@ export default function GrePage() {
|
||||
{ value: "plain", label: "Без IPsec", count: displayTunnels.length - ipsecCount },
|
||||
]
|
||||
|
||||
function handleCopy(code: string) {
|
||||
navigator.clipboard.writeText(code).then(() => {
|
||||
setCopied(true)
|
||||
toast.success("Команды скопированы")
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
})
|
||||
}
|
||||
const greExportCode = useMemo(
|
||||
() => (codePreviewTunnel ? generateRosCommands(codePreviewTunnel, serverById) : ""),
|
||||
[codePreviewTunnel, serverById],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
@@ -551,82 +548,47 @@ export default function GrePage() {
|
||||
</div>
|
||||
|
||||
{/* ══ Sheet: Code Preview ════════════════════════════════════════════════ */}
|
||||
<Sheet open={!!codePreviewTunnel} onOpenChange={(open) => { if (!open) setCodePreviewTunnel(null) }}>
|
||||
<SheetContent side="right" className="w-full sm:max-w-2xl flex flex-col gap-0 p-0">
|
||||
{codePreviewTunnel && (() => {
|
||||
const code = generateRosCommands(codePreviewTunnel, serverById)
|
||||
return (
|
||||
<>
|
||||
<SheetHeader className="px-6 pt-6 pb-4 border-b shrink-0">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<SheetTitle className="font-mono">{codePreviewTunnel.name}</SheetTitle>
|
||||
<SheetDescription>Команды RouterOS 7.20+ для создания туннеля</SheetDescription>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline" size="sm"
|
||||
className="shrink-0 gap-1.5"
|
||||
onClick={() => handleCopy(code)}
|
||||
>
|
||||
{copied
|
||||
? <><CheckIcon className="size-3.5 text-emerald-500" /> Скопировано</>
|
||||
: <><CopyIcon className="size-3.5" /> Копировать</>}
|
||||
</Button>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{/* meta strip */}
|
||||
<div className="flex flex-wrap gap-3 px-6 py-3 border-b bg-muted/30 text-xs">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className={`size-1.5 rounded-full ${STATUS_MAP[codePreviewTunnel.status].dot}`} />
|
||||
{STATUS_MAP[codePreviewTunnel.status].label}
|
||||
</span>
|
||||
<span className="text-muted-foreground">·</span>
|
||||
<span>{serverById[codePreviewTunnel.serverId]?.name}</span>
|
||||
<span className="text-muted-foreground">·</span>
|
||||
<span className="font-mono">{codePreviewTunnel.localAddress === "0.0.0.0" ? "авто" : codePreviewTunnel.localAddress} → {codePreviewTunnel.remoteAddress}</span>
|
||||
{codePreviewTunnel.ipsec && (
|
||||
<>
|
||||
<span className="text-muted-foreground">·</span>
|
||||
<span className="flex items-center gap-1 text-emerald-400"><LockIcon className="size-3" /> IPsec {IKE_LABELS[codePreviewTunnel.ipsec.ikeVersion]}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* code block */}
|
||||
<pre className="px-6 py-5 text-xs font-mono leading-relaxed text-foreground/90 whitespace-pre overflow-x-auto select-all">
|
||||
{code.split("\n").map((line, i) => {
|
||||
const isComment = line.startsWith("#")
|
||||
const isSection = isComment && line.includes("──")
|
||||
const isKey = /^\s+[a-z]/.test(line)
|
||||
return (
|
||||
<span key={i} className={
|
||||
isSection ? "text-muted-foreground/60"
|
||||
: isComment ? "text-muted-foreground"
|
||||
: isKey ? "text-sky-400/90"
|
||||
: "text-foreground"
|
||||
}>
|
||||
{line}
|
||||
{"\n"}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<SheetFooter className="px-6 py-4 border-t shrink-0 flex-row gap-2">
|
||||
<SheetClose render={<Button variant="outline" className="flex-1" />}>Закрыть</SheetClose>
|
||||
<Button className="flex-1 gap-1.5" onClick={() => handleCopy(code)}>
|
||||
{copied ? <CheckIcon className="size-4" /> : <CopyIcon className="size-4" />}
|
||||
{copied ? "Скопировано" : "Копировать команды"}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</>
|
||||
)
|
||||
})()}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<CodeExportSheet
|
||||
open={!!codePreviewTunnel}
|
||||
onClose={() => setCodePreviewTunnel(null)}
|
||||
title={codePreviewTunnel?.name ?? "GRE"}
|
||||
description="Команды RouterOS 7.20+ для создания туннеля"
|
||||
formats={[
|
||||
{
|
||||
id: "rsc",
|
||||
label: "RouterOS",
|
||||
filename: `${codePreviewTunnel?.name ?? "gre"}.rsc`,
|
||||
code: greExportCode,
|
||||
},
|
||||
]}
|
||||
beforeCode={
|
||||
codePreviewTunnel ? (
|
||||
<div className="flex flex-wrap gap-3 text-xs shrink-0">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className={`size-1.5 rounded-full ${STATUS_MAP[codePreviewTunnel.status].dot}`} />
|
||||
{STATUS_MAP[codePreviewTunnel.status].label}
|
||||
</span>
|
||||
<span className="text-muted-foreground">·</span>
|
||||
<span>{serverById[codePreviewTunnel.serverId]?.name}</span>
|
||||
<span className="text-muted-foreground">·</span>
|
||||
<span className="font-mono">
|
||||
{codePreviewTunnel.localAddress === "0.0.0.0" ? "авто" : codePreviewTunnel.localAddress}
|
||||
{" → "}
|
||||
{codePreviewTunnel.remoteAddress}
|
||||
</span>
|
||||
{codePreviewTunnel.ipsec ? (
|
||||
<>
|
||||
<span className="text-muted-foreground">·</span>
|
||||
<span className="flex items-center gap-1 text-success">
|
||||
<LockIcon className="size-3" />
|
||||
IPsec {IKE_LABELS[codePreviewTunnel.ipsec.ikeVersion]}
|
||||
</span>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
{/* ══ Sheet: Add Tunnel ══════════════════════════════════════════════════ */}
|
||||
<Sheet open={tunnelOpen} onOpenChange={setTunnelOpen}>
|
||||
|
||||
@@ -16,6 +16,17 @@ import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetFooter,
|
||||
} from "@/components/ui/sheet"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Flag } from "@/components/flag"
|
||||
import { StatusDot } from "@/components/status-dot"
|
||||
import { servers } from "@/lib/data"
|
||||
@@ -152,7 +163,7 @@ const PERM_OPTS: { v: PermLevel; label: string }[] = [
|
||||
const PERM_COLOR: Record<PermLevel, string> = {
|
||||
none: "bg-muted text-muted-foreground",
|
||||
read: "bg-sky-500/10 text-sky-600 dark:text-sky-400",
|
||||
write: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",
|
||||
write: "bg-success/10 text-success",
|
||||
}
|
||||
|
||||
const SECTIONS_NAV = ["Общие", "EvoBGP", "Уведомления", "Пользователи", "API-ключи", "Безопасность"] as const
|
||||
@@ -188,8 +199,8 @@ function PermPills({ value, onChange, disabled }: { value: PermLevel; onChange:
|
||||
"px-2 text-[11px] font-medium transition-colors",
|
||||
i < PERM_OPTS.length - 1 && "border-r border-input",
|
||||
value === o.v
|
||||
? o.v === "write" ? "bg-emerald-600 text-white dark:bg-emerald-500"
|
||||
: o.v === "read" ? "bg-sky-600 text-white dark:bg-sky-500"
|
||||
? o.v === "write" ? "bg-success text-white"
|
||||
: o.v === "read" ? "bg-info text-white"
|
||||
: "bg-muted-foreground/70 text-white"
|
||||
: "text-muted-foreground hover:bg-muted",
|
||||
)}
|
||||
@@ -685,68 +696,79 @@ function UserSheet({ open, user, onSave, onClose }: {
|
||||
// ─── delete confirm ───────────────────────────────────────────────────────────
|
||||
|
||||
function DatabaseRestoreConfirm({
|
||||
open,
|
||||
filename,
|
||||
busy,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: {
|
||||
open: boolean
|
||||
filename: string
|
||||
busy?: boolean
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onCancel} />
|
||||
<div className="relative z-10 w-full max-w-sm mx-4 bg-card rounded-xl border shadow-2xl p-5 flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-9 rounded-full bg-destructive/10 flex items-center justify-center shrink-0">
|
||||
<AlertCircleIcon className="size-4 text-destructive" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-semibold">Восстановить базу приложения?</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5 break-all">{filename}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Текущие данные SQLite на бекенде будут полностью заменены содержимым файла. Рекомендуется сначала скачать
|
||||
актуальный бэкап.
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" className="flex-1" onClick={onCancel} disabled={busy}>Отмена</Button>
|
||||
<Button variant="destructive" className="flex-1" onClick={onConfirm} disabled={busy}>
|
||||
<AlertDialog open={open} onOpenChange={(v) => { if (!v && !busy) onCancel() }}>
|
||||
<AlertDialogContent size="default">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogMedia className="bg-destructive/10 text-destructive">
|
||||
<AlertCircleIcon />
|
||||
</AlertDialogMedia>
|
||||
<AlertDialogTitle>Восстановить базу приложения?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Файл: {filename}. Текущие данные SQLite на бекенде будут полностью заменены.
|
||||
Рекомендуется сначала скачать актуальный бэкап.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={busy} onClick={onCancel}>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
disabled={busy}
|
||||
onClick={onConfirm}
|
||||
>
|
||||
{busy ? <LoaderCircleIcon className="size-4 animate-spin" /> : null}
|
||||
{busy ? "Восстановление…" : "Восстановить"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
|
||||
function DeleteConfirm({ user, onConfirm, onCancel }: { user: User; onConfirm: () => void; onCancel: () => void }) {
|
||||
function DeleteConfirm({
|
||||
open,
|
||||
user,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: {
|
||||
open: boolean
|
||||
user: User
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onCancel} />
|
||||
<div className="relative z-10 w-full max-w-sm mx-4 bg-card rounded-xl border shadow-2xl p-5 flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-9 rounded-full bg-destructive/10 flex items-center justify-center shrink-0">
|
||||
<TrashIcon className="size-4 text-destructive" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-semibold">Удалить пользователя?</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">{user.name} · @{user.login}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Это действие нельзя отменить. Пользователь потеряет доступ немедленно.
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" className="flex-1" onClick={onCancel}>Отмена</Button>
|
||||
<Button variant="destructive" className="flex-1" onClick={onConfirm}>Удалить</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<AlertDialog open={open} onOpenChange={(v) => { if (!v) onCancel() }}>
|
||||
<AlertDialogContent size="default">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogMedia className="bg-destructive/10 text-destructive">
|
||||
<TrashIcon />
|
||||
</AlertDialogMedia>
|
||||
<AlertDialogTitle>Удалить пользователя?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{user.name} · @{user.login}. Это действие нельзя отменить.
|
||||
Пользователь потеряет доступ немедленно.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={onCancel}>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction variant="destructive" onClick={onConfirm}>
|
||||
Удалить
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -937,7 +959,7 @@ export default function SettingsPage() {
|
||||
|
||||
// ── Общие ──
|
||||
if (section === "Общие") return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
|
||||
{/* ── Источник данных ── */}
|
||||
<OpsPanel
|
||||
@@ -960,9 +982,7 @@ export default function SettingsPage() {
|
||||
"px-3 text-xs transition-colors border-input",
|
||||
i === 0 && "border-r",
|
||||
mode === v
|
||||
? v === "live"
|
||||
? "bg-emerald-600 text-white dark:bg-emerald-500"
|
||||
: "bg-primary text-primary-foreground"
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "text-muted-foreground hover:bg-muted",
|
||||
)}>
|
||||
{l}
|
||||
@@ -972,7 +992,7 @@ export default function SettingsPage() {
|
||||
</SettingRow>
|
||||
) : (
|
||||
<SettingRow label="Режим данных" description="В Docker-образе приложение работает только с живыми данными бекенда">
|
||||
<span className="inline-flex h-8 items-center rounded-md border border-input bg-emerald-600 px-3 text-xs text-white dark:bg-emerald-500">
|
||||
<span className="inline-flex h-8 items-center rounded-md border border-input bg-primary px-3 text-xs text-primary-foreground">
|
||||
Живые
|
||||
</span>
|
||||
</SettingRow>
|
||||
@@ -1173,7 +1193,7 @@ export default function SettingsPage() {
|
||||
|
||||
// ── EvoBGP ──
|
||||
if (section === "EvoBGP") return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
{(mode !== "live" || backendStatus !== true) && (
|
||||
<Frame dense className="w-full">
|
||||
<FramePanel className="px-4 py-4">
|
||||
@@ -1357,7 +1377,7 @@ export default function SettingsPage() {
|
||||
|
||||
// ── Уведомления ──
|
||||
if (section === "Уведомления") return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
<OpsPanel title="Каналы уведомлений" contentClassName="divide-y px-5">
|
||||
<SettingRow label="Email" description="Отправка уведомлений на admin@routerlists.io">
|
||||
<FormToggle checked={notifEmail} onChange={setNotifEmail} />
|
||||
@@ -1479,11 +1499,11 @@ export default function SettingsPage() {
|
||||
|
||||
// ── API-ключи ──
|
||||
if (section === "API-ключи") return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex justify-end">
|
||||
<Button size="sm"><PlusIcon className="size-4" />Создать ключ</Button>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
{apiKeys.map(k => (
|
||||
<Frame key={k.id} dense className="w-full">
|
||||
<FramePanel className="pt-4 pb-3 px-4">
|
||||
@@ -1546,7 +1566,7 @@ export default function SettingsPage() {
|
||||
|
||||
// ── Безопасность ──
|
||||
if (section === "Безопасность") return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
<OpsPanel title="Аутентификация" contentClassName="divide-y px-5">
|
||||
<SettingRow label="Двухфакторная аутентификация (MFA)"
|
||||
description="TOTP / Authenticator app для всех администраторов">
|
||||
@@ -1647,6 +1667,7 @@ export default function SettingsPage() {
|
||||
{/* delete confirm */}
|
||||
{dbRestoreFile && (
|
||||
<DatabaseRestoreConfirm
|
||||
open={!!dbRestoreFile}
|
||||
filename={dbRestoreFile.name}
|
||||
busy={dbRestoreBusy}
|
||||
onConfirm={() => { void handleSystemDatabaseRestoreConfirm() }}
|
||||
@@ -1658,6 +1679,7 @@ export default function SettingsPage() {
|
||||
)}
|
||||
{deleteTarget && (
|
||||
<DeleteConfirm
|
||||
open={!!deleteTarget}
|
||||
user={deleteTarget}
|
||||
onConfirm={() => { setUsers(p => p.filter(u => u.id !== deleteTarget.id)); setDeleteTarget(null) }}
|
||||
onCancel={() => setDeleteTarget(null)}
|
||||
|
||||
+147
-98
@@ -4,11 +4,30 @@ import { useState, useRef, useEffect, useCallback, useMemo } from "react"
|
||||
import { PageHeader } from "@/components/page-header"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { servers as mockServers } from "@/lib/data"
|
||||
import { Flag } from "@/components/flag"
|
||||
import type { ServerStatus } from "@/lib/data"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import {
|
||||
TrashIcon, RefreshCwIcon, CircleIcon, Loader2Icon,
|
||||
Frame,
|
||||
FrameFooter,
|
||||
FrameHeader,
|
||||
FramePanel,
|
||||
FrameTitle,
|
||||
} from "@/components/reui/frame"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import {
|
||||
ServerTileRail,
|
||||
type ServerTileItem,
|
||||
} from "@/components/server-tile-rail"
|
||||
import {
|
||||
TrashIcon, RefreshCwIcon, CircleIcon, Loader2Icon, ServerIcon,
|
||||
} from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
@@ -437,6 +456,7 @@ export default function TerminalPage() {
|
||||
const [liveServers, setLiveServers] = useState<TermServer[]>([])
|
||||
const [serversLoading, setServersLoading] = useState(false)
|
||||
const [refreshKey, setRefreshKey] = useState(0) // force terminal remount on reconnect
|
||||
const [railOpen, setRailOpen] = useState(false)
|
||||
|
||||
// Load servers from backend when in live mode
|
||||
useEffect(() => {
|
||||
@@ -492,6 +512,79 @@ export default function TerminalPage() {
|
||||
|
||||
const termKey = `${selectedUid}-${refreshKey}-${isLive ? "live" : "mock"}`
|
||||
|
||||
const railItems = useMemo<ServerTileItem[]>(() => {
|
||||
return termServers.map((s) => ({
|
||||
id: s.uid,
|
||||
name: s.name,
|
||||
country: s.country || undefined,
|
||||
status: (s.status ?? undefined) as ServerStatus | undefined,
|
||||
enabled: s.enabled,
|
||||
selectable: s.enabled && s.status !== "offline",
|
||||
title: [s.name, s.host].filter(Boolean).join(" · "),
|
||||
}))
|
||||
}, [termServers])
|
||||
|
||||
function handleSelectServer(id: string) {
|
||||
setSelectedUid(id)
|
||||
setRefreshKey((k) => k + 1)
|
||||
setRailOpen(false)
|
||||
}
|
||||
|
||||
const railHeaderRight = isLive
|
||||
? serversLoading
|
||||
? <Loader2Icon className="size-3.5 animate-spin text-muted-foreground" />
|
||||
: <Badge variant="success-light" size="xs">LIVE</Badge>
|
||||
: undefined
|
||||
|
||||
const rail = (
|
||||
<ServerTileRail
|
||||
items={railItems}
|
||||
selectedId={selected?.uid ?? selectedUid}
|
||||
onSelect={handleSelectServer}
|
||||
showAll={false}
|
||||
showCount={false}
|
||||
showType={false}
|
||||
headerRight={railHeaderRight}
|
||||
className="min-h-0 flex-1"
|
||||
/>
|
||||
)
|
||||
|
||||
function QuickCmds() {
|
||||
return (
|
||||
<Frame dense spacing="sm" className="min-h-0 shrink-0">
|
||||
<FramePanel className="flex max-h-56 flex-col gap-0 p-0">
|
||||
<FrameHeader className="border-b px-3 py-2">
|
||||
<FrameTitle className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Быстрые команды
|
||||
</FrameTitle>
|
||||
</FrameHeader>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="flex flex-col gap-0.5 p-1.5">
|
||||
{QUICK_CMDS.map(({ cmd, label }) => (
|
||||
<button
|
||||
key={cmd}
|
||||
type="button"
|
||||
className="truncate rounded-md px-2 py-1.5 text-left font-mono text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
onClick={() => injectCommand(cmd)}
|
||||
title={cmd}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<FrameFooter className="border-t text-[10px] text-muted-foreground/70">
|
||||
<p>↑↓ — история команд</p>
|
||||
<p>Ctrl+L — очистить экран</p>
|
||||
{isLive
|
||||
? <p className="text-info">Команды выполняются на роутере</p>
|
||||
: <p>Режим: mock-данные</p>}
|
||||
</FrameFooter>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
function injectCommand(cmd: string) {
|
||||
const el = document.querySelector<HTMLInputElement>(".terminal-input-active")
|
||||
if (!el) return
|
||||
@@ -502,108 +595,42 @@ export default function TerminalPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex h-full flex-col">
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Инструменты" }, { label: "Терминал" }]}
|
||||
actions={
|
||||
<Button variant="outline" size="sm" onClick={() => {
|
||||
setRefreshKey(k => k + 1)
|
||||
if (isLive) setSelectedUid("")
|
||||
}}>
|
||||
<RefreshCwIcon className="size-4" />Переподключить
|
||||
</Button>
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="md:hidden"
|
||||
onClick={() => setRailOpen(true)}
|
||||
>
|
||||
<ServerIcon className="size-4" />
|
||||
{selected?.name ?? "Сервер"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setRefreshKey((k) => k + 1)
|
||||
if (isLive) setSelectedUid("")
|
||||
}}
|
||||
>
|
||||
<RefreshCwIcon className="size-4" />
|
||||
Переподключить
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="flex-1 overflow-hidden p-6">
|
||||
<div className="grid grid-cols-[220px_1fr] gap-5 h-full">
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<aside className="hidden min-h-0 w-60 shrink-0 flex-col gap-3 p-3 pr-0 md:flex">
|
||||
{rail}
|
||||
<QuickCmds />
|
||||
</aside>
|
||||
|
||||
{/* ── sidebar ── */}
|
||||
<div className="flex flex-col gap-4 overflow-y-auto min-h-0">
|
||||
|
||||
{/* server picker */}
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Узел</p>
|
||||
{isLive && serversLoading && (
|
||||
<Loader2Icon className="size-3 animate-spin text-muted-foreground" />
|
||||
)}
|
||||
{isLive && !serversLoading && (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] font-medium rounded border border-emerald-500/30 bg-emerald-500/10 text-emerald-400 px-1.5 py-0.5">
|
||||
<span className="size-1 rounded-full bg-emerald-400" />LIVE
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isLive && !serversLoading && liveServers.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground px-2.5">
|
||||
Нет доступных серверов
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-1">
|
||||
{termServers.map(s => {
|
||||
const isOffline = s.status === "offline"
|
||||
const isSelected = s.uid === selectedUid
|
||||
return (
|
||||
<button
|
||||
key={s.uid}
|
||||
disabled={isOffline || !s.enabled}
|
||||
onClick={() => { setSelectedUid(s.uid); setRefreshKey(k => k + 1) }}
|
||||
className={cn(
|
||||
"w-full text-left rounded-md px-2.5 py-2 text-xs transition-colors",
|
||||
"flex items-center gap-2",
|
||||
isSelected
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "hover:bg-muted",
|
||||
(isOffline || !s.enabled) && "opacity-40 cursor-not-allowed",
|
||||
)}
|
||||
>
|
||||
<span className={cn(
|
||||
"inline-block size-1.5 rounded-full shrink-0",
|
||||
s.status === "online" ? "bg-emerald-500" :
|
||||
s.status === "degraded" ? "bg-amber-400" :
|
||||
s.status === null ? "bg-sky-400" : "bg-red-500",
|
||||
)} />
|
||||
{s.country && <Flag code={s.country} />}
|
||||
<span className="truncate font-mono">{s.name}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* quick commands */}
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
|
||||
Быстрые команды
|
||||
</p>
|
||||
<div className="space-y-1">
|
||||
{QUICK_CMDS.map(({ cmd, label }) => (
|
||||
<button
|
||||
key={cmd}
|
||||
className="w-full text-left rounded-md px-2.5 py-1.5 text-[11px] font-mono text-muted-foreground hover:bg-muted hover:text-foreground transition-colors truncate block"
|
||||
onClick={() => injectCommand(cmd)}
|
||||
title={cmd}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* hints */}
|
||||
<div className="mt-auto text-[10px] text-muted-foreground/50 space-y-0.5 px-0.5">
|
||||
<p>↑↓ — история команд</p>
|
||||
<p>Ctrl+L — очистить экран</p>
|
||||
{isLive
|
||||
? <p className="text-sky-400/60">Команды выполняются на роутере</p>
|
||||
: <p>Режим: mock-данные</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── terminal ── */}
|
||||
<div className="min-w-0 flex-1 overflow-hidden p-3 md:p-4">
|
||||
{selected ? (
|
||||
<Terminal
|
||||
key={termKey}
|
||||
@@ -612,12 +639,34 @@ export default function TerminalPage() {
|
||||
backendUrl={backendUrl}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center bg-[#0d1117] rounded-lg border border-[#30363d] text-[#8b949e] text-sm font-mono">
|
||||
<div className="flex h-full items-center justify-center rounded-lg border border-[#30363d] bg-[#0d1117] font-mono text-sm text-[#8b949e]">
|
||||
{serversLoading ? "Загрузка серверов…" : "Выберите сервер"}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Sheet open={railOpen} onOpenChange={setRailOpen}>
|
||||
<SheetContent side="left" className="flex w-72 flex-col gap-3 p-3" showCloseButton>
|
||||
<SheetHeader className="px-1 pt-1">
|
||||
<SheetTitle>Серверы</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3">
|
||||
<ServerTileRail
|
||||
items={railItems}
|
||||
selectedId={selected?.uid ?? selectedUid}
|
||||
onSelect={handleSelectServer}
|
||||
showAll={false}
|
||||
showCount={false}
|
||||
showType={false}
|
||||
showHeader={false}
|
||||
headerRight={railHeaderRight}
|
||||
className="min-h-0 flex-1"
|
||||
/>
|
||||
<QuickCmds />
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+16
-54
@@ -13,13 +13,9 @@ import { VxlanDataGrid } from "@/components/data-grids/vxlan-data-grid"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
NetworkIcon, PlusIcon, CopyIcon, CheckIcon,
|
||||
CodeXmlIcon, LayersIcon,
|
||||
NetworkIcon, PlusIcon, CodeXmlIcon, LayersIcon,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||
SheetDescription, SheetFooter, SheetClose,
|
||||
} from "@/components/ui/sheet"
|
||||
import { CodeExportSheet } from "@/components/reui-kit/code-export-sheet"
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -70,57 +66,23 @@ function generateVxlanRsc(t: VxlanTunnel): string {
|
||||
function ExportSheet({ open, tunnel, onClose }: {
|
||||
open: boolean; tunnel: VxlanTunnel | null; onClose: () => void
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const code = useMemo(() => tunnel ? generateVxlanRsc(tunnel) : "", [tunnel])
|
||||
|
||||
function handleCopy() {
|
||||
navigator.clipboard.writeText(code).then(() => {
|
||||
setCopied(true); setTimeout(() => setCopied(false), 2000)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={(v) => { if (!v) onClose() }}>
|
||||
<SheetContent className="flex flex-col overflow-hidden p-0 gap-0 sm:max-w-2xl">
|
||||
<SheetHeader className="shrink-0 px-6 pt-5 pb-4 border-b">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<SheetTitle>Экспорт VXLAN</SheetTitle>
|
||||
<SheetDescription>RouterOS 7.x · /interface/vxlan + vteps</SheetDescription>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="shrink-0" onClick={handleCopy}>
|
||||
{copied ? <><CheckIcon className="size-3.5 text-emerald-500" />Скопировано</> : <><CopyIcon className="size-3.5" />Копировать</>}
|
||||
</Button>
|
||||
</div>
|
||||
</SheetHeader>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<pre className="px-6 py-5 text-[12px] font-mono leading-relaxed text-foreground/85 whitespace-pre select-all">
|
||||
{code.split("\n").map((line, i) => {
|
||||
const isComment = line.startsWith("#")
|
||||
const isCmd = /^\//.test(line.trimStart())
|
||||
const isParam = /^\s+[a-z]/.test(line)
|
||||
return (
|
||||
<span key={i} className={
|
||||
isComment ? "text-muted-foreground"
|
||||
: isCmd ? "text-sky-400"
|
||||
: isParam ? "text-violet-300"
|
||||
: "text-foreground"
|
||||
}>
|
||||
{line}{"\n"}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</pre>
|
||||
</div>
|
||||
<SheetFooter className="shrink-0 px-6 py-4 border-t flex-row gap-2">
|
||||
<SheetClose render={<Button variant="outline" className="flex-1" />}>Закрыть</SheetClose>
|
||||
<Button className="flex-1" onClick={handleCopy}>
|
||||
{copied ? <CheckIcon className="size-4" /> : <CopyIcon className="size-4" />}
|
||||
{copied ? "Скопировано" : "Копировать .rsc"}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<CodeExportSheet
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="Экспорт VXLAN"
|
||||
description="RouterOS 7.x · /interface/vxlan + vteps"
|
||||
formats={[
|
||||
{
|
||||
id: "rsc",
|
||||
label: "MikroTik .rsc",
|
||||
filename: `${tunnel?.name ?? "vxlan"}.rsc`,
|
||||
code,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+805
-207
File diff suppressed because it is too large
Load Diff
@@ -11,7 +11,8 @@
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"test:auth": "tsx src/lib/permissions.test.ts && tsx src/plugins/auth.smoke.test.ts"
|
||||
"test:auth": "tsx src/lib/permissions.test.ts && tsx src/plugins/auth.smoke.test.ts",
|
||||
"test:wireguard": "npx tsx src/services/wireguard-config.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.2.0",
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
]
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -102,7 +102,7 @@ const navStructure: { label: string; items: NavItemBase[] }[] = [
|
||||
},
|
||||
]
|
||||
|
||||
type LiveSidebarCounts = SidebarCountsDto & { greTunnels?: number; certificates?: number }
|
||||
type LiveSidebarCounts = SidebarCountsDto & { greTunnels?: number; certificates?: number; wireguard?: number }
|
||||
|
||||
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
const { mode, backendUrl, prefsHydrated } = useDataSource()
|
||||
@@ -165,8 +165,9 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
if (url === "/uptime") return formatSidebarBadgeCount(liveCounts.monitoringItems)
|
||||
if (url === "/gre") return formatSidebarBadgeCount(liveCounts.greTunnels ?? 0)
|
||||
if (url === "/certificates") return formatSidebarBadgeCount(liveCounts.certificates ?? 0)
|
||||
if (url === "/wireguard") return formatSidebarBadgeCount(liveCounts.wireguard ?? 0)
|
||||
|
||||
if (url === "/wireguard" || url === "/containers" || url === "/bgp") {
|
||||
if (url === "/containers" || url === "/bgp") {
|
||||
return undefined
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "@tanstack/react-table"
|
||||
import type { SchedulerJobStatusDto } from "@/lib/scheduler-settings"
|
||||
import { FormToggle } from "@/components/form-kit"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
CompactDataGrid,
|
||||
@@ -35,11 +35,11 @@ function SnapshotOkBadge({
|
||||
errLabel?: string
|
||||
}) {
|
||||
return ok ? (
|
||||
<Badge variant="outline" className="text-[10px] border-emerald-500/40 text-emerald-700 dark:text-emerald-400">
|
||||
<Badge variant="success-outline" size="sm" className="text-[10px]">
|
||||
{okLabel}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-[10px] border-destructive/50 text-destructive">
|
||||
<Badge variant="destructive-outline" size="sm" className="text-[10px]">
|
||||
{errLabel}
|
||||
</Badge>
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo } from "react"
|
||||
import { useMemo, type ReactNode } from "react"
|
||||
import {
|
||||
type ColumnDef,
|
||||
getCoreRowModel,
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import type { WireGuardInterface } from "@/lib/data"
|
||||
import { Flag } from "@/components/flag"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -33,7 +34,6 @@ import {
|
||||
ChevronRightIcon,
|
||||
CodeXmlIcon,
|
||||
MoreHorizontalIcon,
|
||||
PencilIcon,
|
||||
PlusIcon,
|
||||
PowerIcon,
|
||||
ShieldCheckIcon,
|
||||
@@ -48,17 +48,38 @@ export interface WgIfaceWithServer extends WireGuardInterface {
|
||||
|
||||
interface WireguardDataGridProps {
|
||||
interfaces: WgIfaceWithServer[]
|
||||
compactServer?: boolean
|
||||
emptyAction?: ReactNode
|
||||
onExport: (iface: WgIfaceWithServer) => void
|
||||
onAddPeer?: (iface: WgIfaceWithServer) => void
|
||||
onToggle?: (iface: WgIfaceWithServer) => void
|
||||
onDelete?: (iface: WgIfaceWithServer) => void
|
||||
onDeletePeer?: (iface: WgIfaceWithServer, peerId: string) => void
|
||||
onExportPeer?: (iface: WgIfaceWithServer, peerId: string) => void
|
||||
}
|
||||
|
||||
function WireguardDataGrid({ interfaces, onExport }: WireguardDataGridProps) {
|
||||
function WireguardDataGrid({
|
||||
interfaces,
|
||||
compactServer = false,
|
||||
emptyAction,
|
||||
onExport,
|
||||
onAddPeer,
|
||||
onToggle,
|
||||
onDelete,
|
||||
onDeletePeer,
|
||||
onExportPeer,
|
||||
}: WireguardDataGridProps) {
|
||||
const columns = useMemo<ColumnDef<WgIfaceWithServer>[]>(
|
||||
() => [
|
||||
{
|
||||
id: "name",
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => (
|
||||
<DataGridSortHeader column={column} title="Интерфейс / Сервер" className="ml-1" />
|
||||
<DataGridSortHeader
|
||||
column={column}
|
||||
title={compactServer ? "Интерфейс" : "Интерфейс / Сервер"}
|
||||
className="ml-1"
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const iface = row.original
|
||||
@@ -76,15 +97,17 @@ function WireguardDataGrid({ interfaces, onExport }: WireguardDataGridProps) {
|
||||
<span
|
||||
className={cn(
|
||||
"size-2 rounded-full shrink-0",
|
||||
iface.status === "up" ? "bg-emerald-500 animate-pulse" : "bg-red-500",
|
||||
iface.status === "up" ? "bg-success animate-pulse" : "bg-destructive",
|
||||
)}
|
||||
/>
|
||||
<span className="font-mono font-semibold text-sm">{iface.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 mt-0.5 text-[11px] text-muted-foreground font-mono">
|
||||
<Flag code={iface.serverCountry} size={12} />
|
||||
{iface.serverName}
|
||||
</div>
|
||||
{!compactServer ? (
|
||||
<div className="flex items-center gap-1.5 mt-0.5 text-[11px] text-muted-foreground font-mono">
|
||||
<Flag code={iface.serverCountry || "UN"} size={12} />
|
||||
{iface.serverName}
|
||||
</div>
|
||||
) : null}
|
||||
<p className="sr-only">
|
||||
{onlinePeers}/{iface.peers.length} пиров
|
||||
</p>
|
||||
@@ -93,11 +116,15 @@ function WireguardDataGrid({ interfaces, onExport }: WireguardDataGridProps) {
|
||||
)
|
||||
},
|
||||
meta: {
|
||||
headerTitle: "Интерфейс / Сервер",
|
||||
headerTitle: compactServer ? "Интерфейс" : "Интерфейс / Сервер",
|
||||
headerClassName: DATA_GRID_CELL_PAD_FIRST,
|
||||
cellClassName: DATA_GRID_CELL_PAD_FIRST,
|
||||
expandedContent: (row: WgIfaceWithServer) => (
|
||||
<WireGuardPeersDetail peers={row.peers} />
|
||||
<WireGuardPeersDetail
|
||||
peers={row.peers}
|
||||
onDeletePeer={onDeletePeer ? (peerId) => onDeletePeer(row, peerId) : undefined}
|
||||
onExportPeer={onExportPeer ? (peerId) => onExportPeer(row, peerId) : undefined}
|
||||
/>
|
||||
),
|
||||
},
|
||||
},
|
||||
@@ -136,7 +163,7 @@ function WireguardDataGrid({ interfaces, onExport }: WireguardDataGridProps) {
|
||||
const onlinePeers = iface.peers.filter((p) => !!p.latestHandshake).length
|
||||
return (
|
||||
<span className="font-mono text-sm text-center block">
|
||||
<span className="text-emerald-600 dark:text-emerald-400">{onlinePeers}</span>
|
||||
<span className="text-success">{onlinePeers}</span>
|
||||
<span className="text-muted-foreground">/{iface.peers.length}</span>
|
||||
</span>
|
||||
)
|
||||
@@ -152,16 +179,13 @@ function WireguardDataGrid({ interfaces, onExport }: WireguardDataGridProps) {
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <DataGridSortHeader column={column} title="Статус" />,
|
||||
cell: ({ row }) => (
|
||||
<span
|
||||
className={cn(
|
||||
"text-[11px] font-mono px-2 py-0.5 rounded border",
|
||||
row.original.status === "up"
|
||||
? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20"
|
||||
: "bg-red-500/10 text-red-500 border-red-500/20",
|
||||
)}
|
||||
<Badge
|
||||
variant={row.original.status === "up" ? "success-light" : "destructive-light"}
|
||||
size="sm"
|
||||
className="font-mono"
|
||||
>
|
||||
{row.original.status === "up" ? "UP" : "DOWN"}
|
||||
</span>
|
||||
</Badge>
|
||||
),
|
||||
meta: {
|
||||
headerTitle: "Статус",
|
||||
@@ -203,26 +227,32 @@ function WireguardDataGrid({ interfaces, onExport }: WireguardDataGridProps) {
|
||||
<DropdownMenuContent side="bottom" align="end">
|
||||
<DropdownMenuItem onClick={() => onExport(iface)}>
|
||||
<CodeXmlIcon className="size-4" />
|
||||
Экспорт .rsc
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<PencilIcon className="size-4" />
|
||||
Редактировать
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem>
|
||||
<PlusIcon className="size-4" />
|
||||
Добавить пира
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem>
|
||||
<PowerIcon className="size-4" />
|
||||
{iface.enabled ? "Отключить" : "Включить"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive">
|
||||
<Trash2Icon className="size-4" />
|
||||
Удалить
|
||||
Экспорт
|
||||
</DropdownMenuItem>
|
||||
{onAddPeer && (
|
||||
<DropdownMenuItem onClick={() => onAddPeer(iface)}>
|
||||
<PlusIcon className="size-4" />
|
||||
Добавить пира
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{onToggle && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => onToggle(iface)}>
|
||||
<PowerIcon className="size-4" />
|
||||
{iface.enabled ? "Отключить" : "Включить"}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
{onDelete && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem variant="destructive" onClick={() => onDelete(iface)}>
|
||||
<Trash2Icon className="size-4" />
|
||||
Удалить
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
@@ -236,7 +266,7 @@ function WireguardDataGrid({ interfaces, onExport }: WireguardDataGridProps) {
|
||||
},
|
||||
},
|
||||
],
|
||||
[onExport],
|
||||
[compactServer, onExport, onAddPeer, onToggle, onDelete, onDeletePeer, onExportPeer],
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
@@ -254,7 +284,8 @@ function WireguardDataGrid({ interfaces, onExport }: WireguardDataGridProps) {
|
||||
<EmptyState
|
||||
icon={<ShieldCheckIcon className="size-4" />}
|
||||
title="Нет WireGuard интерфейсов"
|
||||
description="Добавьте первый интерфейс или проверьте поиск"
|
||||
description="Добавьте первый интерфейс или сбросьте фильтры"
|
||||
action={emptyAction}
|
||||
className="border-0 py-16"
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
import type { WireGuardPeer } from "@/lib/data"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
ArrowUpIcon,
|
||||
CodeXmlIcon,
|
||||
KeyRoundIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react"
|
||||
|
||||
function fmtBytes(n: number | undefined): string {
|
||||
@@ -21,7 +24,19 @@ function truncKey(key: string): string {
|
||||
return `${key.slice(0, 8)}…${key.slice(-8)}`
|
||||
}
|
||||
|
||||
function WireGuardPeersDetail({ peers }: { peers: WireGuardPeer[] }) {
|
||||
function peerKey(peer: WireGuardPeer, index: number): string {
|
||||
return peer.id ?? peer.rosId ?? peer.publicKey ?? String(index)
|
||||
}
|
||||
|
||||
function WireGuardPeersDetail({
|
||||
peers,
|
||||
onDeletePeer,
|
||||
onExportPeer,
|
||||
}: {
|
||||
peers: WireGuardPeer[]
|
||||
onDeletePeer?: (peerId: string) => void
|
||||
onExportPeer?: (peerId: string) => void
|
||||
}) {
|
||||
if (peers.length === 0) {
|
||||
return (
|
||||
<div className="px-5 py-4 text-xs text-muted-foreground text-center border-t border-border/50">
|
||||
@@ -32,48 +47,84 @@ function WireGuardPeersDetail({ peers }: { peers: WireGuardPeer[] }) {
|
||||
|
||||
return (
|
||||
<div className="border-t border-border/50">
|
||||
<div className="grid grid-cols-[1fr_1fr_auto_auto_auto] gap-3 px-5 py-1.5 bg-muted/10 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
<div className="grid grid-cols-[1fr_1fr_auto_auto_auto_auto] gap-3 px-5 py-1.5 bg-muted/10 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
<span>Public Key</span>
|
||||
<span>Allowed IPs</span>
|
||||
<span>Последнее рукопожатие</span>
|
||||
<span>RX / TX</span>
|
||||
<span>Endpoint</span>
|
||||
<span className="sr-only">Действия</span>
|
||||
</div>
|
||||
{peers.map((peer) => (
|
||||
<div
|
||||
key={peer.publicKey}
|
||||
className="grid grid-cols-[1fr_1fr_auto_auto_auto] gap-3 px-5 py-2.5 items-center text-xs border-t border-border/50 bg-muted/20"
|
||||
>
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<KeyRoundIcon className="size-3 text-muted-foreground shrink-0" />
|
||||
<span className="font-mono text-muted-foreground truncate" title={peer.publicKey}>
|
||||
{truncKey(peer.publicKey)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="font-mono text-muted-foreground truncate">
|
||||
{peer.allowedIps.join(", ")}
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"font-mono text-[11px] whitespace-nowrap",
|
||||
peer.latestHandshake ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground",
|
||||
)}
|
||||
{peers.map((peer, index) => {
|
||||
const id = peerKey(peer, index)
|
||||
return (
|
||||
<div
|
||||
key={id}
|
||||
className="grid grid-cols-[1fr_1fr_auto_auto_auto_auto] gap-3 px-5 py-2.5 items-center text-xs border-t border-border/50 bg-muted/20"
|
||||
>
|
||||
{peer.latestHandshake ?? "нет рукопожатия"}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 text-muted-foreground whitespace-nowrap">
|
||||
<span className="flex items-center gap-0.5">
|
||||
<ArrowDownIcon className="size-3 text-emerald-500" />
|
||||
{fmtBytes(peer.transferRx)}
|
||||
</span>
|
||||
<span className="flex items-center gap-0.5">
|
||||
<ArrowUpIcon className="size-3 text-blue-400" />
|
||||
{fmtBytes(peer.transferTx)}
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<KeyRoundIcon className="size-3 text-muted-foreground shrink-0" />
|
||||
<span className="font-mono text-muted-foreground truncate" title={peer.publicKey}>
|
||||
{truncKey(peer.publicKey)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="font-mono text-muted-foreground truncate">
|
||||
{peer.allowedIps.join(", ")}
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"font-mono text-[11px] whitespace-nowrap",
|
||||
peer.latestHandshake ? "text-success" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{peer.latestHandshake ?? "нет рукопожатия"}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 text-muted-foreground whitespace-nowrap">
|
||||
<span className="flex items-center gap-0.5">
|
||||
<ArrowDownIcon className="size-3 text-success" />
|
||||
{fmtBytes(peer.transferRx)}
|
||||
</span>
|
||||
<span className="flex items-center gap-0.5">
|
||||
<ArrowUpIcon className="size-3 text-info" />
|
||||
{fmtBytes(peer.transferTx)}
|
||||
</span>
|
||||
</div>
|
||||
<span className="font-mono text-muted-foreground/60 text-[11px]">{peer.endpoint ?? "—"}</span>
|
||||
<div className="flex items-center gap-1 justify-end">
|
||||
{onExportPeer && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7"
|
||||
aria-label="Экспорт peer .conf"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onExportPeer(id)
|
||||
}}
|
||||
>
|
||||
<CodeXmlIcon className="size-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
{onDeletePeer && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 text-destructive"
|
||||
aria-label="Удалить пира"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDeletePeer(id)
|
||||
}}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<span className="font-mono text-muted-foreground/60 text-[11px]">{peer.endpoint ?? "—"}</span>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, type ReactNode } from "react"
|
||||
import {
|
||||
type ColumnDef,
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table"
|
||||
import type { WireGuardPeer } from "@/lib/data"
|
||||
import { Flag } from "@/components/flag"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
|
||||
import {
|
||||
DATA_GRID_CELL_PAD,
|
||||
DATA_GRID_CELL_PAD_FIRST,
|
||||
DATA_GRID_CELL_PAD_LAST,
|
||||
} from "@/components/data-grids/shared/data-grid-layout"
|
||||
import { DataGridSortHeader } from "@/components/data-grids/shared/data-grid-sort-header"
|
||||
import { EmptyState } from "@/components/empty-state"
|
||||
import { fmtBytes, truncKey } from "@/components/data-grids/wireguard-peers-detail"
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
ArrowUpIcon,
|
||||
CodeXmlIcon,
|
||||
KeyRoundIcon,
|
||||
Trash2Icon,
|
||||
UsersIcon,
|
||||
} from "lucide-react"
|
||||
|
||||
export interface WgPeerRow extends WireGuardPeer {
|
||||
id: string
|
||||
ifaceId: string
|
||||
ifaceName: string
|
||||
serverId: string
|
||||
serverName: string
|
||||
serverCountry: string
|
||||
}
|
||||
|
||||
interface WireguardPeersGridProps {
|
||||
peers: WgPeerRow[]
|
||||
compactServer?: boolean
|
||||
emptyAction?: ReactNode
|
||||
onDeletePeer?: (row: WgPeerRow) => void
|
||||
onExportPeer?: (row: WgPeerRow) => void
|
||||
}
|
||||
|
||||
function WireguardPeersGrid({
|
||||
peers,
|
||||
compactServer = false,
|
||||
emptyAction,
|
||||
onDeletePeer,
|
||||
onExportPeer,
|
||||
}: WireguardPeersGridProps) {
|
||||
const columns = useMemo<ColumnDef<WgPeerRow>[]>(() => {
|
||||
const cols: ColumnDef<WgPeerRow>[] = [
|
||||
{
|
||||
id: "peer",
|
||||
accessorKey: "publicKey",
|
||||
header: ({ column }) => (
|
||||
<DataGridSortHeader column={column} title="Пир" className="ml-1" />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const peer = row.original
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<KeyRoundIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate font-mono text-xs" title={peer.publicKey}>
|
||||
{peer.name || truncKey(peer.publicKey)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
meta: {
|
||||
headerTitle: "Пир",
|
||||
headerClassName: DATA_GRID_CELL_PAD_FIRST,
|
||||
cellClassName: DATA_GRID_CELL_PAD_FIRST,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "iface",
|
||||
accessorKey: "ifaceName",
|
||||
header: ({ column }) => <DataGridSortHeader column={column} title="Интерфейс" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="font-mono text-sm">{row.original.ifaceName}</span>
|
||||
),
|
||||
meta: {
|
||||
headerTitle: "Интерфейс",
|
||||
headerClassName: DATA_GRID_CELL_PAD,
|
||||
cellClassName: DATA_GRID_CELL_PAD,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
if (!compactServer) {
|
||||
cols.push({
|
||||
id: "server",
|
||||
accessorKey: "serverName",
|
||||
header: ({ column }) => <DataGridSortHeader column={column} title="Сервер" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1.5 font-mono text-[11px] text-muted-foreground">
|
||||
<Flag code={row.original.serverCountry || "UN"} size={12} />
|
||||
{row.original.serverName}
|
||||
</div>
|
||||
),
|
||||
meta: {
|
||||
headerTitle: "Сервер",
|
||||
headerClassName: DATA_GRID_CELL_PAD,
|
||||
cellClassName: DATA_GRID_CELL_PAD,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
cols.push(
|
||||
{
|
||||
id: "allowedIps",
|
||||
accessorFn: (row) => row.allowedIps.join(", "),
|
||||
header: ({ column }) => <DataGridSortHeader column={column} title="Allowed IPs" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="block truncate font-mono text-xs text-muted-foreground">
|
||||
{row.original.allowedIps.join(", ") || "—"}
|
||||
</span>
|
||||
),
|
||||
meta: {
|
||||
headerTitle: "Allowed IPs",
|
||||
headerClassName: DATA_GRID_CELL_PAD,
|
||||
cellClassName: DATA_GRID_CELL_PAD,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "handshake",
|
||||
accessorKey: "latestHandshake",
|
||||
header: ({ column }) => <DataGridSortHeader column={column} title="Handshake" />,
|
||||
cell: ({ row }) => (
|
||||
<span
|
||||
className={cn(
|
||||
"whitespace-nowrap font-mono text-[11px]",
|
||||
row.original.latestHandshake ? "text-success" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{row.original.latestHandshake ?? "нет рукопожатия"}
|
||||
</span>
|
||||
),
|
||||
meta: {
|
||||
headerTitle: "Handshake",
|
||||
headerClassName: DATA_GRID_CELL_PAD,
|
||||
cellClassName: DATA_GRID_CELL_PAD,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "transfer",
|
||||
header: () => (
|
||||
<span className="text-xs font-medium text-muted-foreground">RX / TX</span>
|
||||
),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2 whitespace-nowrap text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-0.5">
|
||||
<ArrowDownIcon className="size-3 text-success" />
|
||||
{fmtBytes(row.original.transferRx)}
|
||||
</span>
|
||||
<span className="flex items-center gap-0.5">
|
||||
<ArrowUpIcon className="size-3 text-info" />
|
||||
{fmtBytes(row.original.transferTx)}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
meta: {
|
||||
headerTitle: "RX / TX",
|
||||
headerClassName: DATA_GRID_CELL_PAD,
|
||||
cellClassName: DATA_GRID_CELL_PAD,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "endpoint",
|
||||
accessorKey: "endpoint",
|
||||
header: ({ column }) => <DataGridSortHeader column={column} title="Endpoint" />,
|
||||
cell: ({ row }) => (
|
||||
<span className="font-mono text-[11px] text-muted-foreground">
|
||||
{row.original.endpoint ?? "—"}
|
||||
</span>
|
||||
),
|
||||
meta: {
|
||||
headerTitle: "Endpoint",
|
||||
headerClassName: DATA_GRID_CELL_PAD,
|
||||
cellClassName: DATA_GRID_CELL_PAD,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Действия</span>,
|
||||
enableSorting: false,
|
||||
size: 72,
|
||||
cell: ({ row }) => {
|
||||
const peer = row.original
|
||||
return (
|
||||
<div className="flex justify-end gap-0.5">
|
||||
{onExportPeer ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7"
|
||||
aria-label="Экспорт peer .conf"
|
||||
onClick={() => onExportPeer(peer)}
|
||||
>
|
||||
<CodeXmlIcon className="size-3.5" />
|
||||
</Button>
|
||||
) : null}
|
||||
{onDeletePeer ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 text-destructive"
|
||||
aria-label="Удалить пира"
|
||||
onClick={() => onDeletePeer(peer)}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
meta: {
|
||||
headerClassName: DATA_GRID_CELL_PAD_LAST,
|
||||
cellClassName: DATA_GRID_CELL_PAD_LAST,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
return cols
|
||||
}, [compactServer, onDeletePeer, onExportPeer])
|
||||
|
||||
const table = useReactTable({
|
||||
data: peers,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getRowId: (row) => row.id,
|
||||
})
|
||||
|
||||
if (peers.length === 0) {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={<UsersIcon className="size-4" />}
|
||||
title="Нет пиров"
|
||||
description="Добавьте пира к интерфейсу или сбросьте поиск"
|
||||
action={emptyAction}
|
||||
className="border-0 py-16"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DataGridShell
|
||||
table={table}
|
||||
recordCount={peers.length}
|
||||
tableClassNames={{
|
||||
headerRow: "border-b border-border",
|
||||
bodyRow: cn("group/row"),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { WireguardPeersGrid, type WireguardPeersGridProps }
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import * as React from "react"
|
||||
import Link from "next/link"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react"
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
} from "@/components/reui/alert"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Frame, FramePanel } from "@/components/reui/frame"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
Sheet,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import {
|
||||
CheckIcon,
|
||||
CopyIcon,
|
||||
DownloadIcon,
|
||||
LoaderCircleIcon,
|
||||
RefreshCwIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export type CodeExportFormat = {
|
||||
id: string
|
||||
label: string
|
||||
filename: string
|
||||
code: string
|
||||
/** Empty / unavailable — show warning instead of code */
|
||||
emptyMessage?: string
|
||||
/** Content came from live device fetch */
|
||||
isLive?: boolean
|
||||
}
|
||||
|
||||
function downloadText(filename: string, content: string) {
|
||||
const blob = new Blob([content], { type: "text/plain;charset=utf-8" })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement("a")
|
||||
a.href = url
|
||||
a.download = filename
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
function highlightLine(line: string): string {
|
||||
const trimmed = line.trimStart()
|
||||
if (line.startsWith("#") || trimmed.startsWith(";")) return "text-muted-foreground"
|
||||
if (trimmed.startsWith("[")) return "text-info"
|
||||
if (trimmed.startsWith("/")) return "text-info"
|
||||
if (/^\s+[a-zA-Z]/.test(line) || /^[A-Za-z][\w-]*=/.test(line)) return "text-foreground"
|
||||
return "text-foreground/90"
|
||||
}
|
||||
|
||||
function CodeBlock({ code }: { code: string }) {
|
||||
const lines = code.length ? code.split("\n") : [""]
|
||||
return (
|
||||
<pre className="px-4 py-3.5 text-[12px] font-mono leading-[1.65] whitespace-pre-wrap break-all select-all">
|
||||
{lines.map((line, i) => (
|
||||
<span key={i} className={cn("block", highlightLine(line))}>
|
||||
{line || " "}
|
||||
</span>
|
||||
))}
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
|
||||
export interface CodeExportSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
title: string
|
||||
description?: ReactNode
|
||||
formats: CodeExportFormat[]
|
||||
/** Initial format id when sheet opens */
|
||||
initialFormatId?: string
|
||||
/** Optional live fetch from device */
|
||||
onLiveFetch?: (formatId: string) => void
|
||||
liveBusy?: boolean
|
||||
/** Short CTA — keep laconic */
|
||||
liveLabel?: string
|
||||
className?: string
|
||||
/** Extra content under format tabs (e.g. meta strip) */
|
||||
beforeCode?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared code export Sheet — ReUI Frame + sticky footer.
|
||||
* Preview DNA: https://reui.io/preview/base/sheet-8 · Frame https://reui.io/docs/components/base/frame
|
||||
* Alert: https://reui.io/docs/components/base/alert
|
||||
*/
|
||||
function CodeExportSheet({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
description,
|
||||
formats,
|
||||
initialFormatId,
|
||||
onLiveFetch,
|
||||
liveBusy,
|
||||
liveLabel = "С роутера",
|
||||
className,
|
||||
beforeCode,
|
||||
}: CodeExportSheetProps) {
|
||||
const firstId = formats[0]?.id ?? "default"
|
||||
const [tab, setTab] = useState(initialFormatId ?? firstId)
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setTab(
|
||||
initialFormatId && formats.some((f) => f.id === initialFormatId)
|
||||
? initialFormatId
|
||||
: firstId,
|
||||
)
|
||||
setCopied(false)
|
||||
}, [open, initialFormatId, firstId, formats])
|
||||
|
||||
const active = useMemo(
|
||||
() => formats.find((f) => f.id === tab) ?? formats[0],
|
||||
[formats, tab],
|
||||
)
|
||||
|
||||
const code = active?.code ?? ""
|
||||
const emptyMessage = active?.emptyMessage
|
||||
const filename = active?.filename ?? "export.txt"
|
||||
const canCopy = Boolean(code) && !emptyMessage
|
||||
const isLive = Boolean(active?.isLive)
|
||||
const showTabs = formats.length > 1
|
||||
|
||||
function handleCopy() {
|
||||
if (!canCopy) return
|
||||
void navigator.clipboard.writeText(code).then(() => {
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1800)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={(v) => { if (!v) onClose() }}>
|
||||
<SheetContent
|
||||
className={cn(
|
||||
"flex w-full flex-col gap-0 overflow-hidden p-0 sm:max-w-xl",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<SheetHeader className="shrink-0 gap-1 border-b px-5 pt-5 pb-4 pr-12">
|
||||
<SheetTitle className="text-base font-semibold tracking-tight">
|
||||
{title}
|
||||
</SheetTitle>
|
||||
{description ? (
|
||||
<SheetDescription className="font-mono text-xs">
|
||||
{description}
|
||||
</SheetDescription>
|
||||
) : null}
|
||||
</SheetHeader>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3 px-5 py-4">
|
||||
{showTabs ? (
|
||||
<Tabs
|
||||
value={tab}
|
||||
onValueChange={(v) => setTab(String(v))}
|
||||
className="shrink-0 gap-0"
|
||||
>
|
||||
<TabsList className="h-9 w-full">
|
||||
{formats.map((f) => (
|
||||
<TabsTrigger key={f.id} value={f.id} className="flex-1 px-2 text-xs sm:text-sm">
|
||||
{f.label}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
) : null}
|
||||
|
||||
{onLiveFetch || beforeCode ? (
|
||||
<div className="flex shrink-0 flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
{onLiveFetch ? (
|
||||
<Badge
|
||||
variant={isLive ? "success-light" : "secondary"}
|
||||
size="sm"
|
||||
radius="full"
|
||||
>
|
||||
{isLive ? "С роутера" : "Локально"}
|
||||
</Badge>
|
||||
) : null}
|
||||
{beforeCode}
|
||||
</div>
|
||||
{onLiveFetch ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="shrink-0"
|
||||
disabled={liveBusy}
|
||||
onClick={() => onLiveFetch(tab)}
|
||||
aria-label="Подтянуть конфиг с роутера с private-key"
|
||||
>
|
||||
{liveBusy ? (
|
||||
<LoaderCircleIcon className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCwIcon className="size-3.5" />
|
||||
)}
|
||||
{liveBusy ? "Загрузка…" : liveLabel}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Frame dense className="flex min-h-0 flex-1 flex-col">
|
||||
<FramePanel className="relative flex min-h-0 flex-1 flex-col overflow-hidden p-0">
|
||||
{emptyMessage ? (
|
||||
<div className="flex flex-1 items-center p-4">
|
||||
<Alert variant="warning" className="w-full">
|
||||
<TriangleAlertIcon />
|
||||
<AlertTitle>Нет данных</AlertTitle>
|
||||
<AlertDescription>{emptyMessage}</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="h-full min-h-0 flex-1">
|
||||
<div className="min-h-[min(52vh,22rem)]">
|
||||
<CodeBlock code={code} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
|
||||
{onLiveFetch && !isLive ? (
|
||||
<p className="text-muted-foreground shrink-0 text-[11px] leading-snug">
|
||||
Локальный снимок. Подтяните с роутера, если нужен private-key с устройства.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<SheetFooter className="shrink-0 flex-row items-center justify-between gap-3 border-t px-5 py-3.5 sm:flex-row">
|
||||
<SheetClose
|
||||
render={
|
||||
<Button type="button" variant="ghost" className="shrink-0 px-3" />
|
||||
}
|
||||
>
|
||||
Закрыть
|
||||
</SheetClose>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="default"
|
||||
disabled={!canCopy}
|
||||
onClick={() => downloadText(filename, code)}
|
||||
>
|
||||
<DownloadIcon className="size-4" />
|
||||
Файл
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="default"
|
||||
disabled={!canCopy}
|
||||
onClick={handleCopy}
|
||||
className="min-w-28"
|
||||
>
|
||||
{copied ? (
|
||||
<CheckIcon className="size-4 text-success" />
|
||||
) : (
|
||||
<CopyIcon className="size-4" />
|
||||
)}
|
||||
{copied ? "Скопировано" : "Копировать"}
|
||||
</Button>
|
||||
</div>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
export { CodeExportSheet, downloadText }
|
||||
@@ -0,0 +1,5 @@
|
||||
export { CodeExportSheet, downloadText } from "./code-export-sheet"
|
||||
export type { CodeExportFormat, CodeExportSheetProps } from "./code-export-sheet"
|
||||
export { KpiStatGrid, KpiStatCardTile, kpiStatItemKey } from "./kpi-stat-grid"
|
||||
export type { KpiStatItem, KpiStatCardData, KpiStatVariant } from "./kpi-stat-grid"
|
||||
export { kpiCols } from "./kpi-cols"
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Shared grid column classes for hybrid KPI tiles.
|
||||
* @see https://reui.io/preview/base/stats-12
|
||||
*/
|
||||
export function kpiCols(count: number): string {
|
||||
if (count <= 1) return "grid-cols-1"
|
||||
if (count === 2) return "grid-cols-1 @xl:grid-cols-2"
|
||||
if (count === 3) return "grid-cols-1 @3xl:grid-cols-3"
|
||||
if (count === 4) return "grid-cols-1 @3xl:grid-cols-2 @6xl:grid-cols-4"
|
||||
if (count <= 6) return "grid-cols-1 @xl:grid-cols-2 @4xl:grid-cols-3"
|
||||
return "grid-cols-1 @xl:grid-cols-2 @4xl:grid-cols-3 @6xl:grid-cols-4"
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
"use client"
|
||||
|
||||
import type { KeyboardEvent, ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { Frame, FramePanel } from "@/components/reui/frame"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { IconTile } from "@/components/reui/icon-tile"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { kpiCols } from "./kpi-cols"
|
||||
|
||||
export type KpiStatVariant = "default" | "warning" | "destructive"
|
||||
|
||||
/**
|
||||
* KPI tile — horizontal compact hybrid (icon left + label/Badge + value).
|
||||
* @see https://reui.io/preview/base/stats-12
|
||||
*/
|
||||
export type KpiStatItem = {
|
||||
id?: string
|
||||
label: ReactNode
|
||||
value: ReactNode
|
||||
hint?: ReactNode
|
||||
href?: string
|
||||
onSelect?: () => void
|
||||
onClick?: () => void
|
||||
selected?: boolean
|
||||
active?: boolean
|
||||
icon?: ReactNode
|
||||
iconClassName?: string
|
||||
variant?: KpiStatVariant
|
||||
footer?: ReactNode
|
||||
}
|
||||
|
||||
export type KpiStatCardData = KpiStatItem & { id: string }
|
||||
|
||||
const DEFAULT_ICON_CLASS = "text-muted-foreground [&_svg]:text-current"
|
||||
|
||||
const VALUE_VARIANT_CLASS: Record<KpiStatVariant, string> = {
|
||||
default: "text-foreground",
|
||||
warning: "text-warning",
|
||||
destructive: "text-destructive",
|
||||
}
|
||||
|
||||
function handleCardKeyDown(onActivate: () => void, event: KeyboardEvent<HTMLDivElement>) {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault()
|
||||
onActivate()
|
||||
}
|
||||
}
|
||||
|
||||
function resolveActivate(item: KpiStatItem): (() => void) | undefined {
|
||||
return item.onClick ?? item.onSelect
|
||||
}
|
||||
|
||||
function isSelected(item: KpiStatItem): boolean {
|
||||
return Boolean(item.selected ?? item.active)
|
||||
}
|
||||
|
||||
function resolveFooter(item: KpiStatItem): ReactNode {
|
||||
if (item.footer) return item.footer
|
||||
if (typeof item.hint === "string") {
|
||||
return (
|
||||
<Badge variant="outline" size="sm" className="max-w-[min(100%,11rem)] truncate">
|
||||
{item.hint}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
if (item.hint) return item.hint
|
||||
return null
|
||||
}
|
||||
|
||||
function KpiStatCardBody({ item }: { item: KpiStatItem }) {
|
||||
const footer = resolveFooter(item)
|
||||
const valueVariant = item.variant ?? "default"
|
||||
|
||||
return (
|
||||
<div className="@container relative z-10 flex h-full min-w-0 items-start gap-3">
|
||||
{item.icon ? (
|
||||
<IconTile
|
||||
variant="elevated"
|
||||
aria-hidden="true"
|
||||
className={cn("size-10.5 shrink-0", item.iconClassName ?? DEFAULT_ICON_CLASS)}
|
||||
>
|
||||
{item.icon}
|
||||
</IconTile>
|
||||
) : null}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<div className="flex min-w-0 items-start justify-between gap-2">
|
||||
<div className="text-muted-foreground min-w-0 truncate text-sm font-medium">
|
||||
{item.label}
|
||||
</div>
|
||||
{footer ? (
|
||||
<div className="hidden min-w-0 max-w-[min(100%,11rem)] shrink-0 @[20rem]:block">
|
||||
{footer}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"min-w-0 break-all text-2xl leading-none font-bold tabular-nums",
|
||||
VALUE_VARIANT_CLASS[valueVariant],
|
||||
)}
|
||||
>
|
||||
{item.value}
|
||||
</div>
|
||||
{footer ? (
|
||||
<div className="min-w-0 max-w-full @[20rem]:hidden">{footer}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function panelClassName(item: KpiStatItem, className?: string) {
|
||||
const onActivate = resolveActivate(item)
|
||||
const clickable = Boolean(item.href || onActivate)
|
||||
const selected = isSelected(item)
|
||||
|
||||
return cn(
|
||||
"relative isolate flex h-full min-w-0 flex-col",
|
||||
clickable &&
|
||||
"hover:bg-muted/40 focus-within:ring-ring cursor-pointer transition-colors focus-within:ring-2",
|
||||
selected && "ring-primary/30 bg-muted/30 ring-1",
|
||||
className,
|
||||
)
|
||||
}
|
||||
|
||||
export function KpiStatCardTile({
|
||||
item,
|
||||
embedded = false,
|
||||
className,
|
||||
}: {
|
||||
item: KpiStatItem
|
||||
embedded?: boolean
|
||||
className?: string
|
||||
}) {
|
||||
const onActivate = resolveActivate(item)
|
||||
const panelClass = panelClassName(item, className)
|
||||
|
||||
let panel: ReactNode
|
||||
|
||||
if (item.href) {
|
||||
panel = (
|
||||
<FramePanel className={panelClass}>
|
||||
<Link href={item.href} className="focus-visible:outline-none">
|
||||
<KpiStatCardBody item={item} />
|
||||
</Link>
|
||||
</FramePanel>
|
||||
)
|
||||
} else if (onActivate) {
|
||||
panel = (
|
||||
<FramePanel
|
||||
className={panelClass}
|
||||
onClick={onActivate}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => handleCardKeyDown(onActivate, e)}
|
||||
>
|
||||
<KpiStatCardBody item={item} />
|
||||
</FramePanel>
|
||||
)
|
||||
} else {
|
||||
panel = (
|
||||
<FramePanel className={panelClass}>
|
||||
<KpiStatCardBody item={item} />
|
||||
</FramePanel>
|
||||
)
|
||||
}
|
||||
|
||||
if (embedded) {
|
||||
return <Frame className="h-full ring-1 ring-foreground/10">{panel}</Frame>
|
||||
}
|
||||
|
||||
return <Frame className="h-full">{panel}</Frame>
|
||||
}
|
||||
|
||||
function KpiStatGridSkeleton({ count }: { count: number }) {
|
||||
return (
|
||||
<Frame className="@container w-full">
|
||||
<div className={cn("grid gap-2", kpiCols(count))}>
|
||||
{Array.from({ length: count }).map((_, index) => (
|
||||
<FramePanel key={index} className="flex items-start gap-3">
|
||||
<Skeleton className="size-10.5 shrink-0 rounded-lg" />
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Skeleton className="h-4 w-20" />
|
||||
<Skeleton className="h-4.5 w-14 rounded-full" />
|
||||
</div>
|
||||
<Skeleton className="h-7 w-16" />
|
||||
</div>
|
||||
</FramePanel>
|
||||
))}
|
||||
</div>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
interface KpiStatGridProps {
|
||||
items?: KpiStatItem[]
|
||||
cards?: KpiStatCardData[]
|
||||
isLoading?: boolean
|
||||
emptyMessage?: ReactNode
|
||||
emptyIcon?: ReactNode
|
||||
className?: string
|
||||
skeletonCount?: number
|
||||
embedded?: boolean
|
||||
"aria-label"?: string
|
||||
}
|
||||
|
||||
function KpiStatCardItem({ item }: { item: KpiStatItem }) {
|
||||
const onActivate = resolveActivate(item)
|
||||
const panelClass = panelClassName(item)
|
||||
|
||||
if (item.href) {
|
||||
return (
|
||||
<FramePanel className={panelClass}>
|
||||
<Link href={item.href} className="focus-visible:outline-none">
|
||||
<KpiStatCardBody item={item} />
|
||||
</Link>
|
||||
</FramePanel>
|
||||
)
|
||||
}
|
||||
|
||||
if (onActivate) {
|
||||
return (
|
||||
<FramePanel
|
||||
className={panelClass}
|
||||
onClick={onActivate}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => handleCardKeyDown(onActivate, e)}
|
||||
>
|
||||
<KpiStatCardBody item={item} />
|
||||
</FramePanel>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<FramePanel className={panelClass}>
|
||||
<KpiStatCardBody item={item} />
|
||||
</FramePanel>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Hybrid KPI — horizontal compact layout (icon left).
|
||||
* Preview: https://reui.io/preview/base/stats-12
|
||||
*/
|
||||
export function KpiStatGrid({
|
||||
items,
|
||||
cards,
|
||||
isLoading = false,
|
||||
emptyMessage,
|
||||
emptyIcon,
|
||||
className,
|
||||
skeletonCount = 4,
|
||||
embedded = false,
|
||||
"aria-label": ariaLabel,
|
||||
}: KpiStatGridProps) {
|
||||
if (isLoading) {
|
||||
return <KpiStatGridSkeleton count={skeletonCount} />
|
||||
}
|
||||
|
||||
const list = items ?? cards ?? []
|
||||
|
||||
if (list.length === 0 && (emptyMessage || emptyIcon)) {
|
||||
return (
|
||||
<Frame dense spacing="sm" className={cn("w-full", className)}>
|
||||
<FramePanel className="flex items-center gap-3 p-4">
|
||||
{emptyIcon}
|
||||
{emptyMessage ? (
|
||||
<p className="text-muted-foreground text-sm">{emptyMessage}</p>
|
||||
) : null}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
if (embedded) {
|
||||
return (
|
||||
<section aria-label={ariaLabel} className={cn("@container w-full", className)}>
|
||||
<div className={cn("grid gap-2", kpiCols(list.length || 1))}>
|
||||
{list.map((item, index) => (
|
||||
<KpiStatCardTile key={kpiStatItemKey(item, index)} item={item} embedded />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Frame className={cn("@container w-full min-w-0", className)} aria-label={ariaLabel}>
|
||||
<div className={cn("grid gap-2", kpiCols(list.length || 1))}>
|
||||
{list.map((item, index) => (
|
||||
<KpiStatCardItem key={kpiStatItemKey(item, index)} item={item} />
|
||||
))}
|
||||
</div>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
export function kpiStatItemKey(item: KpiStatItem, index: number): string {
|
||||
if (item.id) return item.id
|
||||
if (typeof item.label === "string") return item.label
|
||||
return `kpi-${index}`
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState, type ReactNode } from "react"
|
||||
import type { ServerStatus, ServerType } from "@/lib/data"
|
||||
import { Flag } from "@/components/flag"
|
||||
import { StatusDot } from "@/components/status-dot"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { IconTile } from "@/components/reui/icon-tile"
|
||||
import {
|
||||
Frame,
|
||||
FrameHeader,
|
||||
FramePanel,
|
||||
FrameTitle,
|
||||
} from "@/components/reui/frame"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import {
|
||||
InputGroup,
|
||||
InputGroupAddon,
|
||||
InputGroupInput,
|
||||
} from "@/components/ui/input-group"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { LayersIcon, SearchIcon, ServerIcon } from "lucide-react"
|
||||
|
||||
/** Preview: https://reui.io/preview/base/list-9 · https://reui.io/docs/components/base/icon-tile · https://reui.io/preview/base/components/c-input-group-1 */
|
||||
export const ALL_SERVERS_ID = "all"
|
||||
|
||||
export interface ServerTileItem {
|
||||
id: string
|
||||
name: string
|
||||
country?: string
|
||||
status?: ServerStatus
|
||||
type?: ServerType
|
||||
count?: number
|
||||
enabled?: boolean
|
||||
selectable?: boolean
|
||||
title?: string
|
||||
}
|
||||
|
||||
function typeBadgeVariant(
|
||||
type: ServerType,
|
||||
): "focus-light" | "info-light" | "success-light" {
|
||||
if (type === "jump-host") return "focus-light"
|
||||
if (type === "home-router") return "success-light"
|
||||
return "info-light"
|
||||
}
|
||||
|
||||
function typeBadgeLabel(type: ServerType): string {
|
||||
if (type === "jump-host") return "JH"
|
||||
if (type === "home-router") return "HR"
|
||||
return "EN"
|
||||
}
|
||||
|
||||
function ServerTypeBadge({ type }: { type: ServerType }) {
|
||||
return (
|
||||
<Badge variant={typeBadgeVariant(type)} size="xs" className="font-mono">
|
||||
{typeBadgeLabel(type)}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
function matchesQuery(item: ServerTileItem, q: string): boolean {
|
||||
if (!q) return true
|
||||
const hay = [item.name, item.title ?? ""].join(" ").toLowerCase()
|
||||
return hay.includes(q)
|
||||
}
|
||||
|
||||
function ServerTileRail({
|
||||
items,
|
||||
selectedId,
|
||||
onSelect,
|
||||
allCount = 0,
|
||||
showHeader = true,
|
||||
showAll = true,
|
||||
showCount = true,
|
||||
showType = true,
|
||||
headerRight,
|
||||
className,
|
||||
}: {
|
||||
items: ServerTileItem[]
|
||||
selectedId: string
|
||||
onSelect: (id: string) => void
|
||||
allCount?: number
|
||||
showHeader?: boolean
|
||||
showAll?: boolean
|
||||
showCount?: boolean
|
||||
showType?: boolean
|
||||
headerRight?: ReactNode
|
||||
className?: string
|
||||
}) {
|
||||
const [query, setQuery] = useState("")
|
||||
const q = query.trim().toLowerCase()
|
||||
|
||||
const filtered = useMemo(
|
||||
() => items.filter((item) => matchesQuery(item, q)),
|
||||
[items, q],
|
||||
)
|
||||
|
||||
const showAllTile = showAll && !q
|
||||
|
||||
return (
|
||||
<Frame dense spacing="sm" className={cn("flex h-full min-h-0 w-full flex-col", className)}>
|
||||
<FramePanel className="flex min-h-0 flex-1 flex-col gap-0 p-0">
|
||||
<FrameHeader className="flex flex-col gap-2 border-b px-3 py-2">
|
||||
{showHeader ? (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<FrameTitle className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Серверы
|
||||
</FrameTitle>
|
||||
{headerRight}
|
||||
</div>
|
||||
) : headerRight ? (
|
||||
<div className="flex justify-end">{headerRight}</div>
|
||||
) : null}
|
||||
<InputGroup>
|
||||
<InputGroupAddon>
|
||||
<SearchIcon className="size-3.5" />
|
||||
</InputGroupAddon>
|
||||
<InputGroupInput
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Поиск…"
|
||||
aria-label="Поиск сервера"
|
||||
/>
|
||||
</InputGroup>
|
||||
</FrameHeader>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="flex flex-col gap-0.5 p-1.5" role="listbox" aria-label="Серверы">
|
||||
{showAllTile ? (
|
||||
<ServerTileButton
|
||||
selected={selectedId === ALL_SERVERS_ID}
|
||||
onSelect={() => onSelect(ALL_SERVERS_ID)}
|
||||
title="Все серверы"
|
||||
name="Все"
|
||||
count={showCount ? allCount : undefined}
|
||||
icon={
|
||||
<IconTile variant="elevated" size="sm" aria-hidden="true">
|
||||
<LayersIcon className="text-muted-foreground" />
|
||||
</IconTile>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{filtered.map((item) => (
|
||||
<ServerTileButton
|
||||
key={item.id}
|
||||
selected={selectedId === item.id}
|
||||
onSelect={() => onSelect(item.id)}
|
||||
title={item.title ?? item.name}
|
||||
name={item.name}
|
||||
count={showCount ? item.count : undefined}
|
||||
enabled={item.enabled}
|
||||
selectable={item.selectable}
|
||||
status={item.status}
|
||||
type={showType ? item.type : undefined}
|
||||
icon={
|
||||
<IconTile variant="elevated" size="sm" aria-hidden="true">
|
||||
{item.country ? (
|
||||
<Flag code={item.country} size={16} />
|
||||
) : (
|
||||
<ServerIcon className="text-muted-foreground" />
|
||||
)}
|
||||
</IconTile>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{filtered.length === 0 && !showAllTile ? (
|
||||
<p className="px-2 py-3 text-center text-xs text-muted-foreground">
|
||||
{items.length === 0 ? "Нет доступных серверов" : "Ничего не найдено"}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
function ServerTileButton({
|
||||
selected,
|
||||
onSelect,
|
||||
title,
|
||||
name,
|
||||
count,
|
||||
enabled = true,
|
||||
selectable = true,
|
||||
status,
|
||||
type,
|
||||
icon,
|
||||
}: {
|
||||
selected: boolean
|
||||
onSelect: () => void
|
||||
title: string
|
||||
name: string
|
||||
count?: number
|
||||
enabled?: boolean
|
||||
selectable?: boolean
|
||||
status?: ServerStatus
|
||||
type?: ServerType
|
||||
icon: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
title={title}
|
||||
disabled={!selectable}
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
"flex h-11 w-full items-center gap-2 rounded-md px-2 text-left transition-colors",
|
||||
selected
|
||||
? "bg-muted ring-1 ring-border"
|
||||
: "hover:bg-muted/60",
|
||||
!enabled && !selected && "opacity-40",
|
||||
!selectable && "cursor-not-allowed opacity-40 hover:bg-transparent",
|
||||
)}
|
||||
>
|
||||
{icon}
|
||||
<span className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
{status ? <StatusDot status={status} /> : null}
|
||||
<span className="min-w-0 truncate font-mono text-[11px] font-medium">{name}</span>
|
||||
{type ? <ServerTypeBadge type={type} /> : null}
|
||||
</span>
|
||||
{count != null ? (
|
||||
<Badge
|
||||
variant={selected ? "secondary" : "outline"}
|
||||
size="xs"
|
||||
className="tabular-nums"
|
||||
>
|
||||
{count}
|
||||
</Badge>
|
||||
) : null}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export { ServerTileRail, ServerTypeBadge }
|
||||
@@ -0,0 +1,233 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { FormField, FormToggle, SectionTitle } from "@/components/form-kit"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||
SheetDescription, SheetFooter, SheetClose,
|
||||
} from "@/components/ui/sheet"
|
||||
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
|
||||
|
||||
export type WgCreateFormState = {
|
||||
serverId: string
|
||||
name: string
|
||||
listenPort: string
|
||||
mtu: string
|
||||
comment: string
|
||||
address: string
|
||||
enabled: boolean
|
||||
showAdvanced: boolean
|
||||
peerEnabled: boolean
|
||||
peerPublicKey: string
|
||||
peerAllowedIps: string
|
||||
peerEndpoint: string
|
||||
peerKeepalive: string
|
||||
peerComment: string
|
||||
}
|
||||
|
||||
export const defaultWgCreateForm = (): WgCreateFormState => ({
|
||||
serverId: "",
|
||||
name: "",
|
||||
listenPort: "13231",
|
||||
mtu: "1420",
|
||||
comment: "",
|
||||
address: "",
|
||||
enabled: true,
|
||||
showAdvanced: false,
|
||||
peerEnabled: false,
|
||||
peerPublicKey: "",
|
||||
peerAllowedIps: "",
|
||||
peerEndpoint: "",
|
||||
peerKeepalive: "25",
|
||||
peerComment: "",
|
||||
})
|
||||
|
||||
type ServerOption = { id: string; name: string; host: string }
|
||||
|
||||
function WgCreateSheet({
|
||||
open,
|
||||
onOpenChange,
|
||||
servers,
|
||||
busy,
|
||||
defaultServerId,
|
||||
onSubmit,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (v: boolean) => void
|
||||
servers: ServerOption[]
|
||||
busy?: boolean
|
||||
defaultServerId?: string
|
||||
onSubmit: (form: WgCreateFormState) => void | Promise<void>
|
||||
}) {
|
||||
const [form, setForm] = useState<WgCreateFormState>(defaultWgCreateForm)
|
||||
const set = <K extends keyof WgCreateFormState>(k: K, v: WgCreateFormState[K]) =>
|
||||
setForm((f) => ({ ...f, [k]: v }))
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setForm({ ...defaultWgCreateForm(), serverId: defaultServerId ?? "" })
|
||||
}, [open, defaultServerId])
|
||||
|
||||
const canSubmit = useMemo(() => {
|
||||
return Boolean(form.serverId && form.name.trim() && form.listenPort)
|
||||
}, [form.serverId, form.name, form.listenPort])
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent side="right" className="w-full sm:max-w-md flex flex-col gap-0 p-0">
|
||||
<SheetHeader className="px-6 pt-6 pb-4 border-b shrink-0">
|
||||
<SheetTitle>Быстрый туннель WireGuard</SheetTitle>
|
||||
<SheetDescription>
|
||||
Создать интерфейс на выбранном MikroTik (ключи сгенерирует RouterOS)
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-6 py-5 flex flex-col gap-5">
|
||||
<div className="flex flex-col gap-4">
|
||||
<SectionTitle>Основные</SectionTitle>
|
||||
<FormField label="Сервер" required>
|
||||
<select
|
||||
className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
|
||||
value={form.serverId}
|
||||
onChange={(e) => set("serverId", e.target.value)}
|
||||
>
|
||||
<option value="">Выберите сервер…</option>
|
||||
{servers.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name} ({s.host})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
<FormField label="Имя интерфейса" required hint="Например wg-msk-spb">
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="wg0"
|
||||
value={form.name}
|
||||
onChange={(e) => set("name", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormField label="Listen port" required>
|
||||
<Input
|
||||
className="font-mono"
|
||||
value={form.listenPort}
|
||||
onChange={(e) => set("listenPort", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="MTU">
|
||||
<Input
|
||||
className="font-mono"
|
||||
value={form.mtu}
|
||||
onChange={(e) => set("mtu", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
<FormField label="Комментарий">
|
||||
<Input
|
||||
value={form.comment}
|
||||
onChange={(e) => set("comment", e.target.value)}
|
||||
placeholder="MSK → SPB overlay"
|
||||
/>
|
||||
</FormField>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">Включён</p>
|
||||
<p className="text-xs text-muted-foreground">disabled=no на роутере</p>
|
||||
</div>
|
||||
<FormToggle checked={form.enabled} onChange={(v) => set("enabled", v)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground"
|
||||
onClick={() => set("showAdvanced", !form.showAdvanced)}
|
||||
>
|
||||
{form.showAdvanced ? <ChevronDownIcon className="size-4" /> : <ChevronRightIcon className="size-4" />}
|
||||
Дополнительно
|
||||
</button>
|
||||
|
||||
{form.showAdvanced && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<FormField label="IP на интерфейсе" hint="/ip address add, например 10.210.0.1/30">
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="10.210.0.1/30"
|
||||
value={form.address}
|
||||
onChange={(e) => set("address", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">Добавить первого пира</p>
|
||||
<p className="text-xs text-muted-foreground">Сразу после создания интерфейса</p>
|
||||
</div>
|
||||
<FormToggle checked={form.peerEnabled} onChange={(v) => set("peerEnabled", v)} />
|
||||
</div>
|
||||
|
||||
{form.peerEnabled && (
|
||||
<div className="flex flex-col gap-3 rounded-lg border border-border p-3">
|
||||
<FormField label="Public key пира" required>
|
||||
<Input
|
||||
className="font-mono text-xs"
|
||||
value={form.peerPublicKey}
|
||||
onChange={(e) => set("peerPublicKey", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Allowed IPs" required hint="Через запятую">
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="10.210.0.2/32"
|
||||
value={form.peerAllowedIps}
|
||||
onChange={(e) => set("peerAllowedIps", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Endpoint" hint="host:port">
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="1.2.3.4:13231"
|
||||
value={form.peerEndpoint}
|
||||
onChange={(e) => set("peerEndpoint", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Keepalive (сек)">
|
||||
<Input
|
||||
className="font-mono"
|
||||
value={form.peerKeepalive}
|
||||
onChange={(e) => set("peerKeepalive", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Комментарий пира">
|
||||
<Input
|
||||
value={form.peerComment}
|
||||
onChange={(e) => set("peerComment", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SheetFooter className="px-6 py-4 border-t shrink-0 flex-row gap-2">
|
||||
<SheetClose render={<Button variant="outline" className="flex-1" disabled={busy} />}>
|
||||
Отмена
|
||||
</SheetClose>
|
||||
<Button
|
||||
className="flex-1"
|
||||
disabled={!canSubmit || busy}
|
||||
onClick={() => void onSubmit(form)}
|
||||
>
|
||||
{busy ? "Создание…" : "Создать туннель"}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
export { WgCreateSheet }
|
||||
@@ -0,0 +1,147 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo } from "react"
|
||||
import type { WgIfaceWithServer } from "@/components/data-grids/wireguard-data-grid"
|
||||
import {
|
||||
CodeExportSheet,
|
||||
type CodeExportFormat,
|
||||
} from "@/components/reui-kit/code-export-sheet"
|
||||
import {
|
||||
generateMikrotikRsc,
|
||||
generateNativeConf,
|
||||
generatePeerClientConf,
|
||||
} from "@/lib/wg-config"
|
||||
|
||||
function WgExportSheet({
|
||||
open,
|
||||
iface,
|
||||
onClose,
|
||||
liveContent,
|
||||
liveBusy,
|
||||
onRequestLiveExport,
|
||||
initialTab = "rsc",
|
||||
peerId,
|
||||
}: {
|
||||
open: boolean
|
||||
iface: WgIfaceWithServer | null
|
||||
onClose: () => void
|
||||
liveContent?: { rsc?: string; conf?: string; peerConf?: string } | null
|
||||
liveBusy?: boolean
|
||||
onRequestLiveExport?: (format: "rsc" | "conf" | "peer-conf") => void
|
||||
initialTab?: "rsc" | "conf" | "peer"
|
||||
/** Selected peer for Peer .conf (defaults to first peer) */
|
||||
peerId?: string | null
|
||||
}) {
|
||||
const formats = useMemo((): CodeExportFormat[] => {
|
||||
if (!iface) {
|
||||
return [
|
||||
{ id: "rsc", label: ".rsc", filename: "wg.rsc", code: "" },
|
||||
{ id: "conf", label: ".conf", filename: "wg.conf", code: "" },
|
||||
{
|
||||
id: "peer",
|
||||
label: "Peer",
|
||||
filename: "wg-peer.conf",
|
||||
code: "",
|
||||
emptyMessage: "Интерфейс не выбран",
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
const base = {
|
||||
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,
|
||||
name: p.name,
|
||||
clientAddress: p.clientAddress,
|
||||
clientDns: p.clientDns,
|
||||
clientEndpoint: p.clientEndpoint,
|
||||
})),
|
||||
}
|
||||
|
||||
const peer =
|
||||
(peerId
|
||||
? iface.peers.find((p) => p.id === peerId || p.rosId === peerId)
|
||||
: undefined) ?? iface.peers[0]
|
||||
|
||||
const localRsc = generateMikrotikRsc(base)
|
||||
const localConf = generateNativeConf(base)
|
||||
|
||||
let peerConf = ""
|
||||
let peerEmpty: string | undefined
|
||||
if (!iface.publicKey) {
|
||||
peerEmpty = "Нет public-key интерфейса для клиентского .conf"
|
||||
} else if (!peer) {
|
||||
peerEmpty = "Нет пиров для экспорта Peer .conf"
|
||||
} else {
|
||||
peerConf = generatePeerClientConf({
|
||||
peerAddress: peer.clientAddress,
|
||||
peerDns: peer.clientDns,
|
||||
serverPublicKey: iface.publicKey,
|
||||
allowedIps: peer.allowedIps,
|
||||
endpoint: peer.clientEndpoint || peer.endpoint || undefined,
|
||||
persistentKeepalive: peer.persistentKeepalive ?? 25,
|
||||
})
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: "rsc",
|
||||
label: ".rsc",
|
||||
filename: `${iface.name}.rsc`,
|
||||
code: liveContent?.rsc ?? localRsc,
|
||||
isLive: Boolean(liveContent?.rsc),
|
||||
},
|
||||
{
|
||||
id: "conf",
|
||||
label: ".conf",
|
||||
filename: `${iface.name}.conf`,
|
||||
code: liveContent?.conf ?? localConf,
|
||||
isLive: Boolean(liveContent?.conf),
|
||||
},
|
||||
{
|
||||
id: "peer",
|
||||
label: "Peer",
|
||||
filename: `${iface.name}-peer.conf`,
|
||||
code: liveContent?.peerConf ?? peerConf,
|
||||
emptyMessage: liveContent?.peerConf ? undefined : peerEmpty,
|
||||
isLive: Boolean(liveContent?.peerConf),
|
||||
},
|
||||
]
|
||||
}, [iface, liveContent, peerId])
|
||||
|
||||
return (
|
||||
<CodeExportSheet
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="Экспорт WireGuard"
|
||||
description={iface ? `${iface.name} · ${iface.serverName}` : "—"}
|
||||
formats={formats}
|
||||
initialFormatId={initialTab}
|
||||
liveBusy={liveBusy}
|
||||
liveLabel="С роутера"
|
||||
onLiveFetch={
|
||||
onRequestLiveExport
|
||||
? (formatId) =>
|
||||
onRequestLiveExport(
|
||||
formatId === "peer" ? "peer-conf" : formatId === "conf" ? "conf" : "rsc",
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { WgExportSheet }
|
||||
@@ -0,0 +1,191 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { FormField, SectionTitle } from "@/components/form-kit"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||
SheetDescription, SheetFooter, SheetClose,
|
||||
} from "@/components/ui/sheet"
|
||||
import { detectWgConfigFormat, parseWgConfig, type WgParsedConfig } from "@/lib/wg-config"
|
||||
import { UploadIcon } from "lucide-react"
|
||||
|
||||
type ServerOption = { id: string; name: string; host: string }
|
||||
|
||||
function WgImportSheet({
|
||||
open,
|
||||
onOpenChange,
|
||||
servers,
|
||||
busy,
|
||||
defaultServerId,
|
||||
onImport,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (v: boolean) => void
|
||||
servers: ServerOption[]
|
||||
busy?: boolean
|
||||
defaultServerId?: string
|
||||
onImport: (args: {
|
||||
serverId: string
|
||||
content: string
|
||||
format: "auto" | "rsc" | "conf"
|
||||
dryRun: boolean
|
||||
}) => Promise<void>
|
||||
}) {
|
||||
const [serverId, setServerId] = useState("")
|
||||
const [content, setContent] = useState("")
|
||||
const [format, setFormat] = useState<"auto" | "rsc" | "conf">("auto")
|
||||
const [preview, setPreview] = useState<WgParsedConfig | null>(null)
|
||||
const [parseError, setParseError] = useState<string | null>(null)
|
||||
|
||||
const detected = useMemo(
|
||||
() => (content.trim() ? detectWgConfigFormat(content) : null),
|
||||
[content],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setServerId(defaultServerId ?? "")
|
||||
}, [open, defaultServerId])
|
||||
|
||||
function runPreview() {
|
||||
setParseError(null)
|
||||
setPreview(null)
|
||||
try {
|
||||
setPreview(parseWgConfig(content, format))
|
||||
} catch (e) {
|
||||
setParseError(e instanceof Error ? e.message : "Ошибка разбора")
|
||||
}
|
||||
}
|
||||
|
||||
function onFile(file: File | null) {
|
||||
if (!file) return
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => {
|
||||
setContent(String(reader.result ?? ""))
|
||||
setPreview(null)
|
||||
setParseError(null)
|
||||
}
|
||||
reader.readAsText(file)
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={open}
|
||||
onOpenChange={(v) => {
|
||||
if (v) {
|
||||
setServerId(defaultServerId ?? "")
|
||||
} else {
|
||||
setContent("")
|
||||
setPreview(null)
|
||||
setParseError(null)
|
||||
setServerId("")
|
||||
}
|
||||
onOpenChange(v)
|
||||
}}
|
||||
>
|
||||
<SheetContent side="right" className="w-full sm:max-w-lg flex flex-col gap-0 p-0">
|
||||
<SheetHeader className="px-6 pt-6 pb-4 border-b shrink-0">
|
||||
<SheetTitle>Импорт конфига WireGuard</SheetTitle>
|
||||
<SheetDescription>
|
||||
Native .conf или MikroTik .rsc → применить на выбранный роутер
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-6 py-5 flex flex-col gap-5">
|
||||
<FormField label="Сервер" required>
|
||||
<select
|
||||
className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
|
||||
value={serverId}
|
||||
onChange={(e) => setServerId(e.target.value)}
|
||||
>
|
||||
<option value="">Выберите сервер…</option>
|
||||
{servers.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name} ({s.host})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
|
||||
<FormField label="Формат">
|
||||
<select
|
||||
className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm"
|
||||
value={format}
|
||||
onChange={(e) => setFormat(e.target.value as "auto" | "rsc" | "conf")}
|
||||
>
|
||||
<option value="auto">Авто{detected ? ` (${detected})` : ""}</option>
|
||||
<option value="conf">Native WireGuard (.conf)</option>
|
||||
<option value="rsc">MikroTik (.rsc)</option>
|
||||
</select>
|
||||
</FormField>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<SectionTitle>Содержимое</SectionTitle>
|
||||
<label className="inline-flex items-center gap-2 text-sm text-muted-foreground cursor-pointer w-fit">
|
||||
<UploadIcon className="size-4" />
|
||||
Загрузить файл
|
||||
<input
|
||||
type="file"
|
||||
accept=".conf,.rsc,.txt,text/plain"
|
||||
className="sr-only"
|
||||
onChange={(e) => onFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</label>
|
||||
<textarea
|
||||
className="min-h-40 w-full rounded-md border border-input bg-transparent px-3 py-2 font-mono text-xs leading-relaxed outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
|
||||
placeholder={"[Interface]\nPrivateKey = …\n…\n\nили\n\n/interface wireguard add …"}
|
||||
value={content}
|
||||
onChange={(e) => {
|
||||
setContent(e.target.value)
|
||||
setPreview(null)
|
||||
setParseError(null)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="outline" size="sm" onClick={runPreview} disabled={!content.trim()}>
|
||||
Предпросмотр
|
||||
</Button>
|
||||
|
||||
{parseError && <p className="text-sm text-destructive">{parseError}</p>}
|
||||
|
||||
{preview && (
|
||||
<div className="rounded-lg border border-border bg-muted/20 px-4 py-3 text-sm flex flex-col gap-2">
|
||||
<p className="font-medium">
|
||||
{preview.format.toUpperCase()} · {preview.interface.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
port={preview.interface.listenPort ?? "—"} · mtu={preview.interface.mtu ?? "—"}
|
||||
{preview.interface.address ? ` · ${preview.interface.address}` : ""}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">Пиров: {preview.peers.length}</p>
|
||||
{preview.peers.slice(0, 5).map((p, i) => (
|
||||
<p key={i} className="text-[11px] font-mono text-muted-foreground truncate">
|
||||
{p.publicKey.slice(0, 16)}… → {p.allowedAddresses.join(", ")}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SheetFooter className="px-6 py-4 border-t shrink-0 flex-col gap-2 sm:flex-col">
|
||||
<div className="flex w-full gap-2">
|
||||
<SheetClose render={<Button variant="outline" className="flex-1" disabled={busy} />}>
|
||||
Отмена
|
||||
</SheetClose>
|
||||
<Button
|
||||
className="flex-1"
|
||||
disabled={!serverId || !content.trim() || busy}
|
||||
onClick={() => void onImport({ serverId, content, format, dryRun: false })}
|
||||
>
|
||||
{busy ? "Импорт…" : "Применить на роутер"}
|
||||
</Button>
|
||||
</div>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
export { WgImportSheet }
|
||||
@@ -0,0 +1,114 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { FormField, SectionTitle } from "@/components/form-kit"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
Sheet, SheetContent, SheetHeader, SheetTitle,
|
||||
SheetDescription, SheetFooter, SheetClose,
|
||||
} from "@/components/ui/sheet"
|
||||
import type { WgIfaceWithServer } from "@/components/data-grids/wireguard-data-grid"
|
||||
|
||||
export type WgPeerFormState = {
|
||||
publicKey: string
|
||||
allowedIps: string
|
||||
endpoint: string
|
||||
keepalive: string
|
||||
comment: string
|
||||
}
|
||||
|
||||
const emptyPeerForm = (): WgPeerFormState => ({
|
||||
publicKey: "",
|
||||
allowedIps: "",
|
||||
endpoint: "",
|
||||
keepalive: "25",
|
||||
comment: "",
|
||||
})
|
||||
|
||||
function WgPeerSheet({
|
||||
open,
|
||||
iface,
|
||||
busy,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: {
|
||||
open: boolean
|
||||
iface: WgIfaceWithServer | null
|
||||
busy?: boolean
|
||||
onOpenChange: (v: boolean) => void
|
||||
onSubmit: (form: WgPeerFormState) => void | Promise<void>
|
||||
}) {
|
||||
const [form, setForm] = useState<WgPeerFormState>(emptyPeerForm)
|
||||
const set = <K extends keyof WgPeerFormState>(k: K, v: WgPeerFormState[K]) =>
|
||||
setForm((f) => ({ ...f, [k]: v }))
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
open={open}
|
||||
onOpenChange={(v) => {
|
||||
if (v) setForm(emptyPeerForm())
|
||||
onOpenChange(v)
|
||||
}}
|
||||
>
|
||||
<SheetContent side="right" className="w-full sm:max-w-md flex flex-col gap-0 p-0">
|
||||
<SheetHeader className="px-6 pt-6 pb-4 border-b shrink-0">
|
||||
<SheetTitle>Добавить пира</SheetTitle>
|
||||
<SheetDescription>
|
||||
{iface ? `${iface.name} · ${iface.serverName}` : "WireGuard peer"}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex-1 overflow-y-auto px-6 py-5 flex flex-col gap-4">
|
||||
<SectionTitle>Параметры пира</SectionTitle>
|
||||
<FormField label="Public key" required>
|
||||
<Input
|
||||
className="font-mono text-xs"
|
||||
value={form.publicKey}
|
||||
onChange={(e) => set("publicKey", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Allowed IPs" required hint="Через запятую">
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="10.210.0.2/32"
|
||||
value={form.allowedIps}
|
||||
onChange={(e) => set("allowedIps", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Endpoint" hint="host:port">
|
||||
<Input
|
||||
className="font-mono"
|
||||
placeholder="1.2.3.4:13231"
|
||||
value={form.endpoint}
|
||||
onChange={(e) => set("endpoint", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Keepalive (сек)">
|
||||
<Input
|
||||
className="font-mono"
|
||||
value={form.keepalive}
|
||||
onChange={(e) => set("keepalive", e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Комментарий">
|
||||
<Input value={form.comment} onChange={(e) => set("comment", e.target.value)} />
|
||||
</FormField>
|
||||
</div>
|
||||
<SheetFooter className="px-6 py-4 border-t shrink-0 flex-row gap-2">
|
||||
<SheetClose render={<Button variant="outline" className="flex-1" disabled={busy} />}>
|
||||
Отмена
|
||||
</SheetClose>
|
||||
<Button
|
||||
className="flex-1"
|
||||
disabled={busy || !form.publicKey.trim() || !form.allowedIps.trim()}
|
||||
onClick={() => void onSubmit(form)}
|
||||
>
|
||||
{busy ? "Сохранение…" : "Добавить"}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
export { WgPeerSheet }
|
||||
@@ -0,0 +1,79 @@
|
||||
# UI Design Contract (MikrotikManager)
|
||||
|
||||
Surface: **ReUI Frame**. Kit: `components/reui-kit/`.
|
||||
Иерархия: **ReUI PRO > shadcn primitives**.
|
||||
Стек: Next.js 16 App Router + Turbopack + shadcn **base-nova** + ReUI `@reui`.
|
||||
|
||||
Карта: [docs](https://reui.io/docs) · [llms.txt](https://reui.io/llms.txt) · [Get Started](https://reui.io/docs/get-started) · [Styling](https://reui.io/docs/styling) · [Blocks](https://reui.io/blocks) · [MCP](https://reui.io/docs/mcp)
|
||||
|
||||
## Surface
|
||||
|
||||
Project lock: **`surface: frame`**. Ops / list / dashboard / detail / settings — только **Frame**, не shadcn Card как page shell. Не смешивать Card и Frame на одном ops-экране.
|
||||
|
||||
Эталон CRUD: [`app/(main)/servers`](../app/(main)/servers).
|
||||
Оболочка списков: `DataPageCard` → Frame. Панели: `OpsPanel` → Frame.
|
||||
|
||||
## Canonical PRO references
|
||||
|
||||
| Зона | Preview |
|
||||
|------|---------|
|
||||
| Shell | https://reui.io/preview/base/app-shell-12 |
|
||||
| KPI | https://reui.io/preview/base/stats-12 · https://reui.io/docs/components/base/icon-tile |
|
||||
| Lists | https://reui.io/preview/base/data-grid-filtering-2 |
|
||||
| Settings | https://reui.io/preview/base/settings-16 · https://reui.io/preview/base/settings-3 |
|
||||
| Forms / Sheet | https://reui.io/preview/base/form-7 · https://reui.io/preview/base/sheet-8 |
|
||||
| Alert / Badge | https://reui.io/docs/components/base/alert · https://reui.io/docs/components/base/badge |
|
||||
| Empty | https://reui.io/preview/base/empty-state-12 |
|
||||
|
||||
## Kit (`components/reui-kit/`)
|
||||
|
||||
| Component | Role |
|
||||
|-----------|------|
|
||||
| `KpiStatGrid` | Hybrid KPI (IconTile elevated `size-10.5`) |
|
||||
| `CodeExportSheet` | Экспорт кода (.rsc / .conf) — Sheet + Frame + ScrollArea |
|
||||
|
||||
Слои:
|
||||
|
||||
| Слой | Путь |
|
||||
|------|------|
|
||||
| shadcn | `components/ui/` |
|
||||
| ReUI CLI | `components/reui/` |
|
||||
| Kit | `components/reui-kit/` |
|
||||
| Domain grids | `components/data-grids/` |
|
||||
|
||||
## Shared App Shell chrome
|
||||
|
||||
| Токен / зона | Значение |
|
||||
|--------------|----------|
|
||||
| `--sidebar-width` | `240px` |
|
||||
| Header right | AppsMenu → SystemMonitorPopover (тема — в NavUser) |
|
||||
| Search | ⌘K / Ctrl+K only |
|
||||
| `main` | `gap-4 md:gap-6`, `px-4 py-4 md:px-6 md:py-5` |
|
||||
|
||||
## Spacing & tokens
|
||||
|
||||
- `flex` + `gap-*` — не `space-y-*` / `space-x-*`
|
||||
- Semantic tokens / ReUI Badge variants — не raw `bg-emerald-*` / hex
|
||||
- Max 1 primary CTA на экран
|
||||
|
||||
## Exceptions (не Frame ops shell)
|
||||
|
||||
- `network-map` — canvas / topology UX
|
||||
- `terminal` — terminal chrome
|
||||
|
||||
## Forbidden
|
||||
|
||||
- Card как ops list/dashboard shell
|
||||
- Hand-roll data-grid / KPI / code-export при наличии kit
|
||||
- Дубль Copy в header + footer export sheet
|
||||
- Mixing Card и Frame на одном ops-экране
|
||||
- Radix-варианты docs — только Base UI (`base-nova`)
|
||||
|
||||
## License
|
||||
|
||||
```env
|
||||
# .env.local (gitignored)
|
||||
REUI_LICENSE_KEY=
|
||||
```
|
||||
|
||||
`components.json` → `@reui` с `Authorization: Bearer ${REUI_LICENSE_KEY}`.
|
||||
+12
@@ -14,21 +14,33 @@ export interface WanUplink {
|
||||
// ─── WireGuard ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface WireGuardPeer {
|
||||
id?: string
|
||||
rosId?: string
|
||||
publicKey: string
|
||||
allowedIps: string[]
|
||||
endpoint?: string // "1.2.3.4:13231"
|
||||
latestHandshake?: string // "2 минуты назад"
|
||||
transferRx?: number // bytes
|
||||
transferTx?: number // bytes
|
||||
persistentKeepalive?: number
|
||||
persistent?: boolean
|
||||
comment?: string
|
||||
disabled?: boolean
|
||||
name?: string
|
||||
clientAddress?: string
|
||||
clientDns?: string
|
||||
clientEndpoint?: string
|
||||
}
|
||||
|
||||
export interface WireGuardInterface {
|
||||
id: string
|
||||
rosId?: string
|
||||
name: string // e.g. "wg-msk-spb"
|
||||
listenPort: number // default 13231
|
||||
mtu: number // 1420 default in ROS 7.x
|
||||
publicKey?: string
|
||||
privateKey?: string
|
||||
address?: string
|
||||
peers: WireGuardPeer[]
|
||||
comment: string
|
||||
enabled: boolean
|
||||
|
||||
@@ -52,4 +52,6 @@ export interface SidebarCountsDto {
|
||||
uptimeSpeedProbes: number
|
||||
monitoringItems: number
|
||||
recursiveRoutes: number
|
||||
certificates?: number
|
||||
wireguard?: number
|
||||
}
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
/**
|
||||
* Client-side WireGuard config codecs (mirror of backend wireguard-config).
|
||||
* Used for mock preview / offline export without hitting the API.
|
||||
*/
|
||||
|
||||
export type WgParsedPeer = {
|
||||
publicKey: string
|
||||
allowedAddresses: string[]
|
||||
endpointAddress?: string
|
||||
endpointPort?: number
|
||||
persistentKeepalive?: number
|
||||
comment?: string
|
||||
name?: string
|
||||
privateKey?: 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> = {}
|
||||
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 {
|
||||
currentPeer.endpointAddress = value
|
||||
}
|
||||
} else if (key === "persistentkeepalive") {
|
||||
currentPeer.persistentKeepalive = Number.parseInt(value, 10) || undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
flushPeer()
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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): string {
|
||||
const lines: string[] = []
|
||||
lines.push(`[Interface]`)
|
||||
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 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 \\`)
|
||||
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")
|
||||
}
|
||||
|
||||
export function generatePeerClientConf(args: {
|
||||
peerAddress?: string
|
||||
peerDns?: string
|
||||
serverPublicKey: string
|
||||
allowedIps?: string[]
|
||||
endpoint?: string
|
||||
persistentKeepalive?: number
|
||||
}): string {
|
||||
const lines: string[] = []
|
||||
lines.push(`[Interface]`)
|
||||
lines.push(`# 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")
|
||||
}
|
||||
Generated
+15
@@ -13875,6 +13875,21 @@
|
||||
"dependencies": {
|
||||
"zod": "^4.4.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-x64-msvc": {
|
||||
"version": "16.2.4",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.2.4.tgz",
|
||||
"integrity": "sha512-kMVGgsqhO5YTYODD9IPGGhA6iprWidQckK3LmPeW08PIFENRmgfb4MjXHO+p//d+ts2rpjvK5gXWzXSMrPl9cw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,10 @@
|
||||
"./backups": {
|
||||
"types": "./dist/backups.d.ts",
|
||||
"default": "./dist/backups.js"
|
||||
},
|
||||
"./wireguard": {
|
||||
"types": "./dist/wireguard.d.ts",
|
||||
"default": "./dist/wireguard.js"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -3,3 +3,4 @@ export * from "./alerts.js"
|
||||
export * from "./events.js"
|
||||
export * from "./certificates.js"
|
||||
export * from "./backups.js"
|
||||
export * from "./wireguard.js"
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const wgStatusSchema = z.enum(["up", "down"])
|
||||
|
||||
export const wgPeerDtoSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
rosId: z.string().min(1),
|
||||
publicKey: z.string(),
|
||||
allowedIps: z.array(z.string()),
|
||||
endpoint: z.string().optional(),
|
||||
latestHandshake: z.string().optional(),
|
||||
transferRx: z.number().nonnegative().optional(),
|
||||
transferTx: z.number().nonnegative().optional(),
|
||||
persistentKeepalive: z.number().int().nonnegative().optional(),
|
||||
persistent: z.boolean().optional(),
|
||||
comment: z.string().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
name: z.string().optional(),
|
||||
clientAddress: z.string().optional(),
|
||||
clientDns: z.string().optional(),
|
||||
clientEndpoint: z.string().optional(),
|
||||
})
|
||||
|
||||
export const wgIfaceDtoSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
rosId: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
serverId: z.string().min(1),
|
||||
serverName: z.string(),
|
||||
serverCountry: z.string().optional(),
|
||||
listenPort: z.number().int().positive(),
|
||||
mtu: z.number().int().positive(),
|
||||
publicKey: z.string().optional(),
|
||||
privateKey: z.string().optional(),
|
||||
address: z.string().optional(),
|
||||
peers: z.array(wgPeerDtoSchema),
|
||||
comment: z.string(),
|
||||
enabled: z.boolean(),
|
||||
status: wgStatusSchema,
|
||||
})
|
||||
|
||||
export const wgListResponseSchema = z.object({
|
||||
interfaces: z.array(wgIfaceDtoSchema),
|
||||
failures: z
|
||||
.array(
|
||||
z.object({
|
||||
serverId: z.string(),
|
||||
serverName: z.string().optional(),
|
||||
error: z.string(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
|
||||
export const wgCreatePeerSchema = z.object({
|
||||
publicKey: z.string().min(1),
|
||||
allowedAddresses: z.array(z.string().min(1)).min(1),
|
||||
endpointAddress: z.string().optional(),
|
||||
endpointPort: z.number().int().positive().optional(),
|
||||
persistentKeepalive: z.number().int().nonnegative().optional(),
|
||||
comment: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
privateKey: z.enum(["auto", "none"]).or(z.string().min(1)).optional(),
|
||||
clientAddress: z.string().optional(),
|
||||
clientDns: z.string().optional(),
|
||||
clientEndpoint: z.string().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export const wgCreateInterfaceSchema = z.object({
|
||||
serverId: z.union([z.string(), z.number()]),
|
||||
name: z.string().min(1).max(64),
|
||||
listenPort: z.number().int().positive().default(13231),
|
||||
mtu: z.number().int().positive().default(1420),
|
||||
comment: z.string().optional(),
|
||||
privateKey: z.string().min(1).optional(),
|
||||
address: z.string().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
peer: wgCreatePeerSchema.optional(),
|
||||
})
|
||||
|
||||
export const wgPatchInterfaceSchema = z.object({
|
||||
name: z.string().min(1).max(64).optional(),
|
||||
listenPort: z.number().int().positive().optional(),
|
||||
mtu: z.number().int().positive().optional(),
|
||||
comment: z.string().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
privateKey: z.string().min(1).optional(),
|
||||
})
|
||||
|
||||
export const wgCreatePeerRequestSchema = wgCreatePeerSchema.extend({
|
||||
serverId: z.union([z.string(), z.number()]),
|
||||
interfaceName: z.string().min(1),
|
||||
})
|
||||
|
||||
export const wgPatchPeerSchema = z.object({
|
||||
publicKey: z.string().min(1).optional(),
|
||||
allowedAddresses: z.array(z.string().min(1)).min(1).optional(),
|
||||
endpointAddress: z.string().optional(),
|
||||
endpointPort: z.number().int().positive().optional(),
|
||||
persistentKeepalive: z.number().int().nonnegative().optional(),
|
||||
comment: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
clientAddress: z.string().optional(),
|
||||
clientDns: z.string().optional(),
|
||||
clientEndpoint: z.string().optional(),
|
||||
})
|
||||
|
||||
export const wgImportFormatSchema = z.enum(["auto", "rsc", "conf"])
|
||||
|
||||
export const wgImportRequestSchema = z.object({
|
||||
serverId: z.union([z.string(), z.number()]),
|
||||
content: z.string().min(1),
|
||||
format: wgImportFormatSchema.optional().default("auto"),
|
||||
dryRun: z.boolean().optional().default(false),
|
||||
})
|
||||
|
||||
export const wgExportFormatSchema = z.enum(["rsc", "conf", "peer-conf"])
|
||||
|
||||
export const wgExportRequestSchema = z.object({
|
||||
serverId: z.union([z.string(), z.number()]),
|
||||
interfaceName: z.string().min(1),
|
||||
format: wgExportFormatSchema,
|
||||
peerId: z.string().optional(),
|
||||
includePrivateKey: z.boolean().optional().default(false),
|
||||
})
|
||||
|
||||
export const wgImportPreviewSchema = z.object({
|
||||
format: z.enum(["rsc", "conf"]),
|
||||
interface: z.object({
|
||||
name: z.string(),
|
||||
listenPort: z.number().int().positive().optional(),
|
||||
mtu: z.number().int().positive().optional(),
|
||||
privateKey: z.string().optional(),
|
||||
comment: z.string().optional(),
|
||||
address: z.string().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
}),
|
||||
peers: z.array(wgCreatePeerSchema),
|
||||
})
|
||||
|
||||
export const wgImportResponseSchema = z.object({
|
||||
dryRun: z.boolean(),
|
||||
preview: wgImportPreviewSchema,
|
||||
applied: z
|
||||
.object({
|
||||
interfaceName: z.string(),
|
||||
peersCreated: z.number().int().nonnegative(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
|
||||
export const wgExportResponseSchema = z.object({
|
||||
format: wgExportFormatSchema,
|
||||
filename: z.string(),
|
||||
content: z.string(),
|
||||
})
|
||||
|
||||
export type WgPeerDto = z.infer<typeof wgPeerDtoSchema>
|
||||
export type WgIfaceDto = z.infer<typeof wgIfaceDtoSchema>
|
||||
export type WgListResponse = z.infer<typeof wgListResponseSchema>
|
||||
export type WgCreateInterface = z.infer<typeof wgCreateInterfaceSchema>
|
||||
export type WgPatchInterface = z.infer<typeof wgPatchInterfaceSchema>
|
||||
export type WgCreatePeerRequest = z.infer<typeof wgCreatePeerRequestSchema>
|
||||
export type WgPatchPeer = z.infer<typeof wgPatchPeerSchema>
|
||||
export type WgImportRequest = z.infer<typeof wgImportRequestSchema>
|
||||
export type WgExportRequest = z.infer<typeof wgExportRequestSchema>
|
||||
export type WgImportPreview = z.infer<typeof wgImportPreviewSchema>
|
||||
export type WgImportResponse = z.infer<typeof wgImportResponseSchema>
|
||||
export type WgExportResponse = z.infer<typeof wgExportResponseSchema>
|
||||
@@ -0,0 +1,107 @@
|
||||
import type {
|
||||
WgCreateInterface,
|
||||
WgCreatePeerRequest,
|
||||
WgExportRequest,
|
||||
WgExportResponse,
|
||||
WgImportRequest,
|
||||
WgImportResponse,
|
||||
WgListResponse,
|
||||
WgPatchInterface,
|
||||
WgPatchPeer,
|
||||
} from "@mmapp/contracts/wireguard"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export async function listWireGuard(
|
||||
baseUrl: string,
|
||||
opts?: { serverId?: string; includePrivateKey?: boolean },
|
||||
): Promise<WgListResponse> {
|
||||
const q = new URLSearchParams()
|
||||
if (opts?.serverId) q.set("serverId", opts.serverId)
|
||||
if (opts?.includePrivateKey) q.set("includePrivateKey", "1")
|
||||
const qs = q.toString()
|
||||
return requestJson<WgListResponse>(baseUrl, `/api/wireguard${qs ? `?${qs}` : ""}`)
|
||||
}
|
||||
|
||||
export async function createWireGuardInterface(
|
||||
baseUrl: string,
|
||||
payload: WgCreateInterface,
|
||||
): Promise<unknown> {
|
||||
return requestJson(baseUrl, "/api/wireguard/interfaces", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function patchWireGuardInterface(
|
||||
baseUrl: string,
|
||||
serverId: string,
|
||||
rosId: string,
|
||||
payload: WgPatchInterface,
|
||||
): Promise<{ ok: boolean }> {
|
||||
return requestJson(baseUrl, `/api/wireguard/interfaces/${encodeURIComponent(serverId)}/${encodeURIComponent(rosId)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteWireGuardInterface(
|
||||
baseUrl: string,
|
||||
serverId: string,
|
||||
rosId: string,
|
||||
): Promise<{ ok: boolean }> {
|
||||
return requestJson(baseUrl, `/api/wireguard/interfaces/${encodeURIComponent(serverId)}/${encodeURIComponent(rosId)}`, {
|
||||
method: "DELETE",
|
||||
})
|
||||
}
|
||||
|
||||
export async function createWireGuardPeer(
|
||||
baseUrl: string,
|
||||
payload: WgCreatePeerRequest,
|
||||
): Promise<{ ok: boolean }> {
|
||||
return requestJson(baseUrl, "/api/wireguard/peers", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function patchWireGuardPeer(
|
||||
baseUrl: string,
|
||||
serverId: string,
|
||||
rosId: string,
|
||||
payload: WgPatchPeer,
|
||||
): Promise<{ ok: boolean }> {
|
||||
return requestJson(baseUrl, `/api/wireguard/peers/${encodeURIComponent(serverId)}/${encodeURIComponent(rosId)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteWireGuardPeer(
|
||||
baseUrl: string,
|
||||
serverId: string,
|
||||
rosId: string,
|
||||
): Promise<{ ok: boolean }> {
|
||||
return requestJson(baseUrl, `/api/wireguard/peers/${encodeURIComponent(serverId)}/${encodeURIComponent(rosId)}`, {
|
||||
method: "DELETE",
|
||||
})
|
||||
}
|
||||
|
||||
export async function importWireGuard(
|
||||
baseUrl: string,
|
||||
payload: WgImportRequest,
|
||||
): Promise<WgImportResponse> {
|
||||
return requestJson(baseUrl, "/api/wireguard/import", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export async function exportWireGuard(
|
||||
baseUrl: string,
|
||||
payload: WgExportRequest,
|
||||
): Promise<WgExportResponse> {
|
||||
return requestJson(baseUrl, "/api/wireguard/export", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user