diff --git a/app/(main)/ipsec/page.tsx b/app/(main)/ipsec/page.tsx index cac40f17..a13dd808 100644 --- a/app/(main)/ipsec/page.tsx +++ b/app/(main)/ipsec/page.tsx @@ -53,6 +53,7 @@ import { patchIpsecUser, restoreIpsecRevision, } from "@/shared/api/ipsec" +import type { IpsecExistingCertExportOptions } from "@/shared/api/ipsec" import type { IpsecCertBundle, IpsecCertInfoDto, @@ -203,7 +204,12 @@ function IpsecPage({ selectedServerId, setSelectedServerId, workspaceTab, setWor const [certError, setCertError] = useState(null) const certEpoch = useRef(0) const certPending = useRef(false) - useEffect(() => () => { certEpoch.current += 1 }, []) + const certFailedAttempts = useRef(new Set()) + const certActive = useRef<{ targetKey: string; controller: AbortController } | null>(null) + const [certAttemptFailed, setCertAttemptFailed] = useState(false) + const [certRole, setCertRole] = useState("client") + const [certSession, setCertSession] = useState(0) + useEffect(() => () => { certEpoch.current += 1; certActive.current?.controller.abort() }, []) const [search, setSearch] = useState("") const [initOpen, setInitOpen] = useState(false) @@ -460,6 +466,9 @@ function IpsecPage({ selectedServerId, setSelectedServerId, workspaceTab, setWor setCertBundle(res.bundle) setCertClient(res.client ?? null) setCertByName(null) + setCertRole("client") + setCertAttemptFailed(false) + setCertSession(session => session + 1) setCertOpen(true) } } finally { @@ -487,52 +496,71 @@ function IpsecPage({ selectedServerId, setSelectedServerId, workspaceTab, setWor } } - const loadCert = async (serverId: string, request: () => Promise) => { + const loadCert = async (serverId: string, targetKey: string, request: (signal: AbortSignal) => Promise) => { if (certPending.current) return certPending.current = true + const controller = new AbortController() + certActive.current = { targetKey, controller } const epoch = ++certEpoch.current setCertBusy(true) setCertError(null) try { assertDeviceReady(serverId) - const bundle = await request() - if (epoch === certEpoch.current) setCertBundle(bundle) + const bundle = await request(controller.signal) + if (epoch === certEpoch.current) { + setCertBundle(bundle) + certFailedAttempts.current.delete(targetKey) + setCertAttemptFailed(false) + } } catch (error) { - if (epoch === certEpoch.current) setCertError(error instanceof Error ? error.message : "Ошибка экспорта сертификата") + certFailedAttempts.current.add(targetKey) + if (epoch === certEpoch.current) { + setCertAttemptFailed(true) + setCertError(error instanceof Error ? error.message : "Ошибка экспорта сертификата") + } } finally { - if (epoch === certEpoch.current) { certPending.current = false; setCertBusy(false) } + if (epoch === certEpoch.current) { certPending.current = false; certActive.current = null; setCertBusy(false) } } } - const openCert = async (client: IpsecClientDto) => { - const byName = client.kind === "cert" && Boolean(client.certName) + const openCert = (client: IpsecClientDto) => { + if (certPending.current) return + const byName = !client.rosId.startsWith("identity:") && client.kind === "cert" && Boolean(client.certName) + const targetKey = JSON.stringify([client.serverId, byName ? "certificate" : "client", byName ? client.certName : client.rosId]) certEpoch.current += 1 certPending.current = false setCertClient(byName ? null : client) setCertByName(byName ? { serverId: client.serverId, name: client.certName! } : null) setCertBundle(null) + setCertError(null) + setCertAttemptFailed(certFailedAttempts.current.has(targetKey)) + setCertRole(summaries.find(summary => summary.serverId === client.serverId)?.certs?.find(cert => cert.name === client.certName)?.role ?? "client") + setCertSession(session => session + 1) setCertOpen(true) - const passphrase = crypto.randomUUID() - await loadCert(client.serverId, () => byName - ? exportIpsecCertByName(backendUrl, client.serverId, client.certName!, passphrase) - : exportIpsecUserCert(backendUrl, client.serverId, client.rosId, passphrase)) } - const openCertByName = async (serverId: string, cert: IpsecCertInfoDto) => { + const openCertByName = (serverId: string, cert: IpsecCertInfoDto) => { + if (certPending.current) return certEpoch.current += 1 certPending.current = false setCertByName({ serverId, name: cert.name }) setCertClient(null) setCertBundle(null) + setCertError(null) + setCertAttemptFailed(certFailedAttempts.current.has(JSON.stringify([serverId, "certificate", cert.name]))) + setCertRole(cert.role ?? "other") + setCertSession(session => session + 1) setCertOpen(true) - await loadCert(serverId, () => exportIpsecCertByName(backendUrl, serverId, cert.name, crypto.randomUUID())) } - const reexportCert = async (passphrase: string) => { + const reexportCert = async (passphrase: string, options: IpsecExistingCertExportOptions) => { if (!certClient && !certByName) return - await loadCert(certByName?.serverId ?? certClient!.serverId, () => certByName - ? exportIpsecCertByName(backendUrl, certByName.serverId, certByName.name, passphrase) - : exportIpsecUserCert(backendUrl, certClient!.serverId, certClient!.rosId, passphrase)) + if (options.privateKeyExport !== true || (certRole === "ca" && !options.caPrivateKeyExport)) return + const serverId = certByName?.serverId ?? certClient!.serverId + const targetKey = JSON.stringify([serverId, certByName ? "certificate" : "client", certByName?.name ?? certClient!.rosId]) + await loadCert(serverId, targetKey, signal => certByName + ? exportIpsecCertByName(backendUrl, certByName.serverId, certByName.name, passphrase, options, { signal }) + : exportIpsecUserCert(backendUrl, certClient!.serverId, certClient!.rosId, passphrase, options, { signal })) } const deletingCertificateIdentity = pendingDelete?.kind === "user" && pendingDelete.client.kind === "cert" && pendingDelete.client.rosId.startsWith("identity:") @@ -919,14 +947,25 @@ function IpsecPage({ selectedServerId, setSelectedServerId, workspaceTab, setWor /> { - if (!v) { certEpoch.current += 1; certPending.current = false; setCertBusy(false); setCertBundle(null); setCertClient(null); setCertByName(null) } + if (!v) { + if (certActive.current) { + certFailedAttempts.current.add(certActive.current.targetKey) + certActive.current.controller.abort() + certActive.current = null + } + certEpoch.current += 1; certPending.current = false; setCertBusy(false); setCertBundle(null); setCertClient(null); setCertByName(null) + } setCertOpen(v) }} error={certError} bundle={certBundle} busy={certBusy} + certificateRole={certRole} + targetName={certByName?.name ?? certClient?.certName ?? certClient?.name} + previousAttemptFailed={certAttemptFailed} onReexport={reexportCert} /> diff --git a/app/(main)/mcp/page.tsx b/app/(main)/mcp/page.tsx new file mode 100644 index 00000000..4dc14875 --- /dev/null +++ b/app/(main)/mcp/page.tsx @@ -0,0 +1,6 @@ +import { Suspense } from "react" +import { McpWorkspace } from "@/components/mcp/mcp-workspace" + +export default function McpPage() { + return Загрузка MCP…

}>
+} diff --git a/app/(main)/traffic/page.tsx b/app/(main)/traffic/page.tsx index aa6fef19..b6da6a9a 100644 --- a/app/(main)/traffic/page.tsx +++ b/app/(main)/traffic/page.tsx @@ -924,18 +924,21 @@ export default function TrafficPage() { }) return () => { cancelled = true } } - void Promise.all([ - getTrafficFlows(backendUrl, range), - getFlowExporters(backendUrl, range), - getFlowClients(backendUrl, range), - ]).then(([stats, exporters, clients]) => { + const loadFlowCards = async () => { + // These reads share the collector's constrained admission budget. + const stats = await getTrafficFlows(backendUrl, range) + if (cancelled) return + const exporters = await getFlowExporters(backendUrl, range) + if (cancelled) return + const clients = await getFlowClients(backendUrl, range) if (cancelled) return setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients }) setSelectedId(prev => { const list = flowScope === "users" ? clients.clients : exporters.exporters return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "") }) - }).catch(e => { + } + void loadFlowCards().catch(e => { if (!cancelled) setFlowResult({ key: flowKey, error: e instanceof Error ? e.message : "Не удалось загрузить потоки" }) }) return () => { cancelled = true } diff --git a/app/(main)/users/page.tsx b/app/(main)/users/page.tsx index 8e561cde..55186232 100644 --- a/app/(main)/users/page.tsx +++ b/app/(main)/users/page.tsx @@ -74,6 +74,7 @@ function UsersContent() { const isLive = mode === "live" const canRead = can("mm:users:read") const canWrite = can("mm:users:write") + const canManagePermissions = !isLive || can("mm:settings:admin") const canReadServers = can("mm:servers:read") const [users, setUsers] = useState(() => isLive ? [] : INIT_USERS) @@ -184,8 +185,8 @@ function UsersContent() { setSaving(true); setSaveError(null); setOperationNotice(null) try { const saved = await saveUserSteps(form, checkpoint, { - create: f => createAppUser(backendUrl, userProfileRequest(f), init()), - update: (id, f) => updateAppUser(backendUrl, id, userProfileRequest(f), init()), + create: f => createAppUser(backendUrl, userProfileRequest(f, canManagePermissions), init()), + update: (id, f) => updateAppUser(backendUrl, id, userProfileRequest(f, canManagePermissions), init()), read: id => getAppUser(backendUrl, id, init()), removeBinding: (userId, id) => deleteUserBinding(backendUrl, userId, id, init()), addBinding: (userId, b) => createUserBinding(backendUrl, userId, { @@ -328,6 +329,7 @@ function UsersContent() { users={users} servers={serverOptions} isLive={isLive} + canManagePermissions={canManagePermissions} backendUrl={backendUrl} saving={saving} saveError={saveError} diff --git a/app/globals.css b/app/globals.css index ae204b9d..31af6717 100644 --- a/app/globals.css +++ b/app/globals.css @@ -1,7 +1,16 @@ -@import "tailwindcss"; +@import "tailwindcss" source(none); @import "tw-animate-css"; @import "shadcn/tailwind.css"; +/* Scan application sources only; local test archives and generated bundles + must not become utility classes in the production stylesheet. */ +@source "./"; +@source "../components"; +@source "../entities"; +@source "../hooks"; +@source "../lib"; +@source "../shared"; + /* SVG focus follows the object shape, never the text/foreignObject bounding box. */ .network-map-focusable { outline: none; diff --git a/components/auth-guard.tsx b/components/auth-guard.tsx index f728982c..6616310f 100644 --- a/components/auth-guard.tsx +++ b/components/auth-guard.tsx @@ -1,17 +1,22 @@ "use client" import { useEffect, useState, type ReactNode } from "react" +import { usePathname } from "next/navigation" import { + can, ensureAuthConfig, getClaims, getToken, isAuthEnabled, + permissionForPath, redirectToPortalLogin, redirectToPortalLoginInteractive, } from "@/lib/auth" export function AuthGuard({ children }: { children: ReactNode }) { + const pathname = usePathname() const [ready, setReady] = useState(false) + const permission = pathname ? permissionForPath(pathname) : null useEffect(() => { let cancelled = false @@ -28,7 +33,7 @@ export function AuthGuard({ children }: { children: ReactNode }) { if (!ok) redirectToPortalLoginInteractive() return } - if (!claims.apps.includes("mm")) { + if (!claims.apps.includes("mm") || (permission && !can(permission))) { window.location.assign("/access-denied") return } @@ -37,9 +42,9 @@ export function AuthGuard({ children }: { children: ReactNode }) { return () => { cancelled = true } - }, []) + }, [pathname, permission]) - if (!ready) { + if (!ready || (isAuthEnabled() && (!getToken() || !getClaims()?.apps.includes("mm") || (permission && !can(permission))))) { return (
Проверка сессии… diff --git a/components/data-grids/users-expanded-detail.tsx b/components/data-grids/users-expanded-detail.tsx index ecef71cd..9a641dd2 100644 --- a/components/data-grids/users-expanded-detail.tsx +++ b/components/data-grids/users-expanded-detail.tsx @@ -16,6 +16,9 @@ import { CableIcon, KeyRoundIcon, LockIcon, NetworkIcon, ShieldIcon } from "luci const TYPE_VARIANT: Record = { ether: "outline", + bridge: "info-light", + vlan: "info-light", + vxlan: "info-light", gre: "info-light", wg: "success-light", ipsec: "info-light", @@ -24,6 +27,9 @@ const TYPE_VARIANT: Record = { ether: { icon: CableIcon, className: "text-muted-foreground" }, + bridge: { icon: NetworkIcon, className: "text-info" }, + vlan: { icon: NetworkIcon, className: "text-info" }, + vxlan: { icon: NetworkIcon, className: "text-info" }, gre: { icon: NetworkIcon, className: "text-info" }, wg: { icon: ShieldIcon, className: "text-success" }, ipsec: { icon: LockIcon, className: "text-info" }, diff --git a/components/flag.tsx b/components/flag.tsx index cf68b998..33348004 100644 --- a/components/flag.tsx +++ b/components/flag.tsx @@ -59,10 +59,17 @@ function nearestCdnSize(px: number): number { return CDN_SIZES.find(s => s >= px) ?? CDN_SIZES[CDN_SIZES.length - 1] } +function flagCode(code: string): string | null { + if (!code) return null + const lower = code.toLowerCase() + // The server catalogue uses UN when the country is unknown. + return lower !== "un" && /^[a-z]{2}$/.test(lower) ? lower : null +} + /** CDN URL for SVG `` (flagcdn widths only). */ export function flagCdnUrl(code: string, size = 40): string | null { - const lower = code.toLowerCase() - if (!/^[a-z]{2}$/.test(lower)) return null + const lower = flagCode(code) + if (!lower) return null return `https://flagcdn.com/w${nearestCdnSize(size)}/${lower}.png` } @@ -71,9 +78,8 @@ export function flagCdnUrl(code: string, size = 40): string | null { * Source: https://flagcdn.com — free CDN, no API key needed. */ export function Flag({ code, size = 20, className }: FlagProps) { - if (!code) return null - const lower = code.toLowerCase() - if (!/^[a-z]{2}$/.test(lower)) return null + const lower = flagCode(code) + if (!lower) return null const name = countryName(code.toUpperCase()) const cdnSrc = nearestCdnSize(size) const cdnSrc2x = nearestCdnSize(size * 2) diff --git a/components/ipsec/ipsec-cert-sheet.tsx b/components/ipsec/ipsec-cert-sheet.tsx index ffd18a8f..93ed4271 100644 --- a/components/ipsec/ipsec-cert-sheet.tsx +++ b/components/ipsec/ipsec-cert-sheet.tsx @@ -1,10 +1,13 @@ "use client" - +import { useRef, useState } from "react" import { IPSEC_MIN_PASSPHRASE, type IpsecCertBundle } from "@mmapp/contracts/ipsec" +import type { IpsecExistingCertExportOptions } from "@/shared/api/ipsec" import { FormField, SectionTitle } from "@/components/form-kit" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" +import { Checkbox } from "@/components/ui/checkbox" +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog" import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetFooter, SheetClose, @@ -48,6 +51,9 @@ function IpsecCertSheet({ busy, error, onReexport, + certificateRole, + targetName, + previousAttemptFailed = false, }: { open: boolean onOpenChange: (v: boolean) => void @@ -55,16 +61,49 @@ function IpsecCertSheet({ busy?: boolean error?: string | null /** Перекачка с новой passphrase (серийник ключа остаётся на роутере). */ - onReexport?: (passphrase: string) => void | Promise + onReexport?: (passphrase: string, options: IpsecExistingCertExportOptions) => void | Promise + certificateRole?: "ca" | "server" | "client" | "other" + targetName?: string + previousAttemptFailed?: boolean }) { + const [confirmationOpen, setConfirmationOpen] = useState(false) + const [privateKeyConfirmed, setPrivateKeyConfirmed] = useState(false) + const [caKeyConfirmed, setCaKeyConfirmed] = useState(false) + const [newAttemptConfirmed, setNewAttemptConfirmed] = useState(false) + const submitting = useRef(false) + const isCa = certificateRole === "ca" + const confirmEnabled = privateKeyConfirmed && (!isCa || caKeyConfirmed) && (!previousAttemptFailed || newAttemptConfirmed) && !busy + const openExportConfirmation = () => { + if (busy || submitting.current) return + setPrivateKeyConfirmed(false) + setCaKeyConfirmed(false) + setNewAttemptConfirmed(false) + setConfirmationOpen(true) + } + const confirmExport = async () => { + if (!confirmEnabled || !onReexport || submitting.current) return + submitting.current = true + setConfirmationOpen(false) + try { + // One key per explicitly confirmed attempt. Nothing retries this call or + // allocates another key after an error, opening, selection, or rendering. + const requestKey = crypto.randomUUID() + await onReexport(randomPassphrase(), { privateKeyExport: true, caPrivateKeyExport: isCa && caKeyConfirmed, requestKey }) + } catch { + toast.error("Экспорт не подтверждён. Перед новой попыткой проверьте состояние роутера.") + } finally { + submitting.current = false + } + } const passphrase = bundle?.passphrase ?? "" const canDownload = Boolean(bundle && !busy && passphrase.trim().length >= IPSEC_MIN_PASSPHRASE) return ( + <> - Сертификат клиента {bundle ? `«${bundle.user}»` : ""} + Сертификат {bundle?.user || targetName ? `«${bundle?.user ?? targetName}»` : ""} .p12 для Windows/macOS/iOS · .sswan для strongSwan (Android/iOS) @@ -73,8 +112,16 @@ function IpsecCertSheet({
{busy &&

Загрузка сертификата…

} {error &&

{error}

} + {previousAttemptFailed && !busy && ( +

Предыдущая попытка завершилась ошибкой; её результат на роутере может быть неизвестен. Проверьте временный файл и состояние экспорта перед новым запросом.

+ )} {!bundle ? ( - !busy && onReexport ? : null + !busy && onReexport ? ( +
+

Экспорт .p12 включает закрытый ключ. Подтвердите его получение перед запросом к роутеру.

+ +
+ ) : null ) : ( <>
@@ -99,13 +146,10 @@ function IpsecCertSheet({ type="button" size="icon" variant="outline" - title="Сгенерировать и перекачать" - aria-label="Сгенерировать и перекачать" + title="Подтвердить экспорт с новым паролем" + aria-label="Подтвердить экспорт с новым паролем" disabled={busy || !onReexport} - onClick={() => { - const next = randomPassphrase() - if (onReexport) void onReexport(next) - }} + onClick={openExportConfirmation} > @@ -180,6 +224,38 @@ function IpsecCertSheet({ + + + + Подтвердить экспорт {isCa ? "CA" : "сертификата"} + Запрос создаст на роутере временный .p12 с закрытым ключом сертификата {targetName ? `«${targetName}»` : ""}, прочитает его и удалит временный файл. Пароль архива будет сгенерирован после подтверждения. + + + {isCa && ( + + )} + {previousAttemptFailed && ( +
+

Результат предыдущего запроса может быть неизвестен. Новый запрос не продолжает и не подтверждает предыдущую попытку.

+ +
+ )} + + + + +
+
+ ) } diff --git a/components/ipsec/ipsec-server-grid.tsx b/components/ipsec/ipsec-server-grid.tsx index 8a576792..51642d91 100644 --- a/components/ipsec/ipsec-server-grid.tsx +++ b/components/ipsec/ipsec-server-grid.tsx @@ -118,7 +118,7 @@ function CertRow({

- {onExport && cert.role === "client" ? ( + {onExport ? (
{range === "custom" &&
{["from", "to"].map(key => )}
} -
{collectorEnabled === undefined ? "Проверяем сборщик" : !collectorEnabled ? "Сборщик выключен" : result.streamError ? "Переподключение" : state?.lastError ? "Ошибка сбора" : live && result.stream ? "Live подключён" : "История"}Последний сбор: {formatLogTime(state?.lastCollectedAt ?? result.summary?.states.map(s => s.lastCollectedAt).filter((s): s is string => !!s).sort().at(-1) ?? null)}{live && }
+
+ {result.streamStopped || result.streamError + ? {result.streamStopped ? "Live остановлен" : "Переподключение"} + : + {collectorEnabled === undefined ? "Проверяем сборщик" : !collectorEnabled ? "Сборщик выключен" : state?.lastError ? "Ошибка сбора" : live && result.stream ? "Live подключён" : "История"} + } + Последний сбор: {formatLogTime(state?.lastCollectedAt ?? result.summary?.states.map(s => s.lastCollectedAt).filter((s): s is string => !!s).sort().at(-1) ?? null)} + {live && } +
+ {live && collectorEnabled === true && result.streamReceivedAt !== null &&

+ Получено (live-поток): +

} {collectorEnabled === false && История доступна, сбор новых событий выключенАдминистратор может включить коллектор в разделе «Сбор данных».} {(result.streamError || state?.lastError) && Live требует внимания{state?.lastError ?? result.streamError}} {state?.gapAt && Возможен разрыв историиБуфер изменился без пересечения с предыдущим снимком: {formatLogTime(state.gapAt)}. Количество недоступных событий неизвестно.} diff --git a/components/mcp/artifact-downloads.tsx b/components/mcp/artifact-downloads.tsx new file mode 100644 index 00000000..affc390d --- /dev/null +++ b/components/mcp/artifact-downloads.tsx @@ -0,0 +1,42 @@ +"use client" + +import { useEffect, useRef, useState } from "react" +import { Button } from "@/components/ui/button" +import { humanArtifactError, humanArtifactReceipt } from "@/shared/api/mcp-artifact" +import type { McpApi } from "@/shared/api/mcp" + +function ArtifactDownload({ api, receipt }: { api: McpApi; receipt: unknown }) { + const [busy, setBusy] = useState(false), [error, setError] = useState(""), [saved, setSaved] = useState(false) + const controller = useRef(null) + useEffect(() => () => controller.current?.abort(), []) + const download = async () => { + if (controller.current) return + const request = new AbortController() + controller.current = request + setBusy(true); setError(""); setSaved(false) + try { await api.downloadArtifact(receipt, request.signal); if (!request.signal.aborted) setSaved(true) } + catch (failure) { if (!request.signal.aborted) setError(humanArtifactError(failure)) } + finally { if (!request.signal.aborted) setBusy(false); controller.current = null } + } + return
+ + {error &&

{error}

} +

{busy ? "Получаем файл с проверкой доступа…" : saved ? "Файл передан браузеру для сохранения." : error ? "" : "Доступ и срок хранения проверяются при скачивании."}

+
+} + +export function ArtifactDownloads({ api, operation }: { api: McpApi; operation: Record }) { + const [hadReceipts, setHadReceipts] = useState(false) + const values = operation.state === "applied" && Array.isArray(operation.artifactReceipts) ? operation.artifactReceipts : [] + const receipts = [...new Map(values.flatMap(value => { + const receipt = humanArtifactReceipt(value) + return receipt ? [[receipt.artifactId, value] as const] : [] + })).entries()] + if (receipts.length && !hadReceipts) setHadReceipts(true) + if (!receipts.length && !hadReceipts) return null + return
+

Файлы операции

+ {receipts.length ? receipts.map(([id, receipt]) => ) : +

Файл больше недоступен. Проверьте срок хранения и права подключения.

} +
+} diff --git a/components/mcp/bridge-vlan-workflow.tsx b/components/mcp/bridge-vlan-workflow.tsx new file mode 100644 index 00000000..a537fe0b --- /dev/null +++ b/components/mcp/bridge-vlan-workflow.tsx @@ -0,0 +1,156 @@ +"use client" + +import { useEffect, useRef, useState } from "react" +import Link from "next/link" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Checkbox } from "@/components/ui/checkbox" +import { bridgeVlanDesiredSchema, type BridgeVlanDesired } from "@mmapp/contracts/bridge-vlan" +import type { McpApi } from "@/shared/api/mcp" + +type Row = Record +type Interface = { resource: string; id: string; name: string; disabled?: unknown } +type State = { bridges: Row[]; ports: Row[]; vlans: Row[]; interfaces: Interface[]; vlanInterfaces: Row[]; ipv4Addresses: Row[]; ipv6Addresses: Row[] } +type Reference = BridgeVlanDesired["ports"][number]["interface"] +const keyOf = (reference: Reference) => `${reference.resource}/${reference.id}` +const dynamic = (row: Row) => [true, "true", "yes"].includes(row.dynamic as boolean | string) +const text = (row: Row, field: string) => String(row[field] ?? "") +function boolean(row: Row, field: string): boolean { + if ([true, "true", "yes"].includes(row[field] as boolean | string)) return true + if ([false, "false", "no"].includes(row[field] as boolean | string)) return false + throw new Error(`Не подтверждено поле ${field} у записи ${text(row, ".id")}`) +} +function Choice({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) { + return +} +const selectClass = "h-9 min-w-0 rounded-md border bg-background px-3 text-sm" + +function draftFor(state: State, bridgeId: string): BridgeVlanDesired { + const bridge = state.bridges.find(row => row[".id"] === bridgeId) + if (!bridge) throw new Error("Выберите существующий мост") + const name = text(bridge, "name") + const reference = (name: string): Reference => { + const matches = state.interfaces.filter(item => item.name === name) + if (matches.length !== 1) throw new Error(`Не подтверждён интерфейс ${name}; обновите состояние`) + return { resource: matches[0].resource, id: matches[0].id } + } + const members = (value: unknown) => { + if (value === undefined || value === "") return [] + if (typeof value !== "string") throw new Error("Не подтверждён список участников VLAN") + return value.split(",").map(name => reference(name.trim())) + } + return bridgeVlanDesiredSchema.parse({ + filtering: boolean(bridge, "vlan-filtering"), pvid: Number(bridge.pvid), + ports: state.ports.filter(row => row.bridge === name && !dynamic(row)).map(row => ({ + id: text(row, ".id"), interface: reference(text(row, "interface")), pvid: Number(row.pvid), + ingressFiltering: boolean(row, "ingress-filtering"), frameTypes: row["frame-types"], disabled: boolean(row, "disabled"), + ...(row.comment !== undefined ? { comment: row.comment } : {}), + })), + vlans: state.vlans.filter(row => row.bridge === name && !dynamic(row)).map(row => ({ + id: text(row, ".id"), vlanIds: text(row, "vlan-ids"), tagged: members(row.tagged), untagged: members(row.untagged), + disabled: boolean(row, "disabled"), ...(row.comment !== undefined ? { comment: row.comment } : {}), + })), removePortIds: [], removeVlanIds: [], + }) +} + +export function BridgeVlanWorkflow({ api, connectionId, serverId }: { api: McpApi; connectionId: string; serverId: string }) { + const [state, setState] = useState(null) + const [bridgeId, setBridgeId] = useState("") + const [draft, setDraft] = useState(null) + const [reload, setReload] = useState(0) + const [loading, setLoading] = useState(true) + const [busy, setBusy] = useState(false) + const [error, setError] = useState("") + const [receipt, setReceipt] = useState("") + const scope = `${connectionId}/${serverId}` + const currentScope = useRef(scope) + const selectedBridge = useRef(bridgeId) + useEffect(() => { + const abort = new AbortController() + currentScope.current = scope + const load = async () => { + await Promise.resolve() + if (abort.signal.aborted) return + setState(null); setDraft(null); setReceipt(""); setError(""); setLoading(true) + try { + if (!connectionId || !serverId) return + const data = await api.bridgeVlanState(connectionId, serverId, abort.signal) + if (abort.signal.aborted) return + setState(data.state) + const selected = data.state.bridges.find(row => row[".id"] === selectedBridge.current) + if (selected) setDraft(draftFor(data.state, String(selected[".id"]))) + else { selectedBridge.current = ""; setBridgeId("") } + } catch (failure) { if (!abort.signal.aborted) setError(failure instanceof Error ? failure.message : "Не удалось прочитать состояние моста") } + finally { if (!abort.signal.aborted) setLoading(false) } + } + void load() + return () => { abort.abort(); currentScope.current = "" } + }, [api, connectionId, serverId, scope, reload]) + const edit = (change: (value: BridgeVlanDesired) => BridgeVlanDesired) => { + setDraft(value => value && change(value)); setReceipt(""); setError("") + } + const chooseBridge = (id: string) => { + selectedBridge.current = id + setBridgeId(id); setReceipt(""); setError(""); setDraft(null) + if (state && id) try { setDraft(draftFor(state, id)) } catch (failure) { setError(failure instanceof Error ? failure.message : "Не удалось загрузить мост") } + } + const prepare = async () => { + if (!draft) return + setBusy(true); setError(""); setReceipt("") + try { + const checked = bridgeVlanDesiredSchema.safeParse(draft) + if (!checked.success) throw new Error("Проверьте PVID (1–4094), диапазоны VLAN и выбранные интерфейсы") + const result = await api.bridgeVlanPlan(connectionId, serverId, bridgeId, checked.data) + if (currentScope.current === scope) setReceipt(result.planId) + } catch (failure) { if (currentScope.current === scope) setError(failure instanceof Error ? failure.message : "Не удалось подготовить план") } + finally { setBusy(false) } + } + const bridgeName = state?.bridges.find(row => row[".id"] === bridgeId)?.name + const options = state?.interfaces ?? [] + const portOptions = options.filter(item => ["ethernet", "vlan", "vxlan"].includes(item.resource) && !state?.ports.some(row => row.interface === item.name && row.bridge !== bridgeName)) + const nextPort = portOptions.find(item => !draft?.ports.some(port => keyOf(port.interface) === keyOf(item))) + const memberOptions = options.filter(item => item.resource === "bridge" && item.id === bridgeId || draft?.ports.some(port => keyOf(port.interface) === keyOf(item))) + const interfaceSelect = (label: string, value: Reference, onChange: (value: Reference) => void) => + const membership = (label: string, selected: Reference[], onChange: (value: Reference[]) => void) =>
{label}
{options.filter(item => memberOptions.includes(item) || selected.some(value => keyOf(value) === keyOf(item))).map(item => keyOf(value) === keyOf(item))} onChange={checked => onChange(checked ? [...selected, { resource: item.resource, id: item.id }] : selected.filter(value => keyOf(value) !== keyOf(item)))} />)}
+ + return
+

Мост, порты и VLAN

+

Подготовьте единый план VLAN filtering, PVID и участников. Проверяется доступ к управлению устройством. Без независимого канала используется основной адрес с обязательным подтверждением человеком. Подтверждение и применение выполняются отдельно в планах.

+ {error &&

{error}

} +
+ + +
+ {loading &&

Чтение состояния…

} + {draft && state &&
+
edit(value => ({ ...value, filtering }))} />
+

Статические порты

+ {draft.ports.map((port, index) =>
{port.id ?? "Новый порт"} +
{interfaceSelect("Интерфейс порта", port.interface, reference => edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, interface: reference } : item) })))} + +
+
edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, ingressFiltering } : item) }))} /> edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, disabled } : item) }))} />
+
)} + +

Статические участники VLAN

+ {draft.vlans.map((vlan, index) => { + const update = (patch: Partial) => edit(value => ({ ...value, vlans: value.vlans.map((item, i) => i === index ? { ...item, ...patch } : item) })) + return
{vlan.id ?? "Новая запись VLAN"} + + {membership("Tagged, включая CPU-порт моста при необходимости", vlan.tagged, tagged => update({ tagged }))} + {membership("Untagged", vlan.untagged, untagged => update({ untagged }))} +
update({ disabled })} />
+
+ })} + + {state.ports.filter(row => row.bridge === bridgeName && dynamic(row)).map(row =>

Динамический порт {text(row, "interface")} ({text(row, ".id")}) — только чтение

)} + {state.vlans.filter(row => row.bridge === bridgeName && dynamic(row)).map(row =>

Динамический VLAN {text(row, "vlan-ids")} ({text(row, ".id")}) — только чтение

)} + {(draft.removePortIds.length > 0 || draft.removeVlanIds.length > 0) &&

Явное удаление портов: {draft.removePortIds.join(", ") || "нет"}. Записей VLAN: {draft.removeVlanIds.join(", ") || "нет"}. Для отмены удаления перечитайте состояние.

} + +
} + {receipt &&

Подготовлен план {receipt}. Открыть планы для проверки и подтверждения

} +
+} diff --git a/components/mcp/database-restore.tsx b/components/mcp/database-restore.tsx new file mode 100644 index 00000000..d60014cf --- /dev/null +++ b/components/mcp/database-restore.tsx @@ -0,0 +1,102 @@ +"use client" + +import { useEffect, useRef, useState } from "react" +import { mcpPageQuerySchema } from "@mmapp/contracts/mcp" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { getClaims, hasPermission } from "@/lib/auth" +import { maxMcpRestoreArchiveBytes, type McpApi } from "@/shared/api/mcp" + +export function DatabaseRestore({ api }: { api: McpApi }) { + const [connections, setConnections] = useState<{ id: string; name: string }[]>([]) + const [connectionId, setConnectionId] = useState("") + const [file, setFile] = useState(null) + const [archive, setArchive] = useState> | null>(null) + const [operationId, setOperationId] = useState("") + const [result, setResult] = useState(null) + const [busy, setBusy] = useState(false) + const [error, setError] = useState("") + const [clock, setClock] = useState(0) + const activeRequest = useRef(null) + const deadline = archive ? Date.parse(archive.expiresAt) : null + const expired = deadline !== null && deadline <= clock + const validFile = !!file && file.size > 0 && file.size <= maxMcpRestoreArchiveBytes + const receiptId = operationId.trim() + const validReceiptId = mcpPageQuerySchema.shape.operationId.safeParse(receiptId).success + useEffect(() => { + const abort = new AbortController() + void api.connections(abort.signal).then(data => { + if (abort.signal.aborted) return + const viewer = getClaims()?.sub + setConnections(data.connections.filter(item => item.ownerId === viewer && item.generationValid && item.policy.status === "active" && item.policy.scope.allowGlobal && + item.policy.scope.operationIds.includes("database.restore") && hasPermission(item.policy.permissions, "mm:settings:admin"))) + }, failure => { if (!abort.signal.aborted) setError(String(failure)) }) + return () => { abort.abort(); activeRequest.current?.abort() } + }, [api]) + useEffect(() => { + if (deadline === null) return + let timer: ReturnType + const update = () => { + clearTimeout(timer) + const now = Date.now() + setClock(now) + if (now < deadline) timer = setTimeout(update, Math.min(deadline - now, 2_147_483_647)) + } + update() + document.addEventListener("visibilitychange", update) + return () => { clearTimeout(timer); document.removeEventListener("visibilitychange", update) } + }, [deadline]) + const clearResult = () => { setResult(null); setError("") } + const run = async (work: (signal: AbortSignal) => Promise) => { + if (activeRequest.current) return + const request = new AbortController() + activeRequest.current = request + setBusy(true); clearResult() + try { + const response = await work(request.signal) + if (!request.signal.aborted) setResult(response) + } catch (failure) { + if (!request.signal.aborted) setError(failure instanceof Error ? failure.message : String(failure)) + } finally { + activeRequest.current = null + if (!request.signal.aborted) setBusy(false) + } + } + const upload = () => { + if (!file || !validFile) return + void run(async signal => { + setArchive(null) + const data = await api.uploadRestoreArchive(file, signal) + if (data.sizeBytes !== file.size) throw new Error("Размер загруженного архива не совпадает с выбранным файлом.") + if (!signal.aborted) setArchive(data) + return data + }) + } + const prepare = () => { + if (!archive || !connectionId) return + const now = Date.now() + if (Date.parse(archive.expiresAt) <= now) { setClock(now); return } + void run(signal => api.restorePlan(connectionId, archive.archiveRef, archive.sha256, signal)) + } + return
+

Восстановление БД через MCP

+

Архив PostgreSQL загружает администратор. Модель получает ссылку и SHA-256. Выполнение требует отдельного подтверждения в планах. После восстановления прежний MCP-доступ отзывается, а результат хранится во внешней квитанции.

+ {error &&

{error}

} + + + {file && !validFile &&

Выберите непустой архив размером до 64 МиБ.

} +
+ + +
+ {archive &&

SHA-256: {archive.sha256} · Допуск до {new Date(archive.expiresAt).toLocaleString()}

} + {expired &&

Срок архива истёк. Загрузите архив снова для нового плана.

} + + + {result !== null &&
{JSON.stringify(result, null, 2)}
} +
+} diff --git a/components/mcp/mcp-workspace.tsx b/components/mcp/mcp-workspace.tsx new file mode 100644 index 00000000..b8079be9 --- /dev/null +++ b/components/mcp/mcp-workspace.tsx @@ -0,0 +1,802 @@ +"use client" + +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react" +import { useSearchParams } from "next/navigation" +import Link from "next/link" +import { useTable, type ColumnDef } from "@tanstack/react-table" +import { BotIcon, CopyIcon, PlusIcon, RefreshCwIcon, ShieldIcon, StopCircleIcon } from "lucide-react" +import { toast } from "sonner" +import { mcpConnectionCreateSchema, mcpPageQuerySchema, mcpTargetSchema, type McpConnection, type McpOperationDescriptor, type McpPolicyDecision } from "@mmapp/contracts/mcp" +import { routeAiControllerBlockReason, routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing" +import { useDataSource } from "@/lib/data-source" +import { can, getClaims, getToken, hasPermission } from "@/lib/auth" +import { DATA_GRID_LABELS_RU } from "@/lib/data-grid-labels-ru" +import { mcpApi, type McpApi } from "@/shared/api/mcp" +import { PageHeader } from "@/components/page-header" +import { DatabaseRestore } from "./database-restore" +import { PlanReview } from "./plan-review" +import { ArtifactDownloads } from "./artifact-downloads" +import { PollStorageCapacity } from "./poll-storage-capacity" +import { BridgeVlanWorkflow } from "./bridge-vlan-workflow" +import { ObjectPermissionPreview, PolicyPreviewDecision } from "./object-permission-preview" +import { Frame, FrameHeader, FrameTitle, FrameDescription, FramePanel } from "@/components/reui/frame" +import { DataGrid, DataGridContainer, DataGridTable, DataGridScrollArea, dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid" +import { Badge } from "@/components/reui/badge" +import { Button, buttonVariants } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Checkbox } from "@/components/ui/checkbox" +import { Textarea } from "@/components/ui/textarea" +import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs" +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog" + +const errorText = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить запрос" +const modeLabels = { observer: "Наблюдатель", approval: "С подтверждением", autonomous: "Автономный" } +const tabs = { overview: "Обзор", connections: "Подключения", permissions: "Разрешения", devices: "Интерфейсы", requests: "Обращения", plans: "Планы и операции", routing: "Route AI", settings: "Настройки" } +type Tab = keyof typeof tabs +type RecordRow = Record +function pretty(value: unknown) { return JSON.stringify(value, null, 2) } +function date(value: unknown) { return value ? new Date(String(value)).toLocaleString("ru-RU") : "—" } +function connectionAccessDeadline(connection: McpConnection) { + return Math.min(Date.parse(connection.policy.expiresAt), Date.parse(connection.ownerValidUntil ?? "")) +} +function ConnectionAccessStatus({ connection }: { connection: McpConnection }) { + const [now, setNow] = useState(() => Date.now()) + const expires = Date.parse(connection.policy.expiresAt), ownerExpires = Date.parse(connection.ownerValidUntil ?? "") + useEffect(() => { + let timer: number | undefined + const tick = () => { + const current = Date.now(); setNow(current) + const next = [expires, ownerExpires].filter(value => Number.isFinite(value) && value > current).reduce((first, value) => Math.min(first, value), Infinity) + if (Number.isFinite(next)) timer = window.setTimeout(tick, Math.min(60000, Math.max(1, next - current + 1))) + } + tick() + return () => window.clearTimeout(timer) + }, [expires, ownerExpires]) + const [label, reason] = connection.policy.status === "revoked" ? ["Доступ отозван", "Подключение и его токены отозваны"] + : connection.policy.status === "paused" ? ["На паузе", "Новые вызовы подключения остановлены"] + : !connection.generationValid ? ["Доступ аннулирован", "Поколение доступа больше не действительно"] + : !Number.isFinite(expires) ? ["Срок не подтверждён", "Не удалось определить срок доступа"] + : expires <= now ? ["Срок доступа истёк", "Продлите срок в разрешениях подключения"] + : !Number.isFinite(ownerExpires) ? ["Права не подтверждены", "Срок подтверждения прав владельца отсутствует"] + : ownerExpires <= now ? ["Права владельца истекли", "Владельцу нужно подтвердить актуальные права"] + : ["Активен", "Срок доступа и права владельца действуют"] + return
{label}{reason}
+} +function useQuery(load: (signal: AbortSignal) => Promise, key = "") { + const [response, setResponse] = useState<{ key: string; data: T; updatedAt: string } | null>(null) + const [failure, setFailure] = useState<{ key: string; message: string } | null>(null) + const refresh = useCallback(() => { window.dispatchEvent(new Event("mcp-refresh")) }, []) + useEffect(() => { + let alive = true, revision = 0, pending = false, controller: AbortController | undefined, deadline: number | undefined + const run = async (replace = false) => { + if (!alive || document.hidden || (pending && !replace)) return + controller?.abort(); window.clearTimeout(deadline); controller = new AbortController(); const requestRevision = ++revision + pending = true + deadline = window.setTimeout(() => { + if (!alive || requestRevision !== revision) return + revision++; pending = false; controller?.abort() + setFailure({ key, message: "Обновление не завершилось за минуту. Следующая попытка выполнится автоматически." }) + }, 60000) + try { + const result = await load(controller.signal) + if (alive && requestRevision === revision) { + setResponse({ key, data: result, updatedAt: new Date().toISOString() }) + setFailure(null) + } + } catch (error) { + if (alive && requestRevision === revision && !controller.signal.aborted) setFailure({ key, message: errorText(error) }) + } + finally { if (requestRevision === revision) { window.clearTimeout(deadline); pending = false } } + } + queueMicrotask(() => { void run() }) + const tick = () => { void run() }, timer = window.setInterval(tick, 5000) + const reload = () => { void run(true) } + window.addEventListener("mcp-refresh", reload); document.addEventListener("visibilitychange", tick) + return () => { alive = false; revision++; controller?.abort(); window.clearTimeout(deadline); window.clearInterval(timer); window.removeEventListener("mcp-refresh", reload); document.removeEventListener("visibilitychange", tick) } + }, [load, key]) + return { + data: response?.key === key ? response.data : null, + error: failure?.key === key ? failure.message : "", + refresh, + updatedAt: response?.key === key ? response.updatedAt : null, + } +} +function Panel({ title, description, children, actions }: { title: string; description?: string; children: ReactNode; actions?: ReactNode }) { + return
{title}{description && {description}}
{actions}
{children} +} +function ErrorMessage({ message }: { message: string }) { return message ?

{message}

: null } +function Field({ label, children }: { label: string; children: ReactNode }) { return } +function Choice({ label, checked, onChange }: { label: string; checked: boolean; onChange: (value: boolean) => void }) { return } +function NativeSelect({ label, value, onChange, children }: { label: string; value: string; onChange: (value: string) => void; children: ReactNode }) { + return +} +function Grid({ items, columns, loading, total, onSelect }: { items: RecordRow[]; columns: ColumnDef[]; loading?: boolean; total?: number; onSelect?: (row: RecordRow) => void }) { + const table = useTable({ features: dataGridFeatures, data: items, columns, getRowId: (row, index) => String(row.id ?? index), manualPagination: true, rowCount: total ?? items.length }) + return +} +type DeviceResource = Awaited>["resources"][number] +function DeviceManagement({ api }: { api: McpApi }) { + const connections = useQuery(useCallback(signal => api.connections(signal), [api])) + const [connectionId, setConnectionId] = useState("") + return {connections.data?.connections.filter(connection => connection.ownerId === getClaims()?.sub && connection.policy.status === "active").map(connection => )}{connectionId && } +} +function DeviceCatalog({ api, connectionId }: { api: McpApi; connectionId: string }) { + const catalog = useQuery(useCallback(signal => api.deviceCatalog(connectionId, signal), [api, connectionId])) + const [serverId, setServerId] = useState(""), [resourceId, setResourceId] = useState("") + const resource = catalog.data?.resources.find(resource => resource.id === resourceId) + return <>
{catalog.data?.servers.map(server => )}{catalog.data?.resources.filter(resource => resource.read).map(resource => )}
{catalog.data && !catalog.data.resources.some(resource => resource.read) &&

Подключению не выданы инструменты чтения интерфейсов.

}{resourceId === "bridge" && serverId && catalog.data?.servers.some(server => String(server.id) === serverId && server.enabled) && }{resource && serverId && catalog.data?.servers.some(server => String(server.id) === serverId && server.enabled) && } +} +function DeviceEditor({ api, connectionId, serverId, resource }: { api: McpApi; connectionId: string; serverId: string; resource: DeviceResource }) { + const [offset, setOffset] = useState(0), [editing, setEditing] = useState(null), [draft, setDraft] = useState>({}) + const [busy, setBusy] = useState(false), [error, setError] = useState(""), [receipt, setReceipt] = useState("") + const rows = useQuery(useCallback(signal => api.deviceRows(connectionId, serverId, resource.id, offset, signal), [api, connectionId, serverId, resource.id, offset]), String(offset)) + const open = (row: RecordRow | "new") => { setEditing(row); setDraft({}); setError(""); setReceipt("") } + const prepare = async (action: "create" | "update" | "delete") => { + setBusy(true); setError(""); setReceipt("") + try { + const result = await api.devicePlan(connectionId, serverId, resource.id, action, editing && editing !== "new" ? String(editing[".id"]) : undefined, action === "delete" ? {} : draft) + setReceipt(`Создан план ${result.planId}. Проверьте изменения, подтвердите и примените его на вкладке «Планы и операции».`); setEditing(null); rows.refresh() + } catch (failure) { setError(errorText(failure)) } finally { setBusy(false) } + } + const current = editing && editing !== "new" ? editing : null + const ethernetDisabledUnknown = resource.id === "ethernet" && current !== null && current.disabled === undefined + const editableFields = resource.fields.filter(field => + editing === "new" || field.key === "comment" || field.key in (current ?? {}) || (ethernetDisabledUnknown && field.key === "disabled"), + ) + const protectedRow = current && ["dynamic", "builtin", "default"].some(key => current[key] === "true" || current[key] === true) + const change = (key: string, value: unknown) => setDraft(fields => { const next = { ...fields }; if (value === undefined) delete next[key]; else next[key] = value; return next }) + return <>{receipt &&

{receipt}

}

Объектов: {rows.data?.total ?? "…"}. Выберите строку для просмотра и подготовки изменения.

{resource.create && }
String(row.original[".id"] ?? "—") }, { id: "name", header: "Объект", cell: ({ row }) => String(row.original.name ?? row.original.address ?? row.original.interface ?? "—") }, { id: "state", header: "Состояние", cell: ({ row }) => String(row.original.disabled === "true" || row.original.disabled === true ? "Выключен" : row.original.running ?? "—") }]} onSelect={row => { if (row[".id"] && !busy) open(row) }} />
{editing &&

{editing === "new" ? "Новый объект" : `Объект ${String(current?.[".id"])}`}

{current &&
Текущие свойства
{pretty(current)}
}{protectedRow ?

Системный или динамический объект доступен для чтения.

: <>

В план попадут только заполненные изменения. Пустой выбор оставляет свойство без изменения; при создании действует настройка устройства.

{editableFields.map(field => {field.type === "boolean" || field.options ? : change(field.key, field.type === "number" ? event.target.value === "" ? undefined : Number(event.target.value) : event.target.value)} />})}
+ {ethernetDisabledUnknown && draft.disabled !== undefined &&

Исходное состояние неизвестно. Для этого изменения обратный план недоступен.

} + }
{!protectedRow && (editing === "new" ? resource.create : resource.update) && }{current && !protectedRow && resource.delete && }
} +} +function TokenDialog({ token, close, connectionName }: { token: string; close: () => void; connectionName?: string }) { + return { if (!open) close() }}>Доступ создан{connectionName && `Подключение «${connectionName}». `}Сохраните токен в настройках AI-клиента. Повторно посмотреть его нельзя. +} +function ConnectionForm({ api, operations, editing, close, created }: { api: McpApi; operations: McpOperationDescriptor[]; editing?: McpConnection; close: () => void; created: (token?: string) => void }) { + const [step, setStep] = useState(1), [busy, setBusy] = useState(false), [error, setError] = useState("") + const [name, setName] = useState(editing?.name ?? ""), [mode, setMode] = useState(editing?.policy.mode ?? "observer") + const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState(editing?.policy.scope.operationIds ?? []) + const [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval") + const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? []) + const [expires, setExpires] = useState(() => editing?.policy.expiresAt.slice(0, 16) ?? new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 16)) + const [limits, setLimits] = useState(editing?.policy.limits ?? { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 }) + const permissions = getClaims()?.permissions ?? [] + const eligible = operations.filter(operation => operation.implementation === "available" && operation.requiredPermissions.every(permission => hasPermission(permissions, permission))) + const toggle = (id: string) => setSelected(ids => ids.includes(id) ? ids.filter(value => value !== id) : [...ids, id]) + const save = async () => { + setBusy(true); setError("") + try { + const input = mcpConnectionCreateSchema.parse({ name, mode, expiresAt: new Date(expires + "Z").toISOString(), permissions: [...new Set(eligible.filter(operation => selected.includes(operation.id)).flatMap(operation => operation.requiredPermissions))], scope: { serverIds: serverText.split(/[,\s]+/).filter(Boolean).map(Number), operationIds: selected, allowGlobal: global }, dangerousPolicy: danger, autonomousDangerousOperationIds: dangerIds.filter(id => selected.includes(id)), limits }) + if (editing) { await api.update(editing.id, input); created() } + else { const result = await api.create(input); created(result.token) } + } catch (failure) { setError(errorText(failure)) } finally { setBusy(false) } + } + return { if (!open && !busy) close() }}>{editing ? "Изменить разрешения" : "Новое подключение"}Шаг {step} из 4 · доступ ограничивается правами текущего владельца. + {step === 1 && <> setName(event.target.value)} placeholder="Агент диагностики" /> setExpires(event.target.value)} /> setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => )}} + {step === 2 && <> setServerText(event.target.value)} placeholder="1, 2" />
{eligible.map(operation => toggle(operation.id)} />)}

Новые инструменты не добавляются в доступ автоматически. Для применения планов выберите также инструменты просмотра и применения.

} + {step === 3 && <>
{Object.entries(limits).map(([key, value]) => )[key]}> setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} />)}
setDanger(value as typeof danger)}>{danger === "explicit-allow" && eligible.filter(operation => operation.risk === "dangerous" && selected.includes(operation.id)).map(operation => setDangerIds(ids => checked ? [...ids, operation.id] : ids.filter(id => id !== operation.id))} />)}} + {step === 4 &&

{name || "Без названия"} · {modeLabels[mode]}

Серверы: {serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.

Защита объектов продолжает действовать независимо от автономных разрешений.

После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».

} +
{step < 4 ? : }
+
+} +function Connections({ api, operations }: { api: McpApi; operations: McpOperationDescriptor[] }) { + const query = useQuery(useCallback(signal => api.connections(signal), [api])) + const [editing, setEditing] = useState(null), [token, setToken] = useState("") + const admin = can("mm:mcp:admin") + const refresh = query.refresh + const act = useCallback(async (work: () => Promise) => { try { await work(); refresh() } catch (error) { toast.error(errorText(error)) } }, [refresh]) + const columns = useMemo[]>(() => [ + { accessorKey: "name", header: "Подключение", size: 200, cell: ({ row }) => { + const connection = row.original as unknown as McpConnection + const journal = new URLSearchParams({ tab: "requests", "requests.connectionId": connection.id }) + return
{connection.name}
+ {admin && Проверить права} + Журнал подключения +
+ } }, + { id: "mode", header: "Режим", cell: ({ row }) => modeLabels[(row.original.policy as McpConnection["policy"]).mode] }, + { id: "status", header: "Состояние доступа", size: 260, cell: ({ row }) => }, + { id: "expiresAt", header: "Доступ до", size: 170, cell: ({ row }) => date((row.original.policy as McpConnection["policy"]).expiresAt) }, + { accessorKey: "lastUsedAt", header: "Последний вызов", cell: ({ row }) => date(row.original.lastUsedAt) }, + { id: "ownerValidation", header: "Права владельца до", size: 190, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return
{date(connection.ownerValidUntil)}{connection.ownerId === getClaims()?.sub && }
} }, + { id: "actions", header: "Действия", size: 350, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return admin &&
} }, + ], [api, admin, act]) + return <> setEditing("new")}>Выдать доступ}>

HTTP endpoint: адрес backend + /mcp. Для stdio используйте MCP_URL и MCP_TOKEN с командой npm --prefix backend run mcp:stdio.

{editing && setEditing(null)} created={value => { setEditing(null); if (value) setToken(value); query.refresh() }} />} setToken("")} /> +} +function AccessTools({ api }: { api: McpApi }) { + const connections = useQuery(useCallback(signal => api.connections(signal), [api])) + const [selected, setSelected] = useState("") + const [grantBusy, setGrantBusy] = useState(false) + const [issued, setIssued] = useState<{ token: string; connectionName: string } | null>(null) + const grantLocked = useRef(false) + const connection = connections.data?.connections.find(value => value.id === selected) + + const releaseGrant = () => { + grantLocked.current = false + setGrantBusy(false) + } + const issue = async (grant: Parameters[1]) => { + if (!connection || grantLocked.current) return + grantLocked.current = true + setGrantBusy(true) + try { + const { token } = await api.grant(connection.id, grant) + setIssued({ token, connectionName: connection.name }) + connections.refresh() + } catch (error) { + releaseGrant() + toast.error(errorText(error)) + } + } + + return + + + + {connections.data?.connections.map(connection => )} + + {connection && } + {issued && { setIssued(null); releaseGrant() }} />} + +} + +function ConnectionAccessTools({ api, connection, issue, grantBusy }: { + api: McpApi + connection: McpConnection + issue: (grant: Parameters[1]) => Promise + grantBusy: boolean +}) { + const [result, setResult] = useState> | null>(null) + const [operations, setOperations] = useState([]), [serverText, setServerText] = useState(""), [minutes, setMinutes] = useState(60), [global, setGlobal] = useState(false) + const connectionId = connection.id + const grants = useQuery(useCallback(signal => api.grants(connectionId, signal), [api, connectionId])) + const checkRevision = useRef(0) + useEffect(() => () => { checkRevision.current++ }, []) + + const check = async () => { + const revision = ++checkRevision.current + setResult(null) + try { + const readiness = await api.check(connectionId) + if (revision === checkRevision.current) setResult(readiness) + } catch (error) { + if (revision === checkRevision.current) toast.error(errorText(error)) + } + } + + const create = () => { + const now = new Date(), expires = new Date(Math.min(now.getTime() + minutes * 60000, Date.parse(connection.policy.expiresAt))) + try { + void issue({ + id: crypto.randomUUID(), startsAt: now.toISOString(), expiresAt: expires.toISOString(), + scope: { serverIds: serverText.split(",").map(value => value.trim()).filter(Boolean).map(Number), operationIds: operations, allowGlobal: global }, + }) + } catch (error) { + toast.error(errorText(error)) + } + } + + return <> + +

Права владельца подтверждены до {date(connection.ownerValidUntil)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.

+ + + {result !== null && <> + {result.protocolProbe?.capabilitiesRead &&

+ {({ passed: "Проверочное чтение возможностей прошло.", failed: "Проверочное чтение возможностей завершилось ошибкой.", skipped: "Проверочное чтение возможностей пропущено." })[result.protocolProbe.capabilitiesRead]} +

} +
{pretty(result)}
+ } +
+ setServerText(event.target.value)} placeholder="ID через запятую" /> + setMinutes(Number(event.target.value))} /> +
+ {connection.policy.scope.allowGlobal && } +
{connection.policy.scope.operationIds.map(id => setOperations(values => checked ? [...values, id] : values.filter(value => value !== id))} />)}
+ + {grants.data?.grants.map(grant =>
+ До {date(grant.grant.expiresAt)} · {grant.revoked_at ? "отозван" : "выдан"} + +
)} + +} +function RoutingProfileForm({ api, editing, close }: { api: McpApi; editing?: RecordRow; close: () => void }) { + const connections = useQuery(useCallback(signal => api.connections(signal), [api])) + const original = editing ? routeAiProfileSchema.parse(editing.config) : null + const [connectionId, setConnectionId] = useState(String(editing?.connection_id ?? "")), [name, setName] = useState(original?.name ?? ""), [serverId, setServerId] = useState(String(original?.serverId ?? "")) + const [community, setCommunity] = useState(original?.community ?? ""), [family, setFamily] = useState(original?.family ?? "ipv4"), [table, setTable] = useState(original?.table ?? "main") + const [probeVrf, setProbeVrf] = useState(original?.probeVrf ?? "main") + const [bindBgp, setBindBgp] = useState(!!original?.bgpContext) + const [bgp, setBgp] = useState(original?.bgpContext ?? { connectionId: "", instance: "", inputChain: "", vrf: "main" }) + const [enabled, setEnabled] = useState(editing?.enabled === true), [expires, setExpires] = useState(() => new Date(Date.now() + 1800000).toISOString().slice(0, 16)) + const [autoRecovery, setAutoRecovery] = useState(original?.autoRecovery ?? false) + const [weights, setWeights] = useState(original?.weights ?? { ping: 60, speed: 30, loss: 10 }), [threshold, setThreshold] = useState(original?.switchThreshold ?? 15), [cooldown, setCooldown] = useState(original?.cooldownSec ?? 600) + const [pin, setPin] = useState(original?.pinnedCandidateId ?? ""), [excluded, setExcluded] = useState(original?.excludedCandidateIds ?? []) + const [sla, setSla] = useState({ ping: original?.maxPingMs?.toString() ?? "", loss: original?.maxLossPct?.toString() ?? "", speed: original?.minBandwidthMbps?.toString() ?? "" }) + const [candidates, setCandidates] = useState(() => original?.candidates.map(candidate => ({ ...candidate, jumpHostId: String(candidate.jumpHostId), exitNodeId: String(candidate.exitNodeId) })) ?? [{ id: "path-1", wanInterface: "", jumpHostId: "", exitNodeId: "", downstreamInterface: "", gateway: "", gatewayRef: { resource: "gre" as "gre" | "ipv4_route" | "ipv6_route", id: "" }, wanRemoteInterface: "", downstreamRemoteInterface: "" }]) + const controllerReason = routeAiControllerBlockReason({ table, probeVrf, bgpContext: bindBgp ? bgp : undefined, autoRecovery, candidates }) + const [error, setError] = useState(""), [busy, setBusy] = useState(false), [plan, setPlan] = useState("") + const save = async () => { + setBusy(true); setError("") + try { + const profile = routeAiProfileSchema.parse({ ...original, name, serverId: Number(serverId), community, family, table, probeVrf, bgpContext: bindBgp ? bgp : undefined, weights, switchThreshold: threshold, cooldownSec: cooldown, autoRecovery, pinnedCandidateId: pin || null, excludedCandidateIds: excluded, + maxPingMs: sla.ping ? Number(sla.ping) : null, maxLossPct: sla.loss ? Number(sla.loss) : null, minBandwidthMbps: sla.speed ? Number(sla.speed) : null, + candidates: candidates.map(candidate => ({ ...candidate, jumpHostId: Number(candidate.jumpHostId), exitNodeId: Number(candidate.exitNodeId), wanRemoteInterface: candidate.wanRemoteInterface || undefined, downstreamRemoteInterface: candidate.downstreamRemoteInterface || undefined })) }) + if (enabled && controllerReason) throw new Error(controllerReason + " Отключите контроллер для сохранения профиля.") + const result = await api.profilePlan({ connectionId, ...(editing ? { profileId: editing.id } : {}), profile, enabled, expiresAt: new Date(expires + "Z").toISOString() }) + setPlan(result.planId) + } catch (failure) { setError(errorText(failure)) } finally { setBusy(false) } + } + return { if (!open && !busy) close() }}>{editing ? "Изменить профиль Route AI" : "Новый профиль Route AI"}Проверьте пути и допуск. Сохранение создаёт план для отдельного подтверждения и применения.{plan ? <>

Создан план {plan}. Откройте «Планы и операции», проверьте изменения, подтвердите и примените план.

: <>
{connections.data?.connections.filter(connection => connection.ownerId === getClaims()?.sub && connection.policy.status === "active" && connection.policy.mode !== "observer" && connection.policy.scope.operationIds.includes("routing.profiles.save")).map(connection => )} setName(event.target.value)} /> setServerId(event.target.value)} /> setCommunity(event.target.value)} placeholder="65000:10" /> setFamily(value as typeof family)}> setTable(event.target.value)} /> setProbeVrf(event.target.value)} />
+

Таблица определяет установку маршрутов. VRF диагностических проб определяет контекст измерений и задаётся отдельно от транспортной VRF BGP.

+ + {bindBgp ?
Контекст BGP
{([{ key: "connectionId", title: "ID BGP-подключения RouterOS" }, { key: "instance", title: "Экземпляр BGP" }, { key: "inputChain", title: "Входящая цепочка BGP" }, { key: "vrf", title: "Транспортная VRF BGP" }] as const).map(field => setBgp(values => ({ ...values, [field.key]: event.target.value }))} />)}

Заполните все поля. Снятие привязки явно удалит контекст BGP из плана профиля.

:

Подключение BGP будет определено по наблюдаемой конфигурации; неоднозначная привязка блокирует переключение.

} + {controllerReason &&

{controllerReason} Профиль можно сохранить с выключенным контроллером для анализа и подготовки предложений.

} + {candidates.map((candidate, index) =>
Путь {index + 1} · {candidate.id}
{([{ key: "wanInterface", title: "WAN-интерфейс дома" }, { key: "jumpHostId", title: "ID JumpHost" }, { key: "exitNodeId", title: "ID ExitNode" }, { key: "downstreamInterface", title: "Интерфейс JumpHost к ExitNode" }, { key: "gateway", title: "Адрес gateway" }, { key: "wanRemoteInterface", title: "Входящий интерфейс JumpHost" }, { key: "downstreamRemoteInterface", title: "Входящий интерфейс ExitNode" }] as const).map(field => setCandidates(values => values.map(value => value.id === candidate.id ? { ...value, [field.key]: event.target.value } : value))} />)} setCandidates(values => values.map(value => value.id === candidate.id ? { ...value, gatewayRef: { ...value.gatewayRef, resource: resource as typeof value.gatewayRef.resource } } : value))}> setCandidates(values => values.map(value => value.id === candidate.id ? { ...value, gatewayRef: { ...value.gatewayRef, id: event.target.value } } : value))} />
setExcluded(values => checked ? [...values, candidate.id] : values.filter(value => value !== candidate.id))} />
)} + setCandidates(values => values.map(candidate => candidate.id === id ? { ...candidate, controlProbe } : candidate))} />
{Object.entries(weights).map(([key, value]) => setWeights(values => ({ ...values, [key]: Number(event.target.value) }))} />)}{([{ key: "ping", title: "Максимум RTT, мс" }, { key: "loss", title: "Максимум потерь, %" }, { key: "speed", title: "Минимум скорости, Mbps" }] as const).map(field => setSla(values => ({ ...values, [field.key]: event.target.value }))} />)} setThreshold(Number(event.target.value))} /> setCooldown(Number(event.target.value))} />{candidates.map((candidate, index) => )}
setExpires(event.target.value)} />}
+} +type CandidateForm = Omit & { jumpHostId: string; exitNodeId: string } +function CandidateProbeEditor({ candidates, update }: { candidates: CandidateForm[]; update: (id: string, probe: CandidateForm["controlProbe"]) => void }) { + return
{candidates.map((candidate, index) =>
Контрольная проверка пути {index + 1} update(candidate.id, checked ? { targetInterface: candidate.downstreamRemoteInterface ?? "", expectedHops: [{ serverId: Number(candidate.jumpHostId), interface: candidate.wanRemoteInterface ?? "" }, { serverId: Number(candidate.exitNodeId), interface: candidate.downstreamRemoteInterface ?? "" }] } : undefined)} />{candidate.controlProbe && <> update(candidate.id, { ...candidate.controlProbe!, targetInterface: event.target.value })} /> update(candidate.id, { ...candidate.controlProbe!, sourceAddress: event.target.value || undefined })} /> update(candidate.id, { ...candidate.controlProbe!, targetAddress: event.target.value || undefined })} />{candidate.controlProbe.expectedHops.map((hop, hopIndex) =>
update(candidate.id, { ...candidate.controlProbe!, expectedHops: candidate.controlProbe!.expectedHops.map((item, current) => current === hopIndex ? { ...item, serverId: Number(event.target.value) } : item) })} /> update(candidate.id, { ...candidate.controlProbe!, expectedHops: candidate.controlProbe!.expectedHops.map((item, current) => current === hopIndex ? { ...item, address: event.target.value || undefined } : item) })} /> update(candidate.id, { ...candidate.controlProbe!, expectedHops: candidate.controlProbe!.expectedHops.map((item, current) => current === hopIndex ? { ...item, interface: event.target.value } : item) })} />
)}

Проверяются зарегистрированные адреса, порядок hops и достижение ExitNode. Это наблюдение контрольных пакетов; оно не доказывает путь всего пользовательского трафика.

}
)}
+} +function RoutePathVerification({ api }: { api: McpApi }) { + const profiles = useQuery(useCallback(signal => api.profiles(signal), [api])) + const [profileId, setProfileId] = useState(""), [candidateId, setCandidateId] = useState(""), [busy, setBusy] = useState(false) + const [proofPurpose, setProofPurpose] = useState<"community" | "control-path">("community") + const [feedback, setFeedback] = useState<{ key: string; result: unknown } | { key: string; error: string } | null>(null) + const revision = useRef(0) + const profile = profiles.data?.profiles.find(profile => profile.id === profileId), config = routeAiProfileSchema.safeParse(profile?.config) + const candidates = config.success ? config.data.candidates.filter(candidate => candidate.controlProbe) : [] + const canCheck = candidates.some(candidate => candidate.id === candidateId) + const selectionKey = JSON.stringify([profileId, profile?.version, candidateId, proofPurpose]) + const currentFeedback = feedback?.key === selectionKey ? feedback : null + const invalidate = () => { revision.current++; setFeedback(null) } + const check = async () => { + if (busy || !canCheck) return + const request = ++revision.current + setBusy(true); setFeedback(null) + try { + const result = await api.checkRoutePath(profileId, candidateId, proofPurpose) + if (request === revision.current) setFeedback({ key: selectionKey, result }) + } catch (failure) { + if (request === revision.current) setFeedback({ key: selectionKey, error: errorText(failure) }) + } finally { setBusy(false) } + } + return + +
+ { invalidate(); setProfileId(value); setCandidateId("") }}>{profiles.data?.profiles.map(profile => )} + { invalidate(); setCandidateId(value) }}>{candidates.map(candidate => )} + { invalidate(); setProofPurpose(value as typeof proofPurpose) }}> +
+

{proofPurpose === "control-path" ? "Проверяется только контрольный путь. Результат не разрешает переключение Community и не подтверждает обратный путь." : "Проверка учитывает Community, таблицу маршрутизации и BGP. Применение изменений требует отдельного плана; обратный путь проверяется отдельно."}

+ + {currentFeedback && "result" in currentFeedback &&
{pretty(currentFeedback.result)}
} +
+} +function RoutingProfiles({ api }: { api: McpApi }) { + const query = useQuery(useCallback(signal => api.profiles(signal), [api])), [selected, setSelected] = useState(null) + const [editing, setEditing] = useState(null) + const columns = useMemo[]>(() => [ + { id: "name", header: "Профиль", size: 220, cell: ({ row }) => String((row.original.config as RecordRow)?.name ?? row.original.id) }, + { id: "community", header: "Community / семейство", cell: ({ row }) => { const config = row.original.config as RecordRow; return `${config?.community} · ${config?.family} · ${config?.table}` } }, + { id: "state", header: "Контроллер", cell: ({ row }) => {row.original.enabled ? "включён" : "пауза"} }, + { id: "reason", header: "Решение", size: 300, cell: ({ row }) => String((row.original.state as RecordRow)?.pausedReason ?? (row.original.state as RecordRow)?.reason ?? "Ожидает проверки") }, + { accessorKey: "grant_expires_at", header: "Допуск до", cell: ({ row }) => date(row.original.grant_expires_at) }, + { id: "actions", header: "", cell: ({ row }) => can("mm:mcp:admin") && }, + ], [api, query.refresh]) + return <> setEditing("new")}>Создать профиль}>

Контроллер учитывает свежесть измерений, закрепления, SLA, гистерезис, cooldown и бюджет переключений. Неизвестный фактический путь не считается подтверждённым.

{ if (!open) setSelected(null) }}>Профиль Route AIСохранённые параметры и последнее решение контроллера
{pretty(selected)}
{can("mm:mcp:admin") && can("mm:network:write") && }
{editing && { setEditing(null); query.refresh() }} />} +} +function Overview({ api }: { api: McpApi }) { + const query = useQuery(useCallback(signal => api.overview(signal), [api])) + return { if (window.confirm("Остановить новые обращения MCP и все профили Route AI? Начатые записи будут завершены или сверены.")) void api.stopAutomation().then(query.refresh, error => toast.error(errorText(error))) }}>Остановить автоматические изменения}>
{Object.entries({ connections: "Подключения", calls: "Вызовы за 24 часа", errors: "Ошибки и отказы", approvals: "Ожидают подтверждения", running: "Выполняются" }).map(([key, title]) =>

{title}

{query.data ? query.data[key as "calls"] : "—"}

)}
{query.data?.enabled ? "MCP включён" : "MCP выключен"}

Выключатель прекращает новые вызовы. Выключатель также останавливает новые решения Route AI. Отдельный профиль можно остановить на вкладке Route AI.

+} +const recordQueryFilters = { + requests: ["tool", "status", "connectionId", "serverId", "userId", "from", "to"], + plans: ["status", "connectionId", "from", "to"], + operations: ["status", "connectionId", "from", "to"], + audit: ["connectionId", "userId", "from", "to"], + drift: ["from", "to"], +} as const + +function Records({ api, kind }: { api: McpApi; kind: keyof typeof recordQueryFilters }) { + const urlParams = useSearchParams(), [selected, setSelected] = useState(null) + const [startedOperation, setStartedOperation] = useState(null) + const operationId = kind === "operations" ? urlParams.get("operation") : null + const operationLink = new URLSearchParams(urlParams) + if (startedOperation) operationLink.set("operation", startedOperation) + const fields: readonly string[] = recordQueryFilters[kind] + const filterValue = (field: string) => urlParams.get(kind + "." + field) ?? "" + const cursor = filterValue("cursor") + const setFilter = (key: string, value: string) => { const url = new URL(window.location.href); if (value) url.searchParams.set(kind + "." + key, value); else url.searchParams.delete(kind + "." + key); if (key !== "cursor") url.searchParams.delete(kind + ".cursor"); window.history.replaceState(null, "", url.pathname + url.search) } + const queryFields = new URLSearchParams({ limit: "50" }) + for (const field of [...fields, "cursor"]) { + const value = filterValue(field) + if (value) queryFields.set(field, value) + } + const queryKey = queryFields.toString() + const load = useCallback((signal: AbortSignal) => api.records(kind, new URLSearchParams(queryKey), signal), [api, kind, queryKey]) + const query = useQuery(load, `${kind}?${queryKey}`) + const journalConnection = kind === "requests" ? filterValue("connectionId") : "" + const navigationClass = buttonVariants({ variant: "outline", className: "self-start" }) + const selectRecord = useCallback((row: RecordRow) => { + if (kind !== "operations") { setSelected(row); return } + const url = new URL(window.location.href) + url.searchParams.set("operation", String(row.id)) + window.history.pushState(null, "", url.pathname + url.search) + }, [kind]) + const columns = useMemo[]>(() => [ + { accessorKey: "created_at", header: "Время", size: 170, cell: ({ row }) => date(row.original.created_at ?? row.original.createdAt ?? row.original.detected_at) }, + { id: "action", header: "Действие", size: 260, cell: ({ row }) => String(row.original.tool ?? row.original.operationId ?? row.original.action ?? row.original.id) }, + { id: "state", header: "Результат", cell: ({ row }) => {String(row.original.status ?? row.original.state ?? "событие")} }, + { accessorKey: "connection_id", header: "Подключение", size: 250, cell: ({ row }) => {String(row.original.connection_id ?? row.original.connectionId ?? "—")} }, + { accessorKey: "error_code", header: "Причина", cell: ({ row }) => String(row.original.error_code ?? row.original.verification ?? "—") }, + { id: "details", header: "", cell: ({ row }) => }, + ], [selectRecord]) + const pendingPlanRequests = useRef(new Set()) + const [pendingPlans, setPendingPlans] = useState>(() => new Set()) + const selectedPlanPending = kind === "plans" && !!selected && pendingPlans.has(String(selected.id)) + const planExpiry = kind === "plans" && typeof selected?.expiresAt === "string" ? Date.parse(selected.expiresAt) : null + const [planClock, setPlanClock] = useState(0) + useEffect(() => { + if (planExpiry === null || !Number.isFinite(planExpiry)) return + let timer: ReturnType + const update = () => { + clearTimeout(timer) + const now = Date.now() + setPlanClock(now) + if (now < planExpiry) timer = setTimeout(update, Math.min(planExpiry - now, 2_147_483_647)) + } + update() + document.addEventListener("visibilitychange", update) + return () => { + clearTimeout(timer) + document.removeEventListener("visibilitychange", update) + } + }, [planExpiry]) + const planExpired = planExpiry !== null && (!Number.isFinite(planExpiry) || planExpiry <= planClock) + const currentPlan = kind === "plans" && selected ? query.data?.items.find(item => item.id === selected.id) : null + const planChanged = kind === "plans" && !!selected && (!currentPlan || query.error || pretty(currentPlan) !== pretty(selected)) + const planActionDisabled = selectedPlanPending || planExpired || !!planChanged + const submitPlan = async (action: "approve" | "reject" | "apply") => { + if (!selected || planChanged) return + if (planExpiry !== null && (!Number.isFinite(planExpiry) || planExpiry <= Date.now())) { + setPlanClock(Date.now()) + return + } + const plan = selected + const planId = String(plan.id) + const pending = pendingPlanRequests.current + if (pending.has(planId)) return + pending.add(planId) + setPendingPlans(new Set(pending)) + try { + if (action === "apply") { + const operation = await api.apply(planId) + setStartedOperation(operation.id) + toast.success("Запрос принят. Откройте выполнение операции для проверки результата.") + } else { + await api.decision(planId, action === "approve") + } + setSelected(current => current === plan ? null : current) + query.refresh() + } catch (error) { + toast.error(errorText(error)) + } finally { + pending.delete(planId) + setPendingPlans(new Set(pending)) + } + } + const closeDetails = () => { + setSelected(null) + if (operationId) { + const url = new URL(window.location.href) + url.searchParams.delete("operation") + window.history.replaceState(null, "", url.pathname + url.search) + } + } + return ( + + + {startedOperation && Открыть выполнение операции} + {journalConnection && Планы и операции подключения} + {journalConnection && can("mm:mcp:admin") && Административный аудит подключения} +

Последнее успешное обновление: {date(query.updatedAt)}{query.error && query.data ? " · показаны ранее полученные данные" : ""}

+ +
+ {fields.includes("tool") && setFilter("tool", event.target.value)} />} + {fields.includes("status") && setFilter("status", event.target.value)} />} + +
+ +
+ Найдено: {query.data?.total ?? "—"} +
+ + +
+
+ { if (!open) closeDetails() }}> + + + Детали {kind === "plans" ? "плана" : kind === "operations" ? "операции" : "обращения"} + {kind === "plans" ? "Подтверждение относится к показанному плану." : "Данные журнала с маскировкой секретных полей."} + + {operationId ? : kind === "plans" && selected ? :
{pretty(selected)}
} + {planExpired &&

Срок плана истёк. Подготовьте новый план.

} + {planChanged && !planExpired &&

Текущая версия плана недоступна или изменилась. Откройте план заново.

} + {kind === "plans" && ["approved", "draft"].includes(String(selected?.state)) && can("mm:mcp:admin") && } + {kind === "plans" && selected?.state === "awaiting-approval" && can("mm:mcp:approve") &&
} +
+
+
+ ) +} + +const operationStates: Record = { + pending: "Ожидает выполнения", running: "Выполняется", applied: "Применена", failed: "Ошибка выполнения", + blocked: "Заблокирована", cancelled: "Отменена", partial: "Выполнена частично", unknown: "Исход не подтверждён", +} +const stepStates: Record = { intent: "Записано намерение", applied: "Применён", acknowledged: "Получено подтверждение приёма", verified: "Результат проверен" } + +function OperationMonitor({ api, id }: { api: McpApi; id: string }) { + const recoveryLink = new URLSearchParams(useSearchParams()) + recoveryLink.delete("operation") + recoveryLink.set("reconcile", id) + const load = useCallback((signal: AbortSignal) => api.records("operations", new URLSearchParams({ operationId: id, limit: "1" }), signal), [api, id]) + const query = useQuery(load, id) + const operation = query.data?.items.find(item => item.id === id) + const state = String(operation?.state ?? "") + const steps = Array.isArray(operation?.steps) ? operation.steps as RecordRow[] : [] + return <> + +
+ {id} + +
+

+ {operation ? operationStates[state] ?? state : query.data ? "Операция отсутствует в доступном журнале" : query.error ? "Состояние недоступно" : "Получаем состояние операции…"} + {query.error && operation && " · последнее полученное состояние"} +

+ {operation && <> + {(state === "partial" || state === "unknown") &&
+

Перед обратным изменением сверьте фактическое состояние. Повтор может повторно изменить конфигурацию.

+ {can("mm:mcp:admin") && Перейти к сверке} +
} + {steps.length > 0 &&
+

Шаги выполнения

+
    + {steps.map(step =>
  1. {stepStates[String(step.state)] ?? String(step.state)}{step.server_id != null && ` · сервер ${step.server_id}`}{step.finished_at != null && ` · ${date(step.finished_at)}`}
  2. )} +
+ {operation.stepsTruncated === true &&

Показаны первые 100 шагов.

} +
} +
{pretty(operation)}
+ {!query.error && } + } + +} +function RecordFilters({ fields, value, update }: { fields: readonly string[]; value: (field: string) => string; update: (field: string, value: string) => void }) { + return ( +
+ {fields.includes("connectionId") && update("connectionId", event.target.value)} />} + {fields.includes("serverId") && update("serverId", event.target.value)} />} + {fields.includes("userId") && update("userId", event.target.value)} />} + {["from", "to"].map(field => update(field, event.target.value ? new Date(event.target.value + "Z").toISOString() : "")} />)} +
+ ) +} +function ConnectionPolicySimulation({ api, connection, operations }: { + api: McpApi + connection: McpConnection + operations: McpOperationDescriptor[] +}) { + const [operationId, setOperationId] = useState(""), [serverText, setServerText] = useState("") + const [result, setResult] = useState(null) + const revision = useRef(0) + useEffect(() => () => { revision.current++ }, []) + + const available = operations.filter(operation => connection.policy.scope.operationIds.includes(operation.id)) + const operation = available.find(operation => operation.id === operationId) + const target = mcpTargetSchema.safeParse(operation?.scope === "servers" + ? { scope: "servers", serverIds: serverText.split(/[,\s]+/).filter(Boolean).map(value => /^\d+$/.test(value) ? Number(value) : NaN) } + : { scope: operation?.scope }) + const invalidate = () => { revision.current++; setResult(null) } + const preview = async () => { + if (!operation || !target.success) return + const current = ++revision.current + setResult(null) + try { + const response = await api.preview({ connectionId: connection.id, operationId: operation.id, target: target.data }) + if (revision.current === current) setResult(response.result) + } catch (error) { + if (revision.current === current) toast.error(errorText(error)) + } + } + + return <> +
+ { invalidate(); setOperationId(value); setServerText("") }}> + + {available.map(operation => )} + + {operation?.scope === "servers" && { invalidate(); setServerText(event.target.value) }} />} +
+ {operation &&

{{ connection: "Область операции — подключение", global: "Область операции — всё приложение", servers: "Область операции — выбранные серверы" }[operation.scope]}

} + + {result && } + +} + +function Permissions({ api, operations }: { api: McpApi; operations: McpOperationDescriptor[] }) { + const connections = useQuery(useCallback(signal => api.connections(signal), [api])) + const protections = useQuery(useCallback(signal => api.protections(signal), [api])) + const connectionId = useSearchParams().get("connection") ?? "" + const admin = can("mm:mcp:admin") + const [kind, setKind] = useState("server"), [objectId, setObjectId] = useState("") + const [protection, setProtection] = useState("human-approval-required"), [reason, setReason] = useState("") + const [protectionServerText, setProtectionServerText] = useState("") + const selected = connections.data?.connections.find(connection => connection.id === connectionId) + const protectionItems = protections.data?.protections ?? [] + const protectionServerId = Number(protectionServerText) + const validProtectionServer = /^\d+$/.test(protectionServerText) && Number.isSafeInteger(protectionServerId) && protectionServerId > 0 + const addProtection = () => { + void api.protect({ kind, id: objectId, protection, ...(kind === "server" ? {} : { serverId: protectionServerId }) }, reason) + .then(protections.refresh, error => toast.error(errorText(error))) + } + return
+ + + { + const url = new URL(window.location.href) + if (value) url.searchParams.set("connection", value) + else url.searchParams.delete("connection") + window.history.replaceState(null, "", url.pathname + url.search) + }}> + + {connections.data?.connections.map(connection => )} + + {connectionId && connections.data && !selected &&

Подключение отсутствует в доступном списке.

} + {selected &&
Открыть обращения подключения
} + {selected && admin && } + {selected && admin && selected.ownerId === getClaims()?.sub && } + {!admin &&

Симуляция политики и управление защитой доступны администратору MCP.

} +
+ +
{protectionItems.map(item =>
{item.object_ref.kind} · {item.object_ref.id}{item.object_ref.serverId != null && ` · сервер ${item.object_ref.serverId}`} · {item.object_ref.protection === "deny" ? "Запрет изменений" : "Подтверждение человеком"}{item.reason}{admin && }
)}
+ {admin && <> +
+ setKind(event.target.value)} /> + setObjectId(event.target.value)} /> + {kind !== "server" && setProtectionServerText(event.target.value)} />} + + setReason(event.target.value)} /> +
+ + } +
+
+} +function OperationRecovery({ api, operationId }: { api: McpApi; operationId: string }) { + const [id, setId] = useState(operationId), [result, setResult] = useState(null), [error, setError] = useState(""), [busy, setBusy] = useState(false) + const target = id.trim() + const validId = mcpPageQuerySchema.shape.operationId.safeParse(target).success + const run = async (recover: boolean) => { + if (busy || !validId) return + setBusy(true); setError(""); setResult(null) + try { setResult(recover ? await api.recoverOperation(target) : await api.reconcileOperation(target)) } catch (failure) { setError(errorText(failure)) } finally { setBusy(false) } + } + return
+ + + { setId(event.target.value); setResult(null); setError("") }} /> + {target && !validId &&

Укажите UUID операции из журнала.

} +
+ + +
+ {result !== null &&
{pretty(result)}
} +
+
+} +function ManagementChannels({ api }: { api: McpApi }) { + const channels = useQuery(useCallback(signal => api.managementChannels(signal), [api])) + const [serverId, setServerId] = useState(""), [host, setHost] = useState(""), [port, setPort] = useState(443), [ssl, setSsl] = useState(true), [username, setUsername] = useState(""), [password, setPassword] = useState(""), [attestation, setAttestation] = useState("") + const [expiry, setExpiry] = useState(() => new Date(Date.now() + 1800000).toISOString().slice(0, 16)), [busy, setBusy] = useState(false), [error, setError] = useState("") + const register = async () => { + setBusy(true); setError("") + try { await api.registerManagement({ serverId: Number(serverId), host, port, useSsl: ssl, verifySsl: true, username, password, attestation, expiresAt: new Date(expiry + "Z").toISOString() }); setPassword(""); channels.refresh(); toast.success("Канал проверен по идентичности RouterOS и зарегистрирован") } catch (failure) { setError(errorText(failure)) } finally { setBusy(false) } + } + return date(row.original.verified_at) }, { accessorKey: "expires_at", header: "Допуск до", cell: ({ row }) => date(row.original.expires_at) }, { id: "action", header: "Доступ", cell: ({ row }) => row.original.revoked_at ? "Отозван" : }]} />{can("mm:network:admin") && <>
setServerId(event.target.value)} /> setHost(event.target.value)} /> setPort(Number(event.target.value))} /> setUsername(event.target.value)} /> setPassword(event.target.value)} /> setExpiry(event.target.value)} />