From 6cb550e179b1b349a7d889317c81acaf3c515647 Mon Sep 17 00:00:00 2001
From: Denozordec
Date: Sun, 15 Nov 2026 20:36:14 +0700
Subject: [PATCH] =?UTF-8?q?feat(mcp):=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2?=
=?UTF-8?q?=D0=B8=D1=82=D1=8C=20=D0=B2=D0=B5=D0=B1-=D1=80=D0=B0=D0=B7?=
=?UTF-8?q?=D0=B4=D0=B5=D0=BB=20MCP,=20=D0=BA=D0=BB=D0=B8=D0=B5=D0=BD?=
=?UTF-8?q?=D1=82=D1=81=D0=BA=D0=B8=D0=B9=20API=20=D0=B8=20e2e-=D1=82?=
=?UTF-8?q?=D0=B5=D1=81=D1=82=D1=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Sonnet 5.5
---
app/(main)/ipsec/page.tsx | 77 +-
app/(main)/mcp/page.tsx | 6 +
app/(main)/traffic/page.tsx | 15 +-
app/(main)/users/page.tsx | 6 +-
app/globals.css | 11 +-
components/auth-guard.tsx | 11 +-
.../data-grids/users-expanded-detail.tsx | 6 +
components/flag.tsx | 16 +-
components/ipsec/ipsec-cert-sheet.tsx | 96 +-
components/ipsec/ipsec-server-grid.tsx | 2 +-
components/logs/log-detail-sheet.tsx | 5 +-
components/logs/logs-workspace.tsx | 13 +-
components/mcp/artifact-downloads.tsx | 42 +
components/mcp/bridge-vlan-workflow.tsx | 156 +++
components/mcp/database-restore.tsx | 102 ++
components/mcp/mcp-workspace.tsx | 802 +++++++++++
components/mcp/object-permission-preview.tsx | 71 +
components/mcp/plan-review.tsx | 18 +
components/mcp/poll-storage-capacity.tsx | 25 +
.../settings/system-database-section.tsx | 6 +-
components/users/user-sheet.tsx | 31 +-
hooks/use-flow-live.ts | 46 +-
hooks/use-router-logs.ts | 54 +-
lib/auth-mcp.test.ts | 14 +
lib/auth.ts | 3 +-
lib/data.ts | 2 +-
lib/navigation.ts | 1 +
lib/server-operations.ts | 4 +-
lib/user-save.ts | 5 +-
lib/users.ts | 5 +-
lib/vxlan-export.test.ts | 3 +
lib/vxlan-response.ts | 2 +-
package-lock.json | 255 ++++
package.json | 5 +-
playwright.config.ts | 2 +
playwright.ipsec-export.config.ts | 16 +
playwright.mcp-auth.config.ts | 24 +
playwright.mcp.config.ts | 9 +
shared/api/http-client.ts | 16 +-
shared/api/ipsec-export.test.ts | 105 ++
shared/api/ipsec.ts | 28 +-
shared/api/logs.ts | 9 +-
shared/api/mcp-artifact.test.ts | 78 ++
shared/api/mcp-artifact.ts | 97 ++
shared/api/mcp-capacity.test.ts | 17 +
shared/api/mcp.ts | 65 +
shared/api/servers.ts | 3 +-
shared/api/system-database.ts | 2 +-
shared/api/users.ts | 3 +-
tests/e2e/bgp-context.spec.ts | 4 +-
tests/e2e/bridge-vlan/mcp-context.spec.ts | 177 +++
.../plan-review/mcp-context.spec.ts | 111 ++
.../bridge-vlan/sdk-public-plan.fixture.json | 261 ++++
tests/e2e/filters-context.spec.ts | 4 +-
tests/e2e/firewall-context.spec.ts | 7 +-
tests/e2e/fixtures/mcp-test-fonts.cjs | 8 +
tests/e2e/fixtures/open-settings.ts | 14 +
tests/e2e/gre-context.spec.ts | 4 +-
tests/e2e/ipsec-cert.spec.ts | 171 ++-
tests/e2e/ipsec-context.spec.ts | 4 +-
tests/e2e/logs-context.spec.ts | 119 +-
tests/e2e/mcp-auth-context.spec.ts | 392 ++++++
tests/e2e/mcp-context.spec.ts | 1193 +++++++++++++++++
tests/e2e/network-map-context.spec.ts | 3 +-
.../object-permissions/mcp-context.spec.ts | 59 +
tests/e2e/ospf-context.spec.ts | 5 +-
tests/e2e/recursive-routes-context.spec.ts | 3 +-
tests/e2e/route-optimizer-context.spec.ts | 3 +-
tests/e2e/servers.spec.ts | 4 +-
tests/e2e/system-database-receipt.spec.ts | 13 +-
tests/e2e/traffic-flow.spec.ts | 39 +-
tests/e2e/users-operations.spec.ts | 27 +
tests/e2e/vxlan-context.spec.ts | 4 +-
tests/e2e/wireguard-context.spec.ts | 3 +-
tests/unit/flow-live-admission.test.ts | 54 +
tests/unit/server-poll-batch.test.ts | 15 +
tsconfig.json | 47 +-
77 files changed, 4929 insertions(+), 209 deletions(-)
create mode 100644 app/(main)/mcp/page.tsx
create mode 100644 components/mcp/artifact-downloads.tsx
create mode 100644 components/mcp/bridge-vlan-workflow.tsx
create mode 100644 components/mcp/database-restore.tsx
create mode 100644 components/mcp/mcp-workspace.tsx
create mode 100644 components/mcp/object-permission-preview.tsx
create mode 100644 components/mcp/plan-review.tsx
create mode 100644 components/mcp/poll-storage-capacity.tsx
create mode 100644 lib/auth-mcp.test.ts
create mode 100644 playwright.ipsec-export.config.ts
create mode 100644 playwright.mcp-auth.config.ts
create mode 100644 playwright.mcp.config.ts
create mode 100644 shared/api/ipsec-export.test.ts
create mode 100644 shared/api/mcp-artifact.test.ts
create mode 100644 shared/api/mcp-artifact.ts
create mode 100644 shared/api/mcp-capacity.test.ts
create mode 100644 shared/api/mcp.ts
create mode 100644 tests/e2e/bridge-vlan/mcp-context.spec.ts
create mode 100644 tests/e2e/bridge-vlan/plan-review/mcp-context.spec.ts
create mode 100644 tests/e2e/bridge-vlan/sdk-public-plan.fixture.json
create mode 100644 tests/e2e/fixtures/mcp-test-fonts.cjs
create mode 100644 tests/e2e/fixtures/open-settings.ts
create mode 100644 tests/e2e/mcp-auth-context.spec.ts
create mode 100644 tests/e2e/mcp-context.spec.ts
create mode 100644 tests/e2e/object-permissions/mcp-context.spec.ts
create mode 100644 tests/unit/flow-live-admission.test.ts
create mode 100644 tests/unit/server-poll-batch.test.ts
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 ?
void onReexport(randomPassphrase())}>Повторить экспорт : null
+ !busy && onReexport ? (
+
+
Экспорт .p12 включает закрытый ключ. Подтвердите его получение перед запросом к роутеру.
+
{previousAttemptFailed ? "Подготовить новый запрос" : "Экспортировать .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 && (
+
+
+ Отдельно разрешаю экспорт закрытого ключа центра сертификации CA. Его владелец может подписывать другие сертификаты.
+
+ )}
+ {previousAttemptFailed && (
+
+
Результат предыдущего запроса может быть неизвестен. Новый запрос не продолжает и не подтверждает предыдущую попытку.
+
+
+ Я проверил состояние роутера и явно запрашиваю новый экспорт.
+
+
+ )}
+
+ setConfirmationOpen(false)}>Отмена
+ void confirmExport()}>{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 ? (
void }) {
const [context, setContext] = useState> | null>(null), [error, setError] = useState(null), [retry, setRetry] = useState(0)
+ const { id, serverId } = entry
useEffect(() => {
const ac = new AbortController()
- void getLogContext(base, entry.id, ac.signal).then(data => { if (!ac.signal.aborted) { setContext(data); setError(null) } }).catch(e => { if (!ac.signal.aborted) setError(e instanceof z.ZodError ? "Некорректный ответ контекста" : e.message) })
+ void getLogContext(base, { id, serverId }, ac.signal).then(data => { if (!ac.signal.aborted) { setContext(data); setError(null) } }).catch(e => { if (!ac.signal.aborted) setError(e instanceof z.ZodError ? "Некорректный ответ контекста" : e.message) })
return () => ac.abort()
- }, [base, entry.id, retry])
+ }, [base, id, serverId, retry])
const copy = () => { void navigator.clipboard.writeText(JSON.stringify(entry, null, 2)).then(() => toast.success("Событие скопировано"), () => toast.error("Не удалось скопировать событие")) }
return <>
diff --git a/components/logs/logs-workspace.tsx b/components/logs/logs-workspace.tsx
index bd617d43..099d8de4 100644
--- a/components/logs/logs-workspace.tsx
+++ b/components/logs/logs-workspace.tsx
@@ -127,7 +127,18 @@ function LogExplorer({ base, raw, selectedName, liveAvailable }: { base: string;
void doExport("csv")}> CSV void doExport("json")}>JSON
{range === "custom" && {["from", "to"].map(key => {key === "from" ? "Начало (UTC)" : "Конец (UTC)"} { if (event.target.value) navigate({ [key]: new Date(event.target.value + "Z").toISOString() }) }} /> )}
}
- {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 &&
{ if (paused) setPaused(false); else setPaused(true) }}>{paused ? : }{paused ? `Новых событий: ${result.pendingCount}` : "Пауза"} }
+
+ {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 &&
{ if (paused) setPaused(false); else setPaused(true) }}>{paused ? : }{paused ? `Новых событий: ${result.pendingCount}` : "Пауза"} }
+
+ {live && collectorEnabled === true && result.streamReceivedAt !== null &&
+ Получено (live-поток): {formatLogTime(new Date(result.streamReceivedAt).toISOString())}
+
}
{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
+
{ void download() }}>{busy ? "Скачивание…" : "Скачать файл"}
+ {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 onChange(value === true)} />{label}
+}
+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) => {label} {
+ const item = options.find(item => keyOf(item) === event.target.value)
+ if (item) onChange({ resource: item.resource, id: item.id })
+ }}>{portOptions.map(item => {item.name} · {item.resource} {item.id} )}
+ 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}
}
+
+ Существующий мост chooseBridge(event.target.value)}>Выберите мост {state?.bridges.map(row => {text(row, "name")} · {text(row, ".id")} )}
+ setReload(value => value + 1)}>Перечитать и сбросить черновик
+
+ {loading && Чтение состояния…
}
+ {draft && state &&
+ edit(value => ({ ...value, filtering }))} />PVID моста edit(value => ({ ...value, pvid: Number(event.target.value) }))} />
+ Статические порты
+ {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) })))}
+ PVID порта edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, pvid: Number(event.target.value) } : item) }))} />
+ Типы кадров edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, frameTypes: event.target.value as typeof port.frameTypes } : item) }))}>Все Только tagged Untagged и priority tagged
+ 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) }))} /> edit(value => ({ ...value, ports: value.ports.filter((_, i) => i !== index), removePortIds: port.id ? [...value.removePortIds, port.id] : value.removePortIds }))}>Удалить порт из плана
+ )}
+ { if (nextPort) edit(value => ({ ...value, ports: [...value.ports, { interface: { resource: nextPort.resource, id: nextPort.id }, pvid: 1, ingressFiltering: true, frameTypes: "admit-all", disabled: false }] })) }}>Добавить порт
+ Статические участники 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"}
+ VLAN ID или диапазоны (например, 10,20–30) update({ vlanIds: event.target.value })} />
+ {membership("Tagged, включая CPU-порт моста при необходимости", vlan.tagged, tagged => update({ tagged }))}
+ {membership("Untagged", vlan.untagged, untagged => update({ untagged }))}
+ update({ disabled })} /> edit(value => ({ ...value, vlans: value.vlans.filter((_, i) => i !== index), removeVlanIds: vlan.id ? [...value.removeVlanIds, vlan.id] : value.removeVlanIds }))}>Удалить запись VLAN из плана
+
+ })}
+ edit(value => ({ ...value, vlans: [...value.vlans, { vlanIds: "", tagged: [], untagged: [], disabled: false }] }))}>Добавить запись VLAN
+ {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(", ") || "нет"}. Для отмены удаления перечитайте состояние.
}
+ { void prepare() }}>{busy ? "Подготовка…" : "Подготовить связанный план VLAN"}
+ }
+ {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}
}
+ Подключение для восстановления
+ { setConnectionId(event.target.value); clearResult() }}>Выберите свой глобальный допуск {connections.map(item => {item.name} )}
+
+ Архив PostgreSQL, до 64 МиБ
+ { setFile(event.target.files?.[0] ?? null); setArchive(null); clearResult() }} />
+
+ {file && !validFile && Выберите непустой архив размером до 64 МиБ.
}
+
+ Загрузить архив
+ Подготовить план восстановления БД
+
+ {archive && SHA-256: {archive.sha256} · Допуск до {new Date(archive.expiresAt).toLocaleString()}
}
+ {expired && Срок архива истёк. Загрузите архив снова для нового плана.
}
+ ID операции восстановления БД { setOperationId(event.target.value); clearResult() }} />
+ { void run(signal => api.restoreReceipt(receiptId, signal)) }}>Прочитать внешнюю квитанцию
+ {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 {label} {children} }
+function Choice({ label, checked, onChange }: { label: string; checked: boolean; onChange: (value: boolean) => void }) { return onChange(!!checked)} />{label} }
+function NativeSelect({ label, value, onChange, children }: { label: string; value: string; onChange: (value: string) => void; children: ReactNode }) {
+ return onChange(event.target.value)}>{children}
+}
+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 => {connection.name} )} {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 => {server.name} · {server.host} )}Выберите тип {catalog.data?.resources.filter(resource => resource.read).map(resource => {resource.title} )}
{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 &&
open("new")}> Создать объект }
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) }} /> { setOffset(Math.max(0, offset - 100)); setEditing(null) }}>Предыдущие объекты { if (rows.data?.nextOffset != null) setOffset(rows.data.nextOffset); setEditing(null) }}>Следующие объекты
{editing && {editing === "new" ? "Новый объект" : `Объект ${String(current?.[".id"])}`}
{current &&
Текущие свойства {pretty(current)} }{protectedRow ?
Системный или динамический объект доступен для чтения.
: <>
В план попадут только заполненные изменения. Пустой выбор оставляет свойство без изменения; при создании действует настройка устройства.
{editableFields.map(field => {field.type === "boolean" || field.options ? change(field.key, event.target.value === "" ? undefined : field.type === "boolean" ? event.target.value === "true" : event.target.value)}>{ethernetDisabledUnknown && field.key === "disabled" ? "Текущее значение неизвестно" : current ? `Сейчас: ${String(current[field.key])}` : "По умолчанию устройства"} {(field.options ?? ["true", "false"]).map(value => {value} )} : 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) && { void prepare(editing === "new" ? "create" : "update") }}>Подготовить план изменения }{current && !protectedRow && resource.delete && { void prepare("delete") }}>Подготовить план удаления } setEditing(null)}>Закрыть объект
}>
+}
+function TokenDialog({ token, close, connectionName }: { token: string; close: () => void; connectionName?: string }) {
+ return { if (!open) close() }}>Доступ создан {connectionName && `Подключение «${connectionName}». `}Сохраните токен в настройках AI-клиента. Повторно посмотреть его нельзя. { void navigator.clipboard.writeText(token).then(() => toast.success("Токен скопирован"), () => toast.error("Не удалось скопировать токен")) }}> Копировать Закрыть и скрыть токен
+}
+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]) => {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 > 1 ? setStep(step - 1) : close()}>{step > 1 ? "Назад" : "Отмена"} {step < 4 ? setStep(step + 1)}>Далее : { void save() }}>{busy ? "Сохранение…" : "Сохранить доступ"} }
+
+}
+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 && { void act(() => api.revalidate(connection.id)) }}>Обновить мои права }
} },
+ { id: "actions", header: "Действия", size: 350, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return admin && setEditing(connection)}>Разрешения { void act(() => api.status(connection.id, connection.policy.status === "active" ? "paused" : "active")) }}>{connection.policy.status === "active" ? "Пауза" : "Включить"} { if (window.confirm("Отозвать доступ подключения и все его токены?")) void act(() => api.status(connection.id, "revoked")) }}>Отозвать { if (window.confirm("Заменить токен? Старый токен перестанет работать.")) void act(async () => setToken((await api.rotate(connection.id)).token)) }}>Новый токен
} },
+ ], [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.name} )}
+
+ {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)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.
+ { void api.revalidate(connectionId).then(() => { grants.refresh(); toast.success("Права владельца обновлены") }, error => toast.error(errorText(error))) }}>Подтвердить текущие права владельца
+ { void check() }}>Проверить готовность доступа
+ {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 ? "отозван" : "выдан"}
+ { void api.revokeGrant(grant.id).then(grants.refresh, error => toast.error(errorText(error))) }}>Отозвать допуск
+
)}
+ >
+}
+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 => {connection.name} )} setName(event.target.value)} /> setServerId(event.target.value)} /> setCommunity(event.target.value)} placeholder="65000:10" /> setFamily(value as typeof family)}>IPv4 IPv6 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))}>GRE Рекурсивный IPv4 Рекурсивный IPv6 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.filter(value => value.id !== candidate.id)); setExcluded(values => values.filter(value => value !== candidate.id)); if (pin === candidate.id) setPin("") }}>Удалить путь
)}
+ setCandidates(values => values.map(candidate => candidate.id === id ? { ...candidate, controlProbe } : candidate))} />= 100} onClick={() => setCandidates(values => [...values, { ...values[0], id: crypto.randomUUID(), gateway: "", gatewayRef: { ...values[0].gatewayRef, id: "" } }])}>Добавить путь {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) => Путь {index + 1} )}
setExpires(event.target.value)} /> { void save() }}>{busy ? "Подготовка…" : "Подготовить план профиля"} >}
+}
+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 => {String((profile.config as RecordRow)?.name ?? profile.id)} )}
+ { invalidate(); setCandidateId(value) }}>Выберите путь {candidates.map(candidate => {candidate.id} )}
+ { invalidate(); setProofPurpose(value as typeof proofPurpose) }}>Путь Community Самостоятельный контрольный путь
+
+ {proofPurpose === "control-path" ? "Проверяется только контрольный путь. Результат не разрешает переключение Community и не подтверждает обратный путь." : "Проверка учитывает Community, таблицу маршрутизации и BGP. Применение изменений требует отдельного плана; обратный путь проверяется отдельно."}
+ { void check() }}>Проверить контрольный путь
+ {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") && { void api.pauseProfile(String(row.original.id)).then(query.refresh, error => toast.error(errorText(error))) }}>Остановить },
+ ], [api, query.refresh])
+ return <> setEditing("new")}>Создать профиль}>Контроллер учитывает свежесть измерений, закрепления, SLA, гистерезис, cooldown и бюджет переключений. Неизвестный фактический путь не считается подтверждённым.
{ if (!open) setSelected(null) }}>Профиль Route AI Сохранённые параметры и последнее решение контроллера {pretty(selected)} {can("mm:mcp:admin") && can("mm:network:write") && { setEditing(selected); setSelected(null) }}>Изменить профиль } {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(row.original)}>Открыть },
+ ], [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 ?? "—"}
+
+ setFilter("cursor", "")}>В начало
+ setFilter("cursor", query.data?.nextCursor ?? "")}>Далее
+
+
+ { 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") && { void submitPlan("apply") }}>Применить план }
+ {kind === "plans" && selected?.state === "awaiting-approval" && can("mm:mcp:approve") && { void submitPlan("approve") }}>Подтвердить план { void submitPlan("reject") }}>Отклонить
}
+
+
+
+ )
+}
+
+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 => {stepStates[String(step.state)] ?? String(step.state)}{step.server_id != null && ` · сервер ${step.server_id}`}{step.finished_at != null && ` · ${date(step.finished_at)}`} )}
+
+ {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.title} · {operation.id} )}
+
+ {operation?.scope === "servers" && { invalidate(); setServerText(event.target.value) }} /> }
+
+ {operation && {{ connection: "Область операции — подключение", global: "Область операции — всё приложение", servers: "Область операции — выбранные серверы" }[operation.scope]}
}
+ { void preview() }}> Проверить
+ {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
+}
+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
+}
+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 ? "Отозван" : { void api.revokeManagement(String(row.original.id)).then(channels.refresh, failure => toast.error(errorText(failure))) }}>Отозвать канал }]} />{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)} />
{ void register() }}>Проверить и зарегистрировать канал >}
+}
+function Settings({ api }: { api: McpApi }) {
+ const query = useQuery(useCallback(signal => api.settings(signal), [api])), clients = useQuery(useCallback(signal => api.clients(signal), [api]))
+ const [name, setName] = useState(""), [redirect, setRedirect] = useState("")
+ const save = async (value: unknown) => { try { await api.saveSettings(value); query.refresh() } catch (error) { toast.error(errorText(error)) } }
+ return
+}
+function RestCoverage({ api }: { api: McpApi }) {
+ const query = useQuery(useCallback(signal => api.coverage(signal), [api])), routes = query.data?.routes ?? []
+ return Сценариев с MCP: {routes.filter(route => route.status === "mediated").length} Транспорт и управление доступом: {routes.filter(route => route.status === "excluded").length} Ожидают реализации: {routes.filter(route => route.status === "pending").length}
route.status === "pending")} columns={[{ accessorKey: "method", header: "Метод", size: 90 }, { accessorKey: "path", header: "Незавершённый сценарий", size: 310 }, { accessorKey: "reason", header: "Что осталось", size: 400 }]} loading={!query.data && !query.error} />
+}
+function Consent({ api, id }: { api: McpApi; id: string }) {
+ const request = useQuery(useCallback(signal => api.consentRequest(id, signal), [api, id])), connections = useQuery(useCallback(signal => api.connections(signal), [api]))
+ const [selected, setSelected] = useState("")
+ const [busy, setBusy] = useState(false)
+ const [consentToken] = useState(getToken)
+ const [sessionChanged, setSessionChanged] = useState(false)
+ const submitting = useRef(false)
+ const mounted = useRef(false)
+ useEffect(() => {
+ mounted.current = true
+ return () => { mounted.current = false }
+ }, [])
+ const currentRequest = !sessionChanged && !request.error && request.data?.id === id ? request.data : null
+ const ownerId = getClaims()?.sub
+ const [now, setNow] = useState(() => Date.now())
+ const active = connections.error ? [] : connections.data?.connections.filter(connection => connection.ownerId === ownerId && connection.policy.status === "active" && connection.generationValid) ?? []
+ const nextExpiry = active.reduce((earliest, connection) => {
+ const deadline = connectionAccessDeadline(connection)
+ return deadline > now ? Math.min(earliest, deadline) : earliest
+ }, Infinity)
+ useEffect(() => {
+ if (!Number.isFinite(nextExpiry)) return
+ const schedule = () => window.setTimeout(() => setNow(Date.now()), Math.min(60000, Math.max(0, nextExpiry - Date.now() + 1)))
+ const timer = schedule()
+ return () => window.clearTimeout(timer)
+ }, [nextExpiry, now])
+ const eligible = active.filter(connection => connectionAccessDeadline(connection) > now)
+ const canDeny = currentRequest !== null
+ const canApprove = canDeny && eligible.some(connection => connection.id === selected)
+ const isCurrentLocation = () => mounted.current && new URLSearchParams(window.location.search).get("oauthRequest") === id
+ const verifySession = () => {
+ if (consentToken && getToken() === consentToken && getClaims()?.sub) return true
+ setSessionChanged(true)
+ return false
+ }
+ const confirm = async (approve: boolean) => {
+ if (!(approve ? canApprove : canDeny) || submitting.current || !isCurrentLocation()) return
+ if (!verifySession()) return
+ if (approve && !eligible.some(connection => connection.id === selected && connectionAccessDeadline(connection) > Date.now())) return
+ submitting.current = true
+ setBusy(true)
+ try {
+ const result = await api.consent(id, approve ? { approve: true, connectionId: selected } : { approve: false })
+ if (!isCurrentLocation()) return
+ if (verifySession()) window.location.assign(result.redirectUrl)
+ else setBusy(false)
+ } catch (error) {
+ if (!mounted.current) return
+ submitting.current = false
+ setBusy(false)
+ if (isCurrentLocation() && verifySession()) toast.error(errorText(error))
+ }
+ }
+ return
+
+ {currentRequest && <>{currentRequest.name} запрашивает доступ к MikrotikManager.
Возврат: {currentRequest.redirect_uri}
>}
+
+ Выберите ограниченный доступ
+ {!sessionChanged && eligible.map(connection => {connection.name} · {modeLabels[connection.policy.mode]} )}
+
+
+ { void confirm(true) }}>Разрешить
+ { void confirm(false) }}>Отклонить
+
+
+}
+export function McpWorkspace() {
+ const { backendUrl, mode } = useDataSource()
+ return
+}
+function McpWorkspaceContent({ backendUrl, live }: { backendUrl: string; live: boolean }) {
+ const params = useSearchParams(), requestedTab = params.get("tab") as Tab | null
+ const oauthRequestId = params.get("oauthRequest")
+ const admin = can("mm:mcp:admin")
+ const tab = requestedTab && Object.hasOwn(tabs, requestedTab) && (requestedTab !== "settings" || admin) ? requestedTab : "overview"
+ const recoveryId = params.get("reconcile") ?? ""
+ const api = useMemo(() => mcpApi(backendUrl), [backendUrl])
+ const [operations, setOperations] = useState([]), [error, setError] = useState("")
+ useEffect(() => { if (!live) return; const controller = new AbortController(); void api.catalog(controller.signal).then(catalog => setOperations(catalog.operations), failure => { if (!controller.signal.aborted) setError(errorText(failure)) }); return () => controller.abort() }, [api, live])
+ const changeTab = (value: unknown) => { const next = String(value); const url = new URL(window.location.href); url.searchParams.set("tab", next); window.history.replaceState(null, "", url.pathname + url.search) }
+ return <>MCP Доступ нейросетей, разрешения и контроль изменений
{!live ? Для выдачи реального AI-доступа выберите режим «Живые» и настройте авторизацию портала.
: <> {oauthRequestId && }{Object.entries(tabs).filter(([key]) => key !== "settings" || can("mm:mcp:admin")).map(([key, title]) => {title} )}
{can("mm:mcp:admin") &&
}
{admin && }
{can("mm:mcp:admin") && {can("mm:settings:admin") && }
} >} >
+}
diff --git a/components/mcp/object-permission-preview.tsx b/components/mcp/object-permission-preview.tsx
new file mode 100644
index 00000000..fcbf49de
--- /dev/null
+++ b/components/mcp/object-permission-preview.tsx
@@ -0,0 +1,71 @@
+"use client"
+
+import { useEffect, useState } from "react"
+import { mcpObjectRefSchema, type McpConnection, type McpOperationDescriptor, type McpPolicyDecision } from "@mmapp/contracts/mcp"
+import type { McpApi } from "@/shared/api/mcp"
+import { Badge } from "@/components/reui/badge"
+import { Button } from "@/components/ui/button"
+import { Input } from "@/components/ui/input"
+
+type Catalog = Awaited>
+type Rows = Awaited>
+export function ObjectPermissionPreview({ api, connection, operations, editable, onProtected }: {
+ api: McpApi; connection: McpConnection; operations: McpOperationDescriptor[]; editable: boolean; onProtected: () => void
+}) {
+ const [catalog, setCatalog] = useState(null), [rows, setRows] = useState(null)
+ const [server, setServer] = useState(""), [resource, setResource] = useState(""), [nativeId, setNativeId] = useState("")
+ const [operation, setOperation] = useState(""), [offset, setOffset] = useState(0), [protection, setProtection] = useState("human-approval-required"), [reason, setReason] = useState("")
+ const [error, setError] = useState(""), [busy, setBusy] = useState(false), [result, setResult] = useState(null), [receipt, setReceipt] = useState("")
+ useEffect(() => {
+ const controller = new AbortController()
+ api.deviceCatalog(connection.id, controller.signal).then(value => { if (!controller.signal.aborted) setCatalog(value) }, failure => { if (!controller.signal.aborted) setError(String(failure.message ?? failure)) })
+ return () => controller.abort()
+ }, [api, connection.id])
+ useEffect(() => {
+ if (!server || !resource) return
+ const controller = new AbortController()
+ api.deviceRows(connection.id, server, resource, offset, controller.signal).then(value => { if (!controller.signal.aborted) setRows(value) }, failure => { if (!controller.signal.aborted) setError(String(failure.message ?? failure)) })
+ return () => controller.abort()
+ }, [api, connection.id, server, resource, offset])
+ const reset = () => { setNativeId(""); setRows(null); setResult(null); setReceipt(""); setError("") }
+ const changeServer = (value: string) => { reset(); setServer(value); setOffset(0) }
+ const changeResource = (value: string) => { reset(); setResource(value); setOffset(0) }
+ const availableRows = (rows?.items ?? []).filter(row => typeof row[".id"] === "string" && row[".id"] !== "")
+ const selected = availableRows.find(row => row[".id"] === nativeId)
+ const ready = !!selected && catalog?.servers.some(value => String(value.id) === server) && catalog.resources.some(value => value.id === resource && value.read)
+ const act = async (save: boolean) => {
+ if (!ready) return
+ setBusy(true); setError(""); setResult(null); setReceipt("")
+ try {
+ const object = mcpObjectRefSchema.parse({ kind: resource, id: nativeId, serverId: Number(server) })
+ if (save) { await api.protect({ ...object, protection }, reason); onProtected(); setReceipt(`Защита сохранена: сервер ${server}, ${resource}, ${nativeId}.`) }
+ else {
+ setResult((await api.preview({ connectionId: connection.id, operationId: operation, target: { scope: "servers", serverIds: [Number(server)] }, objects: [object], objectCount: 1 })).result)
+ }
+ } catch (failure) { setError(failure instanceof Error ? failure.message : "Не удалось проверить объект") } finally { setBusy(false) }
+ }
+ const selectClass = "h-9 min-w-0 rounded-md border border-input bg-background px-2 text-sm"
+ return
+ Объект устройства
+ Выберите объект по данным своего подключения. Проверка гипотетическая: она учитывает выбранный объект и сохранённые защиты. Реальный план дополнительно проверяет зависимости. Выбор объекта не ограничивает токен или временный допуск этим объектом.
+ {error && {error}
}
+
+ Сервер проверяемого объекта changeServer(event.target.value)}>Выберите сервер {catalog?.servers.map(value => {value.name} · {value.id} )}
+ Тип проверяемого объекта changeResource(event.target.value)}>Выберите тип {catalog?.resources.filter(value => value.read).map(value => {value.title} )}
+ Стабильный ID объекта { setNativeId(event.target.value); setResult(null); setReceipt("") }}>{rows && !availableRows.length ? "Нет объектов на странице" : "Выберите объект"} {availableRows.map(row => {String(row.name ?? row.address ?? row.interface ?? resource)} · {String(row[".id"])} )}
+ Операция над объектом { setOperation(event.target.value); setResult(null) }}>Выберите действие {operations.filter(value => value.scope === "servers" && connection.policy.scope.operationIds.includes(value.id)).map(value => {value.id} )}
+
+ { reset(); setOffset(value => Math.max(0, value - 100)) }}>Предыдущая страница объектов { const next = rows?.nextOffset; if (next != null) { reset(); setOffset(next) } }}>Следующая страница объектов { void act(false) }}>Проверить выбранный объект
+ {result && }
+ {editable && <>Защита выбранного объекта setProtection(event.target.value)}>Подтверждение человеком Запрет изменений Причина защиты объекта setReason(event.target.value)} /> { void act(true) }}>Защитить выбранный объект >}
+ {receipt && {receipt}
}
+
+}
+
+export function PolicyPreviewDecision({ result }: { result: McpPolicyDecision }) {
+ return
+
{result.decision === "allowed" ? "Разрешено" : result.decision === "denied" ? "Запрещено" : "Нужно подтверждение"}
+ {result.reasons.length > 0 &&
{result.reasons.map((item, index) => {item.message} ({item.code}) )} }
+
Лимиты подключения: {result.limits.callsPerMinute} вызовов/мин · {result.limits.concurrentReads} параллельных чтения · {result.limits.mutationsPerHour} изменений/ч · до {result.limits.serversPerPlan} серверов и {result.limits.objectsPerPlan} объектов в плане.
+
+}
diff --git a/components/mcp/plan-review.tsx b/components/mcp/plan-review.tsx
new file mode 100644
index 00000000..292baba5
--- /dev/null
+++ b/components/mcp/plan-review.tsx
@@ -0,0 +1,18 @@
+import { Badge } from "@/components/reui/badge"
+
+const object = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}
+const list = (value: unknown): unknown[] => Array.isArray(value) ? value : []
+const json = (value: unknown) => JSON.stringify(value, null, 2)
+export function PlanReview({ plan }: { plan: Record }) {
+ const changes = object(plan.changes), target = object(changes.target)
+ const objects = list(changes.objects), steps = list(changes.steps), recovery = object(changes.recovery)
+ return
+
{String(plan.operationId ?? "Операция")} {String(plan.state ?? "Неизвестно")} Шагов: {steps.length}
+
Область {target.scope === "servers" ? "Серверы: " + list(target.serverIds).join(", ") : target.scope === "global" ? "Всё приложение" : "Подключение"}
Срок плана {plan.expiresAt ? new Date(String(plan.expiresAt)).toLocaleString("ru-RU") : "Не указан"}
+ {!!list(changes.warnings).length &&
Условия и последствия
{list(changes.warnings).map((warning, index) => {String(warning)} )} }
+ {!!objects.length &&
Объекты и защищённые зависимости {objects.map((value, index) => { const item = object(value); return {item.serverId ? `Сервер ${item.serverId} · ` : ""}{String(item.kind)} · {String(item.id)} })}
}
+
Исходное состояние {json(changes.before ?? changes.snapshots ?? null)} Запланированные шаги {steps.map((value, index) => { const step = object(value); return {index + 1}. {step.kind === "ros" ? String(object(step.step).action) + " · " + String(object(step.step).resource) : String(step.service)}
{json(step.kind === "ros" ? step.step : step.input)} })}
+ {!!Object.keys(recovery).length &&
Зарезервировано восстановление до {new Date(String(recovery.validUntil)).toLocaleString("ru-RU")}. Оно выполняется только при подтверждённой исходной записи, неуспешной проверке и действующем допуске; неопределённую запись исполнитель не повторяет.
}
+
Полные данные плана {json(plan)}
+
+}
diff --git a/components/mcp/poll-storage-capacity.tsx b/components/mcp/poll-storage-capacity.tsx
new file mode 100644
index 00000000..69ff011d
--- /dev/null
+++ b/components/mcp/poll-storage-capacity.tsx
@@ -0,0 +1,25 @@
+import type {McpPollStorageCapacity} from "@mmapp/contracts/mcp"
+import {Badge} from "@/components/reui/badge"
+import {Button} from "@/components/ui/button"
+
+export function PollStorageCapacity({capacity,loading,refresh}:{capacity?:McpPollStorageCapacity;loading:boolean;refresh:()=>void}){
+ const observed=capacity?.status==="observed"?capacity:undefined
+ const ownerFull=observed?.owner.remaining===0,globalFull=observed?.global.exhausted===true
+ const full=ownerFull||globalFull
+ return
+
+
Журнал полных опросов
+
{loading?"Загрузка":!observed?"Нет данных":full?"Квота заполнена":"Квота не заполнена"} Обновить статус
+
+ {observed?<>
+
+
Ваши полные журналы {observed.owner.used} / {observed.owner.limit}Осталось: {observed.owner.remaining}
+
Полные журналы приложения {observed.global.usage?<>{observed.global.usage.used} / {observed.global.usage.limit}Осталось: {observed.global.usage.remaining} >:globalFull?"Заполнена":"Не заполнена"}
+
+ {full&&{ownerFull&&globalFull?"Личная и общая квоты журнала заполнены.":ownerFull?"Личная квота журнала заполнена.":"Общая квота журнала заполнена."} Новый полный опрос не получит место. После безопасного архивирования или очистки по сроку хранения место может освободиться. Неизвестный результат сохраняет резерв; повторные попытки его не освобождают.
}
+ Счётчик учитывает резерв под выполнение и журналы, ожидающие архивирования. Архив сохраняет все исходные записи и продолжает занимать место. Поэтому остаток зависит и от объёма сохранённой истории.
+ Срок хранения новых записей: {observed.retentionDays} дн. Существующие записи могут храниться дольше. Архивирование сохраняет исходный срок; очистка учитывает завершение операции, истечение допуска и защитный интервал.
+ Состояние показано на момент обновления. Окончательный допуск проверяется при запуске.
+ >:{loading?"Проверяем заполнение журнала…":"Заполнение журнала сейчас недоступно. Свободное место не подтверждено; обновите статус позже."}
}
+
+}
diff --git a/components/settings/system-database-section.tsx b/components/settings/system-database-section.tsx
index a674cc87..9a57a9e2 100644
--- a/components/settings/system-database-section.tsx
+++ b/components/settings/system-database-section.tsx
@@ -48,7 +48,11 @@ function DatabaseForm({source}:{source:string}){
try{
const receipt=await restoreSystemDatabaseBackup(backendUrl,file,{signal,onDispatch:()=>{if(!current())throw Error("Источник изменился");sent=true;checkpoint(source,true);setUnknown(true)}})
if(!current())return;checkpoint(source,false)
- setUnknown(false);setFile(null);setOutcome("База приложения восстановлена");setWarnings([receipt.eventError,receipt.listenerError,receipt.schedulerError,receipt.cleanupError].filter((value):value is string=>!!value))
+ setUnknown(false);setFile(null)
+ setOutcome(receipt.maintenanceError || receipt.migrationError
+ ? "Завершение восстановления базы требует проверки"
+ : "База приложения восстановлена")
+ setWarnings([receipt.eventError,receipt.listenerError,receipt.schedulerError,receipt.cleanupError,receipt.maintenanceError,receipt.migrationError].filter((value):value is string=>!!value))
}catch(e){
const rejected=e instanceof ApiClientError&&[401,403,409,413].includes(e.status)
if(sent&&rejected&¤t())checkpoint(source,false)
diff --git a/components/users/user-sheet.tsx b/components/users/user-sheet.tsx
index dc435216..d36596dc 100644
--- a/components/users/user-sheet.tsx
+++ b/components/users/user-sheet.tsx
@@ -61,6 +61,9 @@ import {
const IFACE_TILE: 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" },
@@ -146,6 +149,7 @@ interface UserSheetProps {
users: AppUser[]
servers: UserServerOption[]
isLive: boolean
+ canManagePermissions: boolean
backendUrl: string
saving?: boolean
saveError?: string | null
@@ -157,13 +161,17 @@ interface UserSheetProps {
}
function UserSheet({
- open, user, users, servers, isLive, backendUrl, saving, saveError, saveBlocked, saveResume, onCheckCatalogs, onSave, onClose, returnFocus,
+ open, user, users, servers, isLive, canManagePermissions, backendUrl, saving, saveError, saveBlocked, saveResume, onCheckCatalogs, onSave, onClose, returnFocus,
}: UserSheetProps) {
const saveErrorRef = useRef(null)
useEffect(() => { if (saveError) saveErrorRef.current?.scrollIntoView({ block: "nearest" }) }, [saveError])
const isCreate = user === null
const [sheetStep, setSheetStep] = useState(1)
- const [form, setForm] = useState(() => (user ? toForm(user) : emptyForm(servers)))
+ const [form, setForm] = useState(() => {
+ if (user) return toForm(user)
+ const initial = emptyForm(servers)
+ return canManagePermissions ? initial : { ...initial, sections: [], servers: [] }
+ })
const [errors, setErrors] = useState>>({})
const [catalogServerId, setCatalogServerId] = useState(servers[0]?.id ?? "")
const [selectedPicks, setSelectedPicks] = useState([])
@@ -245,6 +253,7 @@ function UserSheet({
}
const isAdmin = form.role === "admin"
+ const permissionsReadOnly = isAdmin || !canManagePermissions
const validSelectedPicks = catalogReady ? selectedPicks.filter(pick => {
const iface = catalog.find(item => item.name === pick.interfaceName && item.type === pick.type)
@@ -372,8 +381,8 @@ function UserSheet({
/>
{errors.email && {errors.email} }
-
-
+ {canManagePermissions ?
+ /> : {ROLE_LABEL[form.role]}
}
Активный профиль
@@ -398,10 +407,10 @@ function UserSheet({
key={o.v}
type="button"
onClick={() => setAllSections(o.v)}
- disabled={isAdmin}
+ disabled={permissionsReadOnly}
className={cn(
"text-[11px] px-2 py-0.5 rounded border transition-colors",
- isAdmin ? "opacity-30 cursor-not-allowed" : "hover:bg-muted cursor-pointer",
+ permissionsReadOnly ? "opacity-30 cursor-not-allowed" : "hover:bg-muted cursor-pointer",
PERM_COLOR[o.v], "border-border",
)}
>
@@ -429,7 +438,7 @@ function UserSheet({
return (
{section}
-
setSectionPerm(section, v)} disabled={isAdmin} />
+ setSectionPerm(section, v)} disabled={permissionsReadOnly} />
)
})}
@@ -446,10 +455,10 @@ function UserSheet({
key={o.v}
type="button"
onClick={() => setAllServers(o.v)}
- disabled={isAdmin}
+ disabled={permissionsReadOnly}
className={cn(
"text-[11px] px-2 py-0.5 rounded border transition-colors",
- isAdmin ? "opacity-30 cursor-not-allowed" : "hover:bg-muted cursor-pointer",
+ permissionsReadOnly ? "opacity-30 cursor-not-allowed" : "hover:bg-muted cursor-pointer",
PERM_COLOR[o.v], "border-border",
)}
>
@@ -471,7 +480,7 @@ function UserSheet({
{srv.host} · {srv.site}
- setServerPerm(srv.id, v)} disabled={isAdmin} />
+ setServerPerm(srv.id, v)} disabled={permissionsReadOnly} />
)
})}
diff --git a/hooks/use-flow-live.ts b/hooks/use-flow-live.ts
index 9471b11a..b2e881fb 100644
--- a/hooks/use-flow-live.ts
+++ b/hooks/use-flow-live.ts
@@ -20,6 +20,45 @@ export function isValidFlowLiveSample(value: unknown): value is FlowAnalyticsDto
return parsed.success && [...parsed.data.rxSeries, ...parsed.data.txSeries].every(value => Number.isFinite(value) && value >= 0)
}
+const liveAdmissionDelaysMs = [250, 750, 1500]
+
+function waitForLiveAdmission(delayMs: number, signal: AbortSignal): Promise {
+ return new Promise((resolve, reject) => {
+ signal.throwIfAborted()
+ const abort = () => {
+ clearTimeout(timer)
+ reject(signal.reason)
+ }
+ const timer = setTimeout(() => {
+ signal.removeEventListener("abort", abort)
+ resolve()
+ }, delayMs)
+ signal.addEventListener("abort", abort, { once: true })
+ })
+}
+
+export async function openFlowLiveResponse(
+ url: string,
+ signal: AbortSignal,
+ request: typeof fetch = fetch,
+): Promise {
+ const open = () => {
+ signal.throwIfAborted()
+ return request(url, {
+ headers: withAuthHeaders({ Accept: "text/event-stream" }),
+ signal,
+ credentials: "include",
+ })
+ }
+ for (const delayMs of liveAdmissionDelaysMs) {
+ const response = await open()
+ if (response.status !== 429) return response
+ await response.body?.cancel()
+ await waitForLiveAdmission(delayMs, signal)
+ }
+ return open()
+}
+
export function useFlowLive(opts: {
enabled: boolean
backendUrl: string
@@ -64,13 +103,10 @@ export function useFlowLive(opts: {
void (async () => {
try {
- const res = await fetch(url, {
- headers: withAuthHeaders({ Accept: "text/event-stream" }),
- signal: ac.signal,
- credentials: "include",
- })
+ const res = await openFlowLiveResponse(url, ac.signal)
if (ac.signal.aborted) return
if (!res.ok || !res.body) {
+ await res.body?.cancel()
setError(`live HTTP ${res.status}`)
return
}
diff --git a/hooks/use-router-logs.ts b/hooks/use-router-logs.ts
index 2eebbc22..111bb806 100644
--- a/hooks/use-router-logs.ts
+++ b/hooks/use-router-logs.ts
@@ -9,13 +9,16 @@ export function mergeLogEntries(previous: LogEntry[], incoming: LogEntry[], limi
}
const message = (error: unknown) => error instanceof Error ? error.message : String(error)
export function useRouterLogs(base: string, query: string, enabled: boolean, live: boolean, paused: boolean, windowMs = 0) {
- const [entries, setEntries] = useState([]), [page, setPage] = useState(null)
- const [summary, setSummary] = useState(null), [stream, setStream] = useState(null)
+ const [entries, setEntries] = useState([])
+ const [page, setPage] = useState<{ data: LogPage; query: string; signal: AbortSignal } | null>(null)
+ const [summary, setSummary] = useState(null)
+ const [stream, setStream] = useState<{ batch: LogStream; receivedAt: number } | null>(null)
const [loading, setLoading] = useState(enabled), [fetchingMore, setFetchingMore] = useState(false)
- const [error, setError] = useState(null), [summaryError, setSummaryError] = useState(null), [streamError, setStreamError] = useState(null)
+ const [error, setError] = useState(null), [summaryError, setSummaryError] = useState(null)
+ const [streamFailure, setStreamFailure] = useState<{ message: string | null; stopped: boolean } | null>(null)
const [revision, setRevision] = useState(0), [pendingCount, setPendingCount] = useState(0)
const pending = useRef([]), pausedRef = useRef(paused), initialCursor = useRef(null)
- const lifetime = useRef(null), moreBusy = useRef(false)
+ const moreBusy = useRef(null)
useEffect(() => { pausedRef.current = paused }, [paused])
const flush = useCallback(() => { const buffered = pending.current; setEntries(prev => mergeLogEntries(prev, buffered).filter(row => !windowMs || Date.parse(row.effectiveAt) >= Date.now() - windowMs)); pending.current = []; setPendingCount(0) }, [windowMs])
useEffect(() => {
@@ -23,12 +26,13 @@ export function useRouterLogs(base: string, query: string, enabled: boolean, liv
}, [paused, flush])
useEffect(() => {
if (!enabled) return
- const ac = new AbortController(); lifetime.current = ac
- queueMicrotask(() => { if (!ac.signal.aborted) { setLoading(true); setError(null) } })
+ const ac = new AbortController()
+ queueMicrotask(() => { if (!ac.signal.aborted) { setLoading(true); setFetchingMore(false); setError(null) } })
const currentQuery = () => { const params = new URLSearchParams(query); if (windowMs) params.set("from", new Date(Date.now() - windowMs).toISOString()); return params }
- void getLogs(base, currentQuery(), ac.signal).then(data => {
+ const historyQuery = currentQuery()
+ void getLogs(base, historyQuery, ac.signal).then(data => {
if (ac.signal.aborted) return
- setEntries(data.entries); setPage(data); initialCursor.current = data.watermark
+ setEntries(data.entries); setPage({ data, query: historyQuery.toString(), signal: ac.signal }); initialCursor.current = data.watermark
}).catch(e => { if (!ac.signal.aborted) setError(message(e)) }).finally(() => { if (!ac.signal.aborted) setLoading(false) })
const readSummary = () => { void getLogSummary(base, currentQuery(), ac.signal).then(data => { if (!ac.signal.aborted) { setSummary(data); setSummaryError(null) } }).catch(e => { if (!ac.signal.aborted) setSummaryError(message(e)) }) }
readSummary()
@@ -69,7 +73,7 @@ export function useRouterLogs(base: string, query: string, enabled: boolean, liv
const data = block.split(/\r?\n/).filter(line => line.startsWith("data:")).map(line => line.slice(5).trim()).join("\n")
if (type === "reset") {
const reason = "Поток остановлен для обслуживания БД. После завершения обновите журнал, чтобы заново загрузить историю."
- if (!ac.signal.aborted) setError(reason)
+ if (!ac.signal.aborted) { setStream(null); setStreamFailure({ message: null, stopped: true }); setError(reason) }
return
}
if (type === "error") throw new Error(JSON.parse(data).error)
@@ -79,7 +83,7 @@ export function useRouterLogs(base: string, query: string, enabled: boolean, liv
if (batch.entries.some(row => String(row.serverId) !== expectedServer) || batch.state && String(batch.state.serverId) !== expectedServer || BigInt(batch.cursor) < BigInt(cursor)) throw new Error("Live-поток относится к другому устройству или содержит некорректный курсор")
heartbeat(); retry = 1000; cursor = batch.cursor
if (ac.signal.aborted) return
- setStream(batch); setStreamError(null)
+ setStream({ batch, receivedAt: Date.now() }); setStreamFailure(null)
if (batch.entries.length) {
if (pausedRef.current) {
pending.current = mergeLogEntries(pending.current, batch.entries)
@@ -93,8 +97,9 @@ export function useRouterLogs(base: string, query: string, enabled: boolean, liv
} finally { await reader.cancel().catch(() => {}) }
} catch (e) {
if (ac.signal.aborted) return
- setStreamError(message(e))
- if (e && typeof e === "object" && "status" in e && [401, 403, 404].includes(Number(e.status))) return
+ const stopped = e instanceof Error && "status" in e && [401, 403, 404].includes(Number(e.status))
+ setStreamFailure({ message: message(e), stopped })
+ if (stopped) { setStream(null); return }
} finally { clearTimeout(watchdog); connection.abort(); ac.signal.removeEventListener("abort", abort) }
await new Promise(resolve => {
const done = () => { clearTimeout(timer); ac.signal.removeEventListener("abort", done); resolve() }
@@ -107,17 +112,20 @@ export function useRouterLogs(base: string, query: string, enabled: boolean, liv
}, [base, query, enabled, live, ready, revision, windowMs])
const loadMore = useCallback(async () => {
- if (!page?.nextCursor || moreBusy.current || !enabled) return
- moreBusy.current = true; setFetchingMore(true)
- const signal = lifetime.current?.signal
+ if (!ready || !enabled || !page?.data.nextCursor || page.signal.aborted || moreBusy.current === page.signal) return
+ const { signal } = page
+ moreBusy.current = signal; setFetchingMore(true)
try {
- const params = new URLSearchParams(query); params.set("cursor", page.nextCursor); params.set("watermark", page.watermark)
+ const params = new URLSearchParams(page.query); params.set("cursor", page.data.nextCursor); params.set("watermark", page.data.watermark)
const data = await getLogs(base, params, signal)
- if (signal?.aborted) return
- setEntries(prev => mergeLogEntries(prev, data.entries)); setPage(data)
- } catch (e) { if (!signal?.aborted) setError(message(e)) }
- finally { moreBusy.current = false; if (!signal?.aborted) setFetchingMore(false) }
- }, [base, query, enabled, page])
- const reload = useCallback(() => { pending.current = []; setPendingCount(0); setRevision(n => n + 1) }, [])
- return { entries, summary, stream, loading, fetchingMore, error, summaryError, streamError, pendingCount, hasMore: !!page?.nextCursor && entries.length < 5000, loadMore, reload, flush }
+ if (signal.aborted) return
+ setEntries(prev => mergeLogEntries(prev, data.entries)); setPage({ ...page, data })
+ } catch (e) { if (!signal.aborted) setError(message(e)) }
+ finally {
+ if (moreBusy.current === signal) moreBusy.current = null
+ if (!signal.aborted) setFetchingMore(false)
+ }
+ }, [base, enabled, page, ready])
+ const reload = useCallback(() => { pending.current = []; setPendingCount(0); setStream(null); setStreamFailure(null); setRevision(n => n + 1) }, [])
+ return { entries, summary, stream: stream?.batch ?? null, streamReceivedAt: stream?.receivedAt ?? null, loading, fetchingMore, error, summaryError, streamError: streamFailure?.message ?? null, streamStopped: streamFailure?.stopped ?? false, pendingCount, hasMore: !!page?.data.nextCursor && entries.length < 5000, loadMore, reload, flush }
}
diff --git a/lib/auth-mcp.test.ts b/lib/auth-mcp.test.ts
new file mode 100644
index 00000000..a7c91d91
--- /dev/null
+++ b/lib/auth-mcp.test.ts
@@ -0,0 +1,14 @@
+import assert from "node:assert/strict"
+import { hasPermission, permissionForPath } from "./auth"
+
+for (const permission of ["read", "admin", "approve", "pause"]) {
+ assert.equal(hasPermission(["mm:settings:admin"], `mm:mcp:${permission}`), true)
+}
+assert.equal(hasPermission(["mm:mcp:admin"], "mm:mcp:read"), true)
+assert.equal(hasPermission(["mm:mcp:read"], "mm:mcp:admin"), false)
+assert.equal(hasPermission(["mm:network:write"], "mm:mcp:read"), false)
+assert.equal(permissionForPath("/mcp"), "mm:mcp:read")
+assert.equal(permissionForPath("/mcp/connections"), "mm:mcp:read")
+assert.notEqual(permissionForPath("/mcp-other"), "mm:mcp:read")
+assert.equal(permissionForPath("/logs"), "mm:servers:read")
+console.log("auth-mcp.test.ts: frontend MCP permissions and exact path boundaries pass")
diff --git a/lib/auth.ts b/lib/auth.ts
index ec9784c4..5845110e 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -201,7 +201,7 @@ export function hasPermission(
required: string,
): boolean {
if (granted.includes(required)) return true
- if (required.startsWith("mm:users:") && granted.includes("mm:settings:admin")) {
+ if ((required.startsWith("mm:users:") || required.startsWith("mm:mcp:")) && granted.includes("mm:settings:admin")) {
return true
}
const parts = required.split(":")
@@ -228,6 +228,7 @@ export function can(required: string): boolean {
}
export function permissionForPath(pathname: string): string | null {
+ if (pathname === "/mcp" || pathname.startsWith("/mcp/")) return "mm:mcp:read"
if (pathname === "/" || pathname.startsWith("/dashboard")) {
return "mm:dashboard:read"
}
diff --git a/lib/data.ts b/lib/data.ts
index 384b5bda..6c819f73 100644
--- a/lib/data.ts
+++ b/lib/data.ts
@@ -212,7 +212,7 @@ export interface VxlanTunnel {
serverId: string
vtepIp: string // VTEP address on the server
remoteVteps: string[] // remote VTEP IPs (unicast-flood)
- l2mtu: number
+ l2mtu: number | null
mtu?: number // actual interface MTU; absent in legacy snapshots
arpProxy: boolean
arpMode?: "disabled" | "enabled" | "local-proxy-arp" | "proxy-arp" | "reply-only"
diff --git a/lib/navigation.ts b/lib/navigation.ts
index 91eb5473..90160ab7 100644
--- a/lib/navigation.ts
+++ b/lib/navigation.ts
@@ -49,6 +49,7 @@ export const navigationItems: NavigationItem[] = [
{ id: "probes", title: "Диагностика", group: "Инструменты", url: "/probes", icon: ScanLineIcon, keywords: ["probe","ping","traceroute","диагностика"] },
{ id: "terminal", title: "Терминал", group: "Инструменты", url: "/terminal", icon: TerminalIcon, keywords: ["terminal","cli","ssh","консоль"] },
// Система
+ { id: "mcp", title: "MCP", group: "Система", url: "/mcp", icon: ShieldCheckIcon, keywords: ["mcp", "ai", "нейросети", "агенты", "разрешения", "аудит"] },
{ id: "alerts", title: "Оповещения", group: "Система", url: "/alerts", icon: BellIcon, keywords: ["alert","notification","уведомление"] },
{ id: "data-collection", title: "Сбор данных", group: "Система", url: "/data-collection", icon: DatabaseIcon, keywords: ["scheduler","планировщик","коллектор","uptime","трафик","журнал","прогон"] },
{ id: "releases", title: "Релизы", group: "Система", url: "/releases", icon: BadgeCheckIcon, keywords: ["release","version","версия","changelog","релиз"] },
diff --git a/lib/server-operations.ts b/lib/server-operations.ts
index 4cbffe50..73edef16 100644
--- a/lib/server-operations.ts
+++ b/lib/server-operations.ts
@@ -25,7 +25,7 @@ export function serverOperationError(error: unknown): string {
return error instanceof Error ? error.message : "Не удалось выполнить действие. Попробуйте ещё раз."
}
-/** Bounded polling, preserving one outcome for every requested server. */
+/** Full polls own global history maintenance; serialize without automatic retry. */
export async function pollServers(
ids: string[],
poll: (id: string) => Promise,
@@ -33,7 +33,7 @@ export async function pollServers(
const uniqueIds = [...new Set(ids)]
const results: PollResult[] = new Array(uniqueIds.length)
let next = 0
- await Promise.all(Array.from({ length: Math.min(4, uniqueIds.length) }, async () => {
+ await Promise.all(Array.from({ length: Math.min(1, uniqueIds.length) }, async () => {
while (next < uniqueIds.length) {
const index = next++
const id = uniqueIds[index]
diff --git a/lib/user-save.ts b/lib/user-save.ts
index ff2eb478..476dbca9 100644
--- a/lib/user-save.ts
+++ b/lib/user-save.ts
@@ -55,6 +55,7 @@ export async function saveUserSteps(form: AppUserForm, checkpoint: UserSaveCheck
}
return checkpoint.user
}
-export function userProfileRequest(form: AppUserForm) {
- return { name: form.name.trim(), login: form.login.trim(), email: form.email.trim(), role: form.role, active: form.active, avatar: userInitials(form.name), sections: form.sections, servers: form.servers }
+export function userProfileRequest(form: AppUserForm, canManagePermissions = true) {
+ const profile = { name: form.name.trim(), login: form.login.trim(), email: form.email.trim(), active: form.active, avatar: userInitials(form.name) }
+ return canManagePermissions ? { ...profile, role: form.role, sections: form.sections, servers: form.servers } : profile
}
diff --git a/lib/users.ts b/lib/users.ts
index a930be7a..a6e30a4c 100644
--- a/lib/users.ts
+++ b/lib/users.ts
@@ -77,13 +77,16 @@ export interface UserServerOption {
export const IFACE_TYPE_LABEL: Record = {
ether: "Ethernet",
+ bridge: "Bridge",
+ vlan: "VLAN",
+ vxlan: "VXLAN",
gre: "GRE",
wg: "WireGuard",
ipsec: "IPsec",
other: "Прочие",
}
-export const IFACE_TYPE_ORDER: InterfaceType[] = ["ether", "gre", "wg", "ipsec", "other"]
+export const IFACE_TYPE_ORDER: InterfaceType[] = ["ether", "bridge", "vlan", "vxlan", "gre", "wg", "ipsec", "other"]
export const ROLE_LABEL: Record = {
admin: "Администратор",
diff --git a/lib/vxlan-export.test.ts b/lib/vxlan-export.test.ts
index 1c66d1d1..aaa767af 100644
--- a/lib/vxlan-export.test.ts
+++ b/lib/vxlan-export.test.ts
@@ -1,10 +1,13 @@
import assert from "node:assert/strict"
import { generateVxlanRsc, quoteRosString } from "./vxlan-export"
import type { VxlanTunnel } from "./data"
+import { vxlanResponseSchema } from "./vxlan-response"
assert.equal(quoteRosString('edge "one"\\$value\r\n\t'), '"edge \\"one\\"\\\\\\$value\\0D\\0A\\09"')
const tunnel: VxlanTunnel = { id: "1-*1", serverId: "1", name: 'vx "edge" $name\n/system reboot', vni: 200, port: 0, dstPort: 4789, vtepIp: "192.0.2.1", remoteVteps: ["198.51.100.1"], l2mtu: 1500, arpProxy: false, arpMode: "reply-only", macLearning: false, comment: 'note "quoted"\\$value\n/system reboot', enabled: false, status: "down" }
const code = generateVxlanRsc(tunnel, {})
+assert.equal(vxlanResponseSchema.parse({ tunnels: [{ ...tunnel, l2mtu: null }] }).tunnels[0].l2mtu, null)
+assert.equal(generateVxlanRsc({ ...tunnel, l2mtu: null }, {}), code, "Unknown L2 MTU must not produce a fabricated RouterOS setting")
const commands = code.split("\n").filter(line => line.startsWith("/"))
assert.equal(commands.length, 2)
assert.match(commands[0], /vni=200 port=4789 arp="reply-only" learning=no disabled=yes/)
diff --git a/lib/vxlan-response.ts b/lib/vxlan-response.ts
index 9044842a..22a58243 100644
--- a/lib/vxlan-response.ts
+++ b/lib/vxlan-response.ts
@@ -5,7 +5,7 @@ export const vxlanResponseSchema = z.object({
id: z.string().min(1), name: z.string().min(1), serverId: z.string().min(1),
vni: z.number().int().min(0).max(16777215),
port: z.number().int().min(0).max(65535), dstPort: z.number().int().min(1).max(65535),
- vtepIp: z.string(), remoteVteps: z.array(z.string()), l2mtu: z.number().int().nonnegative(),
+ vtepIp: z.string(), remoteVteps: z.array(z.string()), l2mtu: z.number().int().nonnegative().nullable(),
mtu: z.number().int().min(1).max(65535).optional(),
arpProxy: z.boolean(), arpMode: z.enum(["disabled", "enabled", "local-proxy-arp", "proxy-arp", "reply-only"]).optional(), macLearning: z.boolean(), comment: z.string(), enabled: z.boolean(),
status: z.enum(["up", "down"]),
diff --git a/package-lock.json b/package-lock.json
index c6d21e45..30825b3f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -59,6 +59,10 @@
"@fastify/jwt": "^10.2.2",
"@fastify/type-provider-zod": "^1.0.0",
"@mmapp/contracts": "1.0.0",
+ "@modelcontextprotocol/client": "2.3.1",
+ "@modelcontextprotocol/fastify": "2.0.1",
+ "@modelcontextprotocol/node": "2.1.1",
+ "@modelcontextprotocol/server": "2.3.1",
"acme-client": "^5.4.0",
"better-sqlite3": "^12.9.0",
"dotenv": "^16.4.7",
@@ -75,6 +79,7 @@
"@types/node": "^22.15.3",
"@types/pg": "^8.23.1",
"drizzle-kit": "^0.31.10",
+ "embedded-postgres": "18.4.0-beta.17",
"jose": "^6.2.11",
"pino-pretty": "^13.1.3",
"tsx": "^4.19.3",
@@ -1176,6 +1181,150 @@
"@noble/ciphers": "^1.0.0"
}
},
+ "node_modules/@embedded-postgres/darwin-arm64": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/@embedded-postgres/darwin-arm64/-/darwin-arm64-18.4.0-beta.17.tgz",
+ "integrity": "sha512-Kg1ZMNFzkVIJs3g4V2UYEc5X005km9rGinxFBH8R1sOU2Rblvz4pt2Uf93Pu8Rk273Ue9HIdrbMPpgUqwjUi0Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@embedded-postgres/darwin-x64": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/@embedded-postgres/darwin-x64/-/darwin-x64-18.4.0-beta.17.tgz",
+ "integrity": "sha512-4tShSYWMxUQTSWoQAdLnHISvRj6L9gTch9/31ASJPg6wgyN64LDRwMcOINEWybM7N0ropJ3nTYhFT3UX1bKY5Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@embedded-postgres/linux-arm": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/@embedded-postgres/linux-arm/-/linux-arm-18.4.0-beta.17.tgz",
+ "integrity": "sha512-VuD1nFasN7yG57zpJcp6MBXM0nXqGfb8GBQV+f1FGJ17+VMNYLIFLhFp99UlY4xnWG74FQC4NPYw8eCwSTJ6qg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@embedded-postgres/linux-arm64": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/@embedded-postgres/linux-arm64/-/linux-arm64-18.4.0-beta.17.tgz",
+ "integrity": "sha512-TIzjtGnDGSD/LbdW0OWCEcbI+YVT0WKSfSr20TCkkP4UR8zeKe+QCZbO0/CM4hS9EWyZ4cDebjRvpRc3iMi6wg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@embedded-postgres/linux-ia32": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/@embedded-postgres/linux-ia32/-/linux-ia32-18.4.0-beta.17.tgz",
+ "integrity": "sha512-aSRe4kknqRHuedtpo/rDIaqa8r9VrKIgW9p5FkJyIFqUUkIkxRqND1dg8xrDRREcSUXRJKS0x+j/AuxflgYIfg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@embedded-postgres/linux-ppc64": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/@embedded-postgres/linux-ppc64/-/linux-ppc64-18.4.0-beta.17.tgz",
+ "integrity": "sha512-zO2RRUFdKRPplrdhmglG39VXJZzDXu3P3ONAG1sFPhGh89vbk24Btd5P7uOmQLIpWehzL0s+UqUWoeE/ZUKvgw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@embedded-postgres/linux-x64": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/@embedded-postgres/linux-x64/-/linux-x64-18.4.0-beta.17.tgz",
+ "integrity": "sha512-jVw/MdDtIX/vICH/DKIe6/mHpiCggdx6QVyza4vt/NbcZFsL0KhwglF6F1Koqx3gRBZ9XtN+vi63EsqSyqOSxA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/@embedded-postgres/windows-x64": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/@embedded-postgres/windows-x64/-/windows-x64-18.4.0-beta.17.tgz",
+ "integrity": "sha512-AwRerliA4IGWyW5jWBvHt5vidVUSB0QQW9Tt2y7ScnmifnCb/awfxZr4BkBSTv+gNt8Djcddqs+xSF5Z6/CkTg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16"
+ }
+ },
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
@@ -3193,6 +3342,65 @@
"resolved": "packages/contracts",
"link": true
},
+ "node_modules/@modelcontextprotocol/client": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.3.1.tgz",
+ "integrity": "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.3.1",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.8",
+ "jose": "^6.1.3",
+ "pkce-challenge": "^5.0.0",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz",
+ "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/fastify": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/fastify/-/fastify-2.0.1.tgz",
+ "integrity": "sha512-tqfYC5zV7c5lu+B8NtXSzD2yyjF0ABJNCQi6cTI++cOVB6pCWPBiJuzICEfCFhLhZViyVeikWhcm0p0DjSKSwg==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=20"
+ },
+ "peerDependencies": {
+ "@modelcontextprotocol/server": "^2.3.0",
+ "fastify": "^5.2.0"
+ }
+ },
+ "node_modules/@modelcontextprotocol/node": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.1.tgz",
+ "integrity": "sha512-EY92OAXN2xYL7tNS/MVsWJW1v8VHAPwl9B4Ca3pCrjmvqyC+S1C/6UHsMxF2GoFPraS5Yyg56vFz9brVpFojMA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@hono/node-server": "^1.19.9",
+ "hono": "^4.11.4"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "peerDependencies": {
+ "@modelcontextprotocol/server": "^2.3.0"
+ }
+ },
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.29.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
@@ -3255,6 +3463,19 @@
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT"
},
+ "node_modules/@modelcontextprotocol/server": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.1.tgz",
+ "integrity": "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.3.1",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/@mswjs/interceptors": {
"version": "0.41.6",
"resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.41.6.tgz",
@@ -5818,6 +6039,16 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/async-exit-hook": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/async-exit-hook/-/async-exit-hook-2.0.1.tgz",
+ "integrity": "sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.12.0"
+ }
+ },
"node_modules/async-function": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz",
@@ -7190,6 +7421,30 @@
"integrity": "sha512-4MxfbmNDm+KPh066EZy+eUnkcDPcZ35wNmOWzFuh/ijvHsve6kbLTLURy88uCNK5FbpN+yk2nQY6BYh1GEt+wg==",
"license": "ISC"
},
+ "node_modules/embedded-postgres": {
+ "version": "18.4.0-beta.17",
+ "resolved": "https://registry.npmjs.org/embedded-postgres/-/embedded-postgres-18.4.0-beta.17.tgz",
+ "integrity": "sha512-ORT/A1YiO6ecpRHpyIIBgyCR/8ASqqYZuFw11aX9PkqTX3FUM5+9sNOXY1mGIixxsm2TWSIA5WghJEk7A5ZxVw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "async-exit-hook": "^2.0.1",
+ "pg": "^8.7.3"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "optionalDependencies": {
+ "@embedded-postgres/darwin-arm64": "^18.4.0-beta.17",
+ "@embedded-postgres/darwin-x64": "^18.4.0-beta.17",
+ "@embedded-postgres/linux-arm": "^18.4.0-beta.17",
+ "@embedded-postgres/linux-arm64": "^18.4.0-beta.17",
+ "@embedded-postgres/linux-ia32": "^18.4.0-beta.17",
+ "@embedded-postgres/linux-ppc64": "^18.4.0-beta.17",
+ "@embedded-postgres/linux-x64": "^18.4.0-beta.17",
+ "@embedded-postgres/windows-x64": "^18.4.0-beta.17"
+ }
+ },
"node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
diff --git a/package.json b/package.json
index d31d0a7e..aa473547 100644
--- a/package.json
+++ b/package.json
@@ -7,6 +7,9 @@
"backend"
],
"scripts": {
+ "test:mcp": "tsx --test shared/api/mcp-artifact.test.ts shared/api/mcp-capacity.test.ts && playwright test --config playwright.mcp.config.ts",
+ "test:mcp:auth-ui": "playwright test --config playwright.mcp-auth.config.ts",
+ "test:ipsec-export": "tsx --test shared/api/ipsec-export.test.ts && playwright test --config playwright.ipsec-export.config.ts",
"test:logs": "playwright test --config playwright.logs-context.config.ts",
"dev": "next dev",
"build": "npm run build -w @mmapp/contracts && next build",
@@ -14,7 +17,7 @@
"prepare": "node .ci/scripts/ensure-git-hooks.mjs",
"start": "next start",
"lint": "eslint",
- "test:servers": "playwright test tests/e2e/servers.spec.ts"
+ "test:servers": "tsx --test tests/unit/server-poll-batch.test.ts && playwright test tests/e2e/servers.spec.ts"
},
"dependencies": {
"@base-ui/react": "^1.4.1",
diff --git a/playwright.config.ts b/playwright.config.ts
index 1560eb88..9905918a 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -2,6 +2,8 @@ import { defineConfig } from "@playwright/test"
export default defineConfig({
testDir: "./tests/e2e",
+ // This suite requires NEXT_PUBLIC_AUTH_ENABLED=true and its own config.
+ testMatch: /^(?!.*mcp-auth-context\.spec\.ts$).*\.spec\.ts$/,
testIgnore: ["**/logs-context.spec.ts", "**/wireguard-context.spec.ts", "**/uptime-context.spec.ts", "**/alerts-context.spec.ts", "**/system-database-context.spec.ts", "**/settings-context.spec.ts", "**/evobgp-context.spec.ts", "**/netflow-context.spec.ts", "**/geoip-context.spec.ts", "**/data-collection-context.spec.ts", "**/backups-context.spec.ts", "**/certificates-context.spec.ts", "**/containers-context.spec.ts", "**/users-context.spec.ts", "**/probes-context.spec.ts", "**/terminal-context.spec.ts", "**/network-map-context.spec.ts", "**/route-optimizer-context.spec.ts", "**/recursive-routes-context.spec.ts", "**/ospf-context.spec.ts", "**/bgp-context.spec.ts", "**/firewall-context.spec.ts", "**/filters-context.spec.ts", "**/ipsec-context.spec.ts", "**/gre-context.spec.ts", "**/vxlan-context.spec.ts"],
fullyParallel: false,
workers: 1,
diff --git a/playwright.ipsec-export.config.ts b/playwright.ipsec-export.config.ts
new file mode 100644
index 00000000..64e38719
--- /dev/null
+++ b/playwright.ipsec-export.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from "@playwright/test"
+import base from "./playwright.config"
+const server = base.webServer
+if (!server || Array.isArray(server)) throw new Error("Ожидается один локальный сервер")
+export default defineConfig({
+ ...base,
+ testIgnore: [],
+ testMatch: "ipsec-cert.spec.ts",
+ use: { ...base.use, baseURL: "http://127.0.0.1:3117" },
+ webServer: {
+ ...server,
+ command: "node node_modules/next/dist/bin/next dev --webpack --hostname 127.0.0.1 --port 3117",
+ url: "http://127.0.0.1:3117",
+ env: { ...server.env, MM_NEXT_DIST_DIR: "tmp/next-ipsec-export-test" },
+ },
+})
diff --git a/playwright.mcp-auth.config.ts b/playwright.mcp-auth.config.ts
new file mode 100644
index 00000000..ee9582d5
--- /dev/null
+++ b/playwright.mcp-auth.config.ts
@@ -0,0 +1,24 @@
+import { defineConfig } from '@playwright/test'
+import path from 'node:path'
+
+// Shipped UI with synthetic API/JWT fixtures. Actual backend token enforcement
+// is accepted separately by test:mcp:external-process:pg.
+export default defineConfig({
+ testDir: './tests/e2e', testMatch: 'mcp-auth-context.spec.ts', workers: 1, retries: 0,
+ timeout: 60000, outputDir: './tmp/mcp-auth-test-results', reporter: 'list',
+ use: {
+ baseURL: 'http://127.0.0.1:3108', browserName: 'chromium',
+ channel: process.env.MCP_UI_BROWSER_CHANNEL || 'msedge',
+ viewport: { width: 1440, height: 1000 }, trace: 'retain-on-failure',
+ },
+ webServer: {
+ command: 'node node_modules/next/dist/bin/next dev --webpack --hostname 127.0.0.1 --port 3108',
+ url: 'http://127.0.0.1:3108/release-manifest.json', reuseExistingServer: false, timeout: 120000,
+ env: {
+ NEXT_PUBLIC_BACKEND_URL: 'local', NEXT_PUBLIC_DEFAULT_DATA_SOURCE: 'live',
+ NEXT_PUBLIC_ALLOW_MOCK_DATA: 'true', NEXT_PUBLIC_AUTH_ENABLED: 'true',
+ NEXT_FONT_GOOGLE_MOCKED_RESPONSES: path.resolve('tests/e2e/fixtures/mcp-test-fonts.cjs'),
+ MM_NEXT_DIST_DIR: 'tmp/next-mcp-auth-test',
+ },
+ },
+})
diff --git a/playwright.mcp.config.ts b/playwright.mcp.config.ts
new file mode 100644
index 00000000..3a741091
--- /dev/null
+++ b/playwright.mcp.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from "@playwright/test"
+import base from "./playwright.config"
+const server = base.webServer
+if (!server || Array.isArray(server)) throw new Error("Ожидается один локальный сервер")
+export default defineConfig({
+ ...base, testIgnore: [], testMatch: "mcp-context.spec.ts",
+ use: { ...base.use, baseURL: "http://127.0.0.1:3102" },
+ webServer: { ...server, command: "node node_modules/next/dist/bin/next dev --webpack --hostname 127.0.0.1 --port 3102", url: "http://127.0.0.1:3102", env: { ...server.env, NEXT_PUBLIC_BACKEND_URL: "local", MM_NEXT_DIST_DIR: "tmp/next-mcp-test" } },
+})
diff --git a/shared/api/http-client.ts b/shared/api/http-client.ts
index 2df2a88c..f1dc8810 100644
--- a/shared/api/http-client.ts
+++ b/shared/api/http-client.ts
@@ -49,10 +49,16 @@ export function withAuthHeaders(init?: HeadersInit): Headers {
return headers
}
-function handleUnauthorized(): never {
+let portalHandoffStarted = false
+
+function handleUnauthorized(authorization: string | null): never {
if (typeof window !== "undefined" && isAuthEnabled()) {
- const ok = redirectToPortalLogin()
- if (!ok) redirectToPortalLoginInteractive()
+ const token = getToken()
+ if (!portalHandoffStarted && (!token || authorization === `Bearer ${token}`)) {
+ const ok = redirectToPortalLogin()
+ if (!ok) redirectToPortalLoginInteractive()
+ portalHandoffStarted = true
+ }
}
throw new ApiClientError("Unauthorized", 401)
}
@@ -86,7 +92,7 @@ export async function requestJson(
headers,
})
- if (res.status === 401) handleUnauthorized()
+ if (res.status === 401) handleUnauthorized(headers.get("Authorization"))
if (res.status === 204) return undefined as T
@@ -116,7 +122,7 @@ export async function requestBlob(
...init,
headers,
})
- if (res.status === 401) handleUnauthorized()
+ if (res.status === 401) handleUnauthorized(headers.get("Authorization"))
if (!res.ok) {
throw new ApiClientError(await parseErrorMessage(res), res.status)
}
diff --git a/shared/api/ipsec-export.test.ts b/shared/api/ipsec-export.test.ts
new file mode 100644
index 00000000..0c75b70c
--- /dev/null
+++ b/shared/api/ipsec-export.test.ts
@@ -0,0 +1,105 @@
+import assert from "node:assert/strict"
+import { test } from "node:test"
+import { exportIpsecCertByName, exportIpsecUserCert, type IpsecExistingCertExportOptions } from "./ipsec"
+
+const base = "https://fixture.example.test"
+const options: IpsecExistingCertExportOptions = { privateKeyExport: true, caPrivateKeyExport: false, requestKey: "11111111-1111-4111-8111-111111111111" }
+const passphrase = " synthetic-passphrase "
+const bundle = { user: "Renamed label", filename: "fixture.p12", contentB64: "YQ==", passphrase }
+
+test("existing exports reject missing/invalid explicit intent before fetch", async () => {
+ const original = globalThis.fetch
+ let calls = 0
+ globalThis.fetch = async () => { calls++; throw Error("Unexpected fetch") }
+ try {
+ for (const invalid of [undefined, {}, { ...options, privateKeyExport: false }, { ...options, caPrivateKeyExport: undefined }, { ...options, requestKey: "invalid" }, { ...options, requestKey: undefined }, { ...options, extra: true }]) {
+ const intent = invalid as IpsecExistingCertExportOptions
+ await assert.rejects(() => exportIpsecUserCert(base, "1", "identity:*1", passphrase, intent))
+ await assert.rejects(() => exportIpsecCertByName(base, "1", "cert", passphrase, intent))
+ }
+ await assert.rejects(() => exportIpsecUserCert(base, "1", "identity:*1", "short", options))
+ assert.equal(calls, 0)
+ } finally { globalThis.fetch = original }
+})
+
+test("client export preserves native identity selector, raw passphrase, flags and caller UUID", async () => {
+ const original = globalThis.fetch
+ let calls = 0
+ globalThis.fetch = async (url, init) => {
+ calls++
+ assert.equal(new URL(String(url)).pathname.endsWith("/identity%3A*1%2F2/cert"), true)
+ assert.equal(init?.method, "POST")
+ const headers = new Headers(init?.headers), body = JSON.parse(String(init?.body))
+ assert.equal(headers.get("Idempotency-Key") === options.requestKey, true)
+ assert.equal(headers.get("Content-Type"), "application/json")
+ // Compare as booleans so assertion failures cannot print private material.
+ assert.equal(body.passphrase === passphrase, true)
+ assert.equal(body.privateKeyExport, true); assert.equal(body.caPrivateKeyExport, false)
+ assert.equal(Object.hasOwn(body, "requestKey"), false); assert.equal(Object.hasOwn(body, "name"), false)
+ return new Response(JSON.stringify(bundle))
+ }
+ try {
+ const result = await exportIpsecUserCert(base, "1", "identity:*1/2", passphrase, options)
+ assert.equal(result.passphrase === passphrase, true); assert.equal(calls, 1)
+ } finally { globalThis.fetch = original }
+})
+
+test("by-name export supports client/server/foreign/CA targets and explicit CA intent", async () => {
+ const original = globalThis.fetch
+ let expectedName = "", expectedCa = false, calls = 0
+ globalThis.fetch = async (url, init) => {
+ calls++
+ assert.equal(new URL(String(url)).pathname, "/api/ipsec/certs/1/export")
+ const body = JSON.parse(String(init?.body))
+ assert.equal(body.name === expectedName, true); assert.equal(body.passphrase === passphrase, true)
+ assert.equal(body.privateKeyExport, true); assert.equal(body.caPrivateKeyExport, expectedCa)
+ assert.equal(new Headers(init?.headers).get("Idempotency-Key") === options.requestKey, true)
+ return new Response(JSON.stringify(bundle))
+ }
+ try {
+ for (const [name, ca] of [["client", false], ["server", false], ["foreign", false], ["ca", true]] as const) {
+ expectedName = name; expectedCa = ca
+ await exportIpsecCertByName(base, "1", name, passphrase, { ...options, caPrivateKeyExport: ca })
+ }
+ assert.equal(calls, 4)
+ } finally { globalThis.fetch = original }
+})
+
+test("failed, unknown and malformed responses never retry or allocate another request UUID", async () => {
+ const original = globalThis.fetch
+ try {
+ for (const mode of ["network", "unknown", "malformed"] as const) {
+ let calls = 0
+ globalThis.fetch = async (_url, init) => {
+ calls++
+ assert.equal(new Headers(init?.headers).get("Idempotency-Key") === options.requestKey, true)
+ if (mode === "network") throw Error("Synthetic transport failure")
+ if (mode === "unknown") return new Response(JSON.stringify({ error: "Результат неизвестен", state: "unknown", needsReview: true }), { status: 502 })
+ return new Response(JSON.stringify({ ...bundle, contentB64: "invalid!" }))
+ }
+ await assert.rejects(() => exportIpsecUserCert(base, "1", "identity:*1", passphrase, options))
+ assert.equal(calls, 1)
+ await assert.rejects(() => exportIpsecCertByName(base, "1", "client", passphrase, options))
+ assert.equal(calls, 2)
+ }
+ } finally { globalThis.fetch = original }
+})
+
+test("closing an export can abort its one fetch without changing explicit intent", async () => {
+ const original = globalThis.fetch, controller = new AbortController()
+ let calls = 0
+ globalThis.fetch = async (_url, init) => {
+ calls++
+ assert.equal(init?.signal === controller.signal, true)
+ assert.equal(new Headers(init?.headers).get("Idempotency-Key") === options.requestKey, true)
+ return new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true })
+ })
+ }
+ try {
+ const pending = exportIpsecUserCert(base, "1", "identity:*1", passphrase, options, { signal: controller.signal })
+ controller.abort()
+ await assert.rejects(pending, error => error instanceof DOMException && error.name === "AbortError")
+ assert.equal(calls, 1)
+ } finally { globalThis.fetch = original }
+})
diff --git a/shared/api/ipsec.ts b/shared/api/ipsec.ts
index 11111990..595f0571 100644
--- a/shared/api/ipsec.ts
+++ b/shared/api/ipsec.ts
@@ -1,5 +1,6 @@
-import { ipsecListResponseSchema, ipsecServerSummaryDtoSchema, ipsecUserCreatedSchema, ipsecCertBundleSchema } from "@mmapp/contracts/ipsec"
+import { ipsecListResponseSchema, ipsecServerSummaryDtoSchema, ipsecUserCreatedSchema, ipsecCertBundleSchema, ipsecExistingCertificateExportIntentSchema, ipsecExistingCertificateExportRequestKeySchema } from "@mmapp/contracts/ipsec"
import { requestJson } from "@/shared/api/http-client"
+import { z } from "zod"
import type {
IpsecCertBundle,
IpsecInitRequest,
@@ -129,16 +130,34 @@ function parseExportBundle(response: unknown): IpsecCertBundle {
return result.data
}
+const existingCertExportOptionsSchema = ipsecExistingCertificateExportIntentSchema.extend({
+ caPrivateKeyExport: z.boolean(),
+ requestKey: ipsecExistingCertificateExportRequestKeySchema,
+}).strict()
+
+export type IpsecExistingCertExportOptions = z.infer
+
+function existingCertExportIntent(passphrase: string, options: IpsecExistingCertExportOptions) {
+ const parsed = existingCertExportOptionsSchema.safeParse(options)
+ if (!parsed.success || !z.string().min(8).max(16384).safeParse(passphrase).success) {
+ throw new Error("Экспорт требует явного подтверждения приватного ключа и UUID запроса")
+ }
+ return parsed.data
+}
+
export async function exportIpsecUserCert(
baseUrl: string,
serverId: string,
clientId: string,
passphrase: string,
+ options: IpsecExistingCertExportOptions,
+ control?: { signal?: AbortSignal },
): Promise {
+ const intent = existingCertExportIntent(passphrase, options)
const response = await requestJson(
baseUrl,
`/api/ipsec/users/${encodeURIComponent(serverId)}/${encodeURIComponent(clientId)}/cert`,
- { method: "POST", body: JSON.stringify({ passphrase }) },
+ { method: "POST", signal: control?.signal, headers: { "Idempotency-Key": intent.requestKey }, body: JSON.stringify({ passphrase, privateKeyExport: intent.privateKeyExport, caPrivateKeyExport: intent.caPrivateKeyExport }) },
)
return parseExportBundle(response)
}
@@ -148,11 +167,14 @@ export async function exportIpsecCertByName(
serverId: string,
name: string,
passphrase: string,
+ options: IpsecExistingCertExportOptions,
+ control?: { signal?: AbortSignal },
): Promise {
+ const intent = existingCertExportIntent(passphrase, options)
const response = await requestJson(
baseUrl,
`/api/ipsec/certs/${encodeURIComponent(serverId)}/export`,
- { method: "POST", body: JSON.stringify({ name, passphrase }) },
+ { method: "POST", signal: control?.signal, headers: { "Idempotency-Key": intent.requestKey }, body: JSON.stringify({ name, passphrase, privateKeyExport: intent.privateKeyExport, caPrivateKeyExport: intent.caPrivateKeyExport }) },
)
return parseExportBundle(response)
}
diff --git a/shared/api/logs.ts b/shared/api/logs.ts
index 5541a3e3..c9574b3c 100644
--- a/shared/api/logs.ts
+++ b/shared/api/logs.ts
@@ -1,5 +1,5 @@
import { z } from "zod"
-import { logEntrySchema, logPageSchema, logSettingsSchema, logSettingsPatchSchema, logSummarySchema } from "@mmapp/contracts"
+import { logEntrySchema, logPageSchema, logSettingsSchema, logSettingsPatchSchema, logSummarySchema, type LogEntry } from "@mmapp/contracts"
import { requestBlob, requestJson } from "./http-client"
const timedSignal = (signal?: AbortSignal, ms = 30000) => AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(ms)])
@@ -18,8 +18,11 @@ export async function getLogs(base: string, params: URLSearchParams, signal?: Ab
export async function getLogSummary(base: string, params: URLSearchParams, signal?: AbortSignal) {
return confirmed(logSummarySchema, await requestJson(base, "/api/logs/summary?" + params, { signal: timedSignal(signal) }))
}
-export async function getLogContext(base: string, id: string, signal?: AbortSignal) {
- return confirmed(z.object({ entry: logEntrySchema, before: z.array(logEntrySchema), after: z.array(logEntrySchema) }), await requestJson(base, `/api/logs/${encodeURIComponent(id)}/context`, { signal: timedSignal(signal) }))
+export async function getLogContext(base: string, { id, serverId }: Pick, signal?: AbortSignal) {
+ const context = confirmed(z.object({ entry: logEntrySchema, before: z.array(logEntrySchema), after: z.array(logEntrySchema) }), await requestJson(base, `/api/logs/${encodeURIComponent(id)}/context`, { signal: timedSignal(signal) }))
+ if (context.entry.id !== id || context.entry.serverId !== serverId) throw new Error("Контекст относится к другому событию")
+ if ([...context.before, ...context.after].some(row => row.serverId !== serverId)) throw new Error("Контекст содержит события другого устройства")
+ return context
}
export async function getLogSettings(base: string, signal?: AbortSignal) { return confirmed(logSettingsSchema, await requestJson(base, "/api/logs/settings", { signal: timedSignal(signal) })) }
export async function putLogSettings(base: string, patch: z.infer, signal?: AbortSignal) {
diff --git a/shared/api/mcp-artifact.test.ts b/shared/api/mcp-artifact.test.ts
new file mode 100644
index 00000000..7d806a5d
--- /dev/null
+++ b/shared/api/mcp-artifact.test.ts
@@ -0,0 +1,78 @@
+import assert from "node:assert/strict"
+import { createHash } from "node:crypto"
+import { test } from "node:test"
+import { downloadHumanArtifact, humanArtifactError, humanArtifactReceipt } from "./mcp-artifact"
+
+const id = "fa58fa40-4bcb-4616-9316-cb69463b3150", path = `/api/mcp/artifacts/${id}`
+const receipt = { artifactId: id, humanDownloadOnly: true, downloadPath: path }
+
+test("artifact paths come exclusively from a UUID and a matching structured receipt", () => {
+ assert.deepEqual(humanArtifactReceipt(receipt), { artifactId: id, path })
+ assert.equal(humanArtifactReceipt({ ...receipt, bytes: 4 }), null)
+ assert.equal(humanArtifactReceipt({ ...receipt, bytes: 64 * 1024 * 1024 + 1, sha256: "a".repeat(64) }), null)
+ for (const invalid of [null, path, { ...receipt, artifactId: "../secrets" }, { ...receipt, artifactId: id + "?token=secret" }, { ...receipt, humanDownloadOnly: false }, ...["https://unsafe.test/", "//unsafe.test/", "javascript:alert(1)", path + "?token=secret", path + "/../x"].map(downloadPath => ({ ...receipt, downloadPath }))]) assert.equal(humanArtifactReceipt(invalid), null)
+})
+
+test("binary download uses the portal JWT, no redirects, temporary Blob URL and safe errors", async () => {
+ const globals = ["window", "document", "localStorage", "setTimeout"] as const
+ const descriptors = globals.map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const)
+ const originalFetch = globalThis.fetch, originalCreate = URL.createObjectURL, originalRevoke = URL.revokeObjectURL
+ let token: string | null = "header." + btoa(JSON.stringify({ sub: "human", apps: ["mm"], exp: 4102444800 })) + ".signature"
+ let clicks = 0, removed = 0, revoked = 0, requests = 0
+ const anchor = { href: "", download: "", click: () => { clicks++ }, remove: () => { removed++ } }
+ try {
+ Object.defineProperty(globalThis, "window", { configurable: true, value: { location: { hostname: "localhost" } } })
+ Object.defineProperty(globalThis, "localStorage", { configurable: true, value: { getItem: () => token, removeItem: () => { token = null } } })
+ Object.defineProperty(globalThis, "document", { configurable: true, value: { createElement: () => anchor, body: { appendChild: () => undefined } } })
+ Object.defineProperty(globalThis, "setTimeout", { configurable: true, value: (callback: () => void) => { callback(); return 0 } })
+ URL.createObjectURL = blob => { assert.ok(blob instanceof Blob); assert.equal(blob.size, 4); return "blob:temporary" }
+ URL.revokeObjectURL = url => { assert.equal(url, "blob:temporary"); revoked++ }
+ globalThis.fetch = async (url, init) => {
+ requests++
+ assert.ok(String(url).endsWith(path)); assert.equal(new Headers(init?.headers).get("Authorization"), `Bearer ${token}`)
+ assert.equal(init?.redirect, "error"); assert.equal(init?.cache, "no-store")
+ return new Response(new Uint8Array([0, 255, 128, 1]), { headers: { "Content-Disposition": 'attachment; filename="backup.rsc"' } })
+ }
+ await downloadHumanArtifact("http://localhost:8000", receipt)
+ assert.equal(anchor.href, "blob:temporary"); assert.equal(anchor.download, "backup.rsc")
+ assert.equal(clicks, 1); assert.equal(removed, 1); assert.equal(revoked, 1)
+ const cancelled = new AbortController(); cancelled.abort()
+ await assert.rejects(downloadHumanArtifact("http://localhost:8000", receipt, cancelled.signal)); assert.equal(clicks, 1)
+ for (const status of [403, 404, 409, 500]) {
+ globalThis.fetch = async () => new Response(JSON.stringify({ error: "NEVER_RENDER_SECRET" }), { status })
+ await assert.rejects(downloadHumanArtifact("http://localhost:8000", receipt), error => !humanArtifactError(error).includes("NEVER_RENDER_SECRET"))
+ }
+ token = "mmcp_bearer_not_a_portal_JWT"
+ globalThis.fetch = async () => { throw Error("must not request") }
+ await assert.rejects(downloadHumanArtifact("http://localhost:8000", receipt), error => humanArtifactError(error).includes("Войдите в портал"))
+ token = null
+ await assert.rejects(downloadHumanArtifact("http://localhost:8000", receipt))
+ assert.equal(requests, 2)
+
+ token = "header." + btoa(JSON.stringify({ sub: "human", apps: ["mm"], exp: 4102444800 })) + ".signature"
+ const payload = new Uint8Array([0, 255, 128, 1])
+ const pinnedReceipt = { ...receipt, bytes: payload.length, sha256: createHash("sha256").update(payload).digest("hex") }
+ globalThis.fetch = async () => new Response(payload)
+ await downloadHumanArtifact("http://localhost:8000", pinnedReceipt)
+ assert.equal(clicks, 2)
+ for (const body of [new Uint8Array([0, 1]), new Uint8Array([0, 255, 128, 2])]) {
+ globalThis.fetch = async () => new Response(body)
+ await assert.rejects(downloadHumanArtifact("http://localhost:8000", pinnedReceipt), failure => humanArtifactError(failure).includes("квитанции"))
+ }
+ let cancelledOversize = false
+ globalThis.fetch = async () => new Response(new ReadableStream({
+ start(stream) { stream.enqueue(new Uint8Array(5)) },
+ cancel() { cancelledOversize = true },
+ }))
+ await assert.rejects(downloadHumanArtifact("http://localhost:8000", pinnedReceipt), failure => humanArtifactError(failure).includes("квитанции"))
+ assert.equal(cancelledOversize, true)
+ globalThis.fetch = async () => new Response(new ReadableStream({
+ pull(stream) { token = null; stream.enqueue(payload); stream.close() },
+ }, { highWaterMark: 0 }))
+ await assert.rejects(downloadHumanArtifact("http://localhost:8000", pinnedReceipt), failure => humanArtifactError(failure).includes("Войдите в портал"))
+ assert.equal(clicks, 2)
+ } finally {
+ globalThis.fetch = originalFetch; URL.createObjectURL = originalCreate; URL.revokeObjectURL = originalRevoke
+ for (const [name, descriptor] of descriptors) { if (descriptor) Object.defineProperty(globalThis, name, descriptor); else Reflect.deleteProperty(globalThis, name) }
+ }
+})
diff --git a/shared/api/mcp-artifact.ts b/shared/api/mcp-artifact.ts
new file mode 100644
index 00000000..4ce76548
--- /dev/null
+++ b/shared/api/mcp-artifact.ts
@@ -0,0 +1,97 @@
+import { z } from "zod"
+import { getClaims, getToken } from "@/lib/auth"
+import { ApiClientError, requestBlob } from "./http-client"
+
+// The largest human-only receipt is a PostgreSQL backup, bounded to 64 MiB.
+const maxDownloadBytes = 64 * 1024 * 1024
+const receiptSchema = z.object({
+ artifactId: z.string().uuid(),
+ humanDownloadOnly: z.literal(true),
+ downloadPath: z.string().optional(),
+ bytes: z.number().int().min(0).max(maxDownloadBytes).optional(),
+ sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
+}).refine(receipt => (receipt.bytes === undefined) === (receipt.sha256 === undefined))
+
+/** Only structured receipts qualify; supplied paths never become navigation targets. */
+export function humanArtifactReceipt(value: unknown) {
+ const parsed = receiptSchema.safeParse(value)
+ if (!parsed.success) return null
+ const path = `/api/mcp/artifacts/${parsed.data.artifactId}`
+ if (parsed.data.downloadPath !== undefined && parsed.data.downloadPath !== path) return null
+ const { artifactId, bytes, sha256 } = parsed.data
+ return { artifactId, path, ...(bytes === undefined ? {} : { bytes, sha256 }) }
+}
+
+async function boundedArtifactBlob(response: Response, artifact: NonNullable>, signal?: AbortSignal) {
+ const size = artifact.bytes
+ const bytes = size === undefined ? undefined : new Uint8Array(size)
+ const chunks: BlobPart[] = []
+ const reader = response.body?.getReader()
+ let length = 0, finished = false
+ const mismatch = () => new ApiClientError("Файл не соответствует квитанции", 409)
+ if (reader) {
+ try {
+ while (true) {
+ const chunk = await reader.read()
+ signal?.throwIfAborted()
+ if (chunk.done) { finished = true; break }
+ const offset = length
+ length += chunk.value.byteLength
+ if (length > (size ?? maxDownloadBytes)) throw mismatch()
+ if (bytes) bytes.set(chunk.value, offset)
+ else chunks.push(chunk.value)
+ }
+ } finally {
+ if (!finished) void reader.cancel().catch(() => undefined)
+ reader.releaseLock()
+ }
+ }
+ if (size !== undefined && length !== size) throw mismatch()
+ // The backend also verifies the signed receipt for browsers without Web Crypto on plain HTTP.
+ if (bytes && artifact.sha256 && globalThis.crypto?.subtle) {
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes)
+ const sha256 = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("")
+ if (sha256 !== artifact.sha256) throw mismatch()
+ }
+ return new Blob(bytes ? [bytes] : chunks, { type: response.headers.get("Content-Type") ?? "" })
+}
+
+export async function downloadHumanArtifact(base: string, receipt: unknown, signal?: AbortSignal) {
+ const artifact = humanArtifactReceipt(receipt)
+ if (!artifact) throw new Error("Некорректная квитанция файла")
+ const claims = getClaims()
+ const token = getToken()
+ if (!token || !claims?.sub || !claims.apps?.includes("mm")) {
+ throw new ApiClientError("Войдите в портал для скачивания файла", 401)
+ }
+ const response = await requestBlob(base, artifact.path, { signal, cache: "no-store", redirect: "error" })
+ const blob = await boundedArtifactBlob(response, artifact, signal)
+ signal?.throwIfAborted()
+ if (getToken() !== token || !getClaims()) throw new ApiClientError("Сеанс портала изменился", 401)
+ const disposition = response.headers.get("Content-Disposition") ?? ""
+ const suggested = /filename="([a-zA-Z0-9._-]{1,200})"/.exec(disposition)?.[1]
+ const filename = suggested && suggested !== "." && suggested !== ".." ? suggested : `mcp-${artifact.artifactId}.bin`
+ const url = URL.createObjectURL(blob)
+ const link = document.createElement("a")
+ try {
+ link.href = url
+ link.download = filename
+ document.body.appendChild(link)
+ link.click()
+ } finally {
+ link.remove()
+ // Let the browser begin consuming the download before releasing the in-memory file.
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
+ }
+}
+
+export function humanArtifactError(error: unknown): string {
+ if (error instanceof ApiClientError) {
+ if (error.status === 401) return "Войдите в портал для скачивания файла."
+ if (error.status === 403) return "Доступ к файлу отозван или файл принадлежит другому пользователю."
+ if (error.status === 404 || error.status === 410) return "Файл отсутствует или срок хранения истёк. Подготовьте новую выгрузку."
+ if (error.status === 409) return "Файл изменился или больше не соответствует квитанции. Подготовьте новую выгрузку."
+ }
+ // Do not render response bodies, filenames, credentials, or binary content as errors.
+ return "Не удалось скачать файл. Проверьте соединение и повторите попытку."
+}
diff --git a/shared/api/mcp-capacity.test.ts b/shared/api/mcp-capacity.test.ts
new file mode 100644
index 00000000..cda67d4a
--- /dev/null
+++ b/shared/api/mcp-capacity.test.ts
@@ -0,0 +1,17 @@
+import assert from "node:assert/strict"
+import {test} from "node:test"
+import {mcpPollStorageCapacitySchema} from "@mmapp/contracts/mcp"
+import {mcpOverviewSchema} from "./mcp"
+
+const capacity={status:"observed",owner:{used:8,limit:8,remaining:0},global:{exhausted:true,usage:{used:128,limit:128,remaining:0}},retentionDays:14}
+test("poll retained capacity validates full counters and hides non-admin global usage",()=>{
+ assert.deepEqual(mcpPollStorageCapacitySchema.parse(capacity),capacity)
+ const privateView={...capacity,global:{exhausted:true,usage:null}}
+ assert.deepEqual(mcpPollStorageCapacitySchema.parse(privateView),privateView)
+ for(const bad of [{...capacity,owner:{used:8,limit:8,remaining:1}},{...capacity,global:{exhausted:false,usage:capacity.global.usage}},{...capacity,retentionDays:0},{...capacity,owner:{used:9,limit:8,remaining:0}},{status:"unavailable",owner:{used:0,limit:8,remaining:8}}])assert.equal(mcpPollStorageCapacitySchema.safeParse(bad).success,false)
+})
+test("old overview responses report capacity unavailable instead of inventing free slots",()=>{
+ const original={connections:1,calls:2,errors:0,approvals:0,running:0,enabled:true,observedAt:new Date().toISOString()}
+ assert.deepEqual(mcpOverviewSchema.parse(original).pollStorageCapacity,{status:"unavailable"})
+ assert.deepEqual(mcpOverviewSchema.parse({...original,pollStorageCapacity:capacity}).pollStorageCapacity,capacity)
+})
diff --git a/shared/api/mcp.ts b/shared/api/mcp.ts
new file mode 100644
index 00000000..62db3d78
--- /dev/null
+++ b/shared/api/mcp.ts
@@ -0,0 +1,65 @@
+import { z } from "zod"
+import { bridgeVlanStateSchema, type BridgeVlanDesired } from "@mmapp/contracts/bridge-vlan"
+import { mcpCatalogResponseSchema, mcpConnectionsSchema, mcpSettingsSchema, mcpPolicyPreviewResponseSchema, mcpPollStorageCapacitySchema, type McpConnectionCreate } from "@mmapp/contracts/mcp"
+import { requestJson } from "./http-client"
+import { downloadHumanArtifact } from "./mcp-artifact"
+
+export const mcpRecordsSchema = z.object({ items: z.array(z.record(z.string(), z.unknown())), total: z.number().int(), nextCursor: z.string().nullable() })
+export const mcpOverviewSchema = z.object({ connections: z.number(), calls: z.number(), errors: z.number(), approvals: z.number(), running: z.number(), enabled: z.boolean(), observedAt: z.string(), pollStorageCapacity:mcpPollStorageCapacitySchema.default({status:"unavailable"}) })
+export const maxMcpRestoreArchiveBytes = 64 * 1024 * 1024
+const restoreArchiveSchema = z.object({ archiveRef: z.string().uuid(), sha256: z.string().regex(/^[a-f0-9]{64}$/), sizeBytes: z.number().int().positive().max(maxMcpRestoreArchiveBytes), expiresAt: z.string().datetime() })
+const deviceCatalogSchema = z.object({ servers: z.array(z.object({ id: z.number(), name: z.string(), host: z.string(), enabled: z.boolean() })), resources: z.array(z.object({ id: z.string(), title: z.string(), read: z.boolean(), create: z.boolean(), update: z.boolean(), delete: z.boolean(), fields: z.array(z.object({ key: z.string(), type: z.enum(["string", "number", "boolean"]), options: z.array(z.string()).optional(), min: z.number().optional(), max: z.number().optional(), maxLength: z.number().optional(), requiredOnCreate: z.boolean() })) })) })
+export function mcpApi(base: string) {
+ const get = async (path: string, schema: z.ZodType, signal?: AbortSignal): Promise => schema.parse(await requestJson(base, "/api/mcp" + path, { signal }))
+ const send = async (path: string, body: unknown, schema: z.ZodType, method = "POST", signal?: AbortSignal): Promise => schema.parse(await requestJson(base, "/api/mcp" + path, { method, body: JSON.stringify(body), signal }))
+ return {
+ downloadArtifact: (receipt: unknown, signal?: AbortSignal) => downloadHumanArtifact(base, receipt, signal),
+ coverage: (signal?: AbortSignal) => get("/coverage", z.object({ version: z.literal(1), routes: z.array(z.object({ method: z.string(), path: z.string(), status: z.enum(["mediated", "excluded", "pending"]), operations: z.array(z.string()), reason: z.string() })) }), signal),
+ uploadRestoreArchive: async (file: File, signal?: AbortSignal) => restoreArchiveSchema.parse(await requestJson(base, "/api/mcp/database/archives", { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: file, signal })),
+ restorePlan: (connectionId: string, archiveRef: string, expectedSha256: string, signal?: AbortSignal) => send("/database/plan", { connectionId, archiveRef, expectedSha256 }, z.object({ planId: z.string(), state: z.string() }), "POST", signal),
+ restoreReceipt: (id: string, signal?: AbortSignal) => get(`/database/receipts/${encodeURIComponent(id)}`, z.record(z.string(), z.unknown()), signal),
+ managementChannels: (signal?: AbortSignal) => get("/management-channels", z.object({ channels: z.array(z.record(z.string(), z.unknown())) }), signal),
+ registerManagement: (input: unknown) => send("/management-channels", input, z.object({ id: z.string(), serverId: z.number(), expiresAt: z.string(), verification: z.string(), independence: z.string() })),
+ revokeManagement: (id: string) => send(`/management-channels/${id}`, {}, z.object({ ok: z.literal(true) }), "DELETE"),
+ recoverOperation: (id: string) => send(`/operations/${id}/recover`, {}, z.object({ planId: z.string(), state: z.string() })),
+ checkRoutePath: (id: string, candidateId: string, proofPurpose: "community" | "control-path" = "community") => send(`/routing-profiles/${id}/check`, { candidateId, proofPurpose }, z.record(z.string(), z.unknown())),
+ reconcileOperation: (id: string) => send(`/operations/${id}/reconcile`, {}, z.record(z.string(), z.unknown())),
+ deviceCatalog: (connectionId: string, signal?: AbortSignal) => get("/devices/catalog?" + new URLSearchParams({ connectionId }), deviceCatalogSchema, signal),
+ deviceRows: (connectionId: string, serverId: string, resource: string, offset = 0, signal?: AbortSignal) => get(`/devices/${encodeURIComponent(serverId)}/${encodeURIComponent(resource)}?` + new URLSearchParams({ connectionId, offset: String(offset) }), z.object({ items: z.array(z.record(z.string(), z.unknown())), total: z.number(), nextOffset: z.number().nullable() }), signal),
+ devicePlan: (connectionId: string, serverId: string, resource: string, action: "create" | "update" | "delete", id: string | undefined, fields: Record) => send(`/devices/${encodeURIComponent(serverId)}/${encodeURIComponent(resource)}/plan`, { connectionId, action, id, fields }, z.object({ planId: z.string(), state: z.string() })),
+ bridgeVlanState: (connectionId: string, serverId: string, signal?: AbortSignal) => get(`/devices/${encodeURIComponent(serverId)}/bridge-vlan/configuration?` + new URLSearchParams({ connectionId }), z.object({ state: bridgeVlanStateSchema }), signal),
+ bridgeVlanPlan: (connectionId: string, serverId: string, bridgeId: string, desired: BridgeVlanDesired) => send(`/devices/${encodeURIComponent(serverId)}/bridge-vlan/configuration/plan`, { connectionId, bridgeId, desired }, z.object({ planId: z.string(), state: z.string() })),
+ revalidate: (id: string) => send("/connections/" + id + "/revalidate", {}, mcpConnectionsSchema.shape.connections.element),
+ apply: (id: string) => send("/plans/" + id + "/apply", {}, z.object({ id: z.string(), state: z.string() })),
+ profilePlan: (input: unknown) => send("/routing-profiles/plan", input, z.object({ planId: z.string(), state: z.string() })),
+ catalog: (signal?: AbortSignal) => get("/catalog", mcpCatalogResponseSchema, signal),
+ connections: (signal?: AbortSignal) => get("/connections", mcpConnectionsSchema, signal),
+ overview: (signal?: AbortSignal) => get("/overview", mcpOverviewSchema, signal),
+ settings: (signal?: AbortSignal) => get("/settings", mcpSettingsSchema, signal),
+ records: (kind: "requests" | "plans" | "operations" | "audit" | "drift", params: URLSearchParams, signal?: AbortSignal) => get("/" + kind + "?" + params, mcpRecordsSchema, signal),
+ create: (input: McpConnectionCreate) => send("/connections", input, z.object({ token: z.string(), connection: mcpConnectionsSchema.shape.connections.element })),
+ update: (id: string, input: McpConnectionCreate) => send("/connections/" + id, input, mcpConnectionsSchema.shape.connections.element, "PUT"),
+ status: (id: string, status: "active" | "paused" | "revoked") => send(`/connections/${id}/status`, { status }, z.object({ ok: z.literal(true) })),
+ rotate: (id: string) => send(`/connections/${id}/rotate`, {}, z.object({ token: z.string() })),
+ check: (id: string) => send(`/connections/${id}/check`, {}, z.object({ ok: z.boolean(), checks: z.record(z.string(), z.boolean()), checkedAt: z.string(), protocolProbe: z.object({ status: z.enum(["passed", "failed", "skipped"]), elapsedMs: z.number(), reason: z.string().optional(), credentialType: z.enum(["temporary-no-operations", "temporary-capabilities-read"]), capabilitiesRead: z.enum(["passed", "failed", "skipped"]).optional(), clientCredentialsVerified: z.literal(false) }).optional() })),
+ grants: (id: string, signal?: AbortSignal) => get(`/connections/${id}/grants`, z.object({ grants: z.array(z.object({ id: z.string(), grant: z.record(z.string(), z.unknown()), revoked_at: z.string().nullable() })) }), signal),
+ grant: (id: string, grant: unknown) => send(`/connections/${id}/grants`, grant, z.object({ token: z.string(), expiresAt: z.string() })),
+ revokeGrant: (id: string) => send(`/grants/${id}`, {}, z.object({ ok: z.literal(true) }), "DELETE"),
+ profiles: (signal?: AbortSignal) => get("/routing-profiles", z.object({ profiles: z.array(z.record(z.string(), z.unknown())) }), signal),
+ pauseProfile: (id: string) => send(`/routing-profiles/${id}/pause`, {}, z.object({ ok: z.literal(true) })),
+ decision: (id: string, approve: boolean) => send(`/plans/${id}/decision`, { approve }, z.object({ ok: z.literal(true) })),
+ saveSettings: (settings: unknown) => send("/settings", settings, mcpSettingsSchema, "PUT"),
+ pause: () => send("/pause", {}, z.object({ ok: z.literal(true) })),
+ stopAutomation: () => send("/stop-automation", {}, z.object({ ok: z.literal(true) })),
+ preview: (input: unknown) => send("/policy/preview", input, mcpPolicyPreviewResponseSchema),
+ clients: (signal?: AbortSignal) => get("/oauth/clients", z.object({ clients: z.array(z.object({ id: z.string(), name: z.string(), redirect_uris: z.array(z.string()), enabled: z.boolean() })) }), signal),
+ createClient: (name: string, redirectUris: string[]) => send("/oauth/clients", { name, redirectUris }, z.object({ clientId: z.string() })),
+ disableClient: (id: string) => send(`/oauth/clients/${id}`, {}, z.object({ ok: z.literal(true) }), "DELETE"),
+ consentRequest: (id: string, signal?: AbortSignal) => get("/oauth/requests/" + id, z.object({ id: z.string(), name: z.string(), redirect_uri: z.string(), scope: z.string() }), signal),
+ consent: (requestId: string, decision: { approve: true; connectionId: string } | { approve: false }) => send("/oauth/consent", { requestId, ...decision }, z.object({ redirectUrl: z.string().url() })),
+ protections: (signal?: AbortSignal) => get("/protections", z.object({ protections: z.array(z.object({ id: z.string(), object_ref: z.object({ kind: z.string(), id: z.string(), serverId: z.number().optional(), protection: z.enum(["deny", "human-approval-required"]) }), reason: z.string() })) }), signal),
+ protect: (object: unknown, reason: string) => send("/protections", { object, reason }, z.object({ id: z.string() })),
+ removeProtection: async (id: string) => requestJson(base, "/api/mcp/protections/" + id, { method: "DELETE" }),
+ }
+}
+export type McpApi = ReturnType
diff --git a/shared/api/servers.ts b/shared/api/servers.ts
index c7130aba..c5abe7ec 100644
--- a/shared/api/servers.ts
+++ b/shared/api/servers.ts
@@ -12,7 +12,8 @@ import { requestJson as httpRequestJson } from "@/shared/api/http-client"
function requestJson(baseUrl: string, path: string, init?: RequestInit): Promise {
return httpRequestJson(baseUrl, path, {
...init,
- signal: AbortSignal.timeout(path.endsWith("/poll") ? 60_000 : 30_000),
+ // The executor retains its 180s bound; allow 5s for the final HTTP response.
+ signal: AbortSignal.timeout(path.endsWith("/poll") ? 185_000 : 30_000),
})
}
diff --git a/shared/api/system-database.ts b/shared/api/system-database.ts
index fcb0fe7e..1972d9bf 100644
--- a/shared/api/system-database.ts
+++ b/shared/api/system-database.ts
@@ -2,7 +2,7 @@ import {z} from "zod"
import {ApiClientError,requestBlob,requestJson} from "@/shared/api/http-client"
const MAX_RESTORE_BYTES=512*1024*1024
const magic=[80,71,68,77,80]
-const receiptSchema=z.object({ok:z.literal(true),eventError:z.string().min(1).optional(),listenerError:z.string().min(1).optional(),schedulerError:z.string().min(1).optional(),cleanupError:z.string().min(1).optional()}).strict()
+const receiptSchema=z.object({ok:z.literal(true),eventError:z.string().min(1).optional(),listenerError:z.string().min(1).optional(),schedulerError:z.string().min(1).optional(),cleanupError:z.string().min(1).optional(),maintenanceError:z.string().min(1).optional(),migrationError:z.string().min(1).optional()}).strict()
export type SystemDatabaseRestoreReceipt=z.output
const warningSchema=receiptSchema.omit({ok:true})
export type SystemDatabaseWarnings=z.output
diff --git a/shared/api/users.ts b/shared/api/users.ts
index 55a6ec6c..17a02409 100644
--- a/shared/api/users.ts
+++ b/shared/api/users.ts
@@ -1,6 +1,7 @@
import {
interfaceCatalogStateSchema,
type InterfaceCatalogState,
+ appUserCreateSchema,
appUserReadSchema,
catalogInterfaceSchema,
userBindingSchema,
@@ -80,7 +81,7 @@ function confirmProfile(user: AppUserRead, data: AppUserCreate | AppUserUpdate)
}
}
-export async function createAppUser(baseUrl: string, data: AppUserCreate, init?: RequestInit): Promise {
+export async function createAppUser(baseUrl: string, data: z.input, init?: RequestInit): Promise {
const payload = await requestJson(baseUrl, "/api/users", {
...init,
method: "POST",
diff --git a/tests/e2e/bgp-context.spec.ts b/tests/e2e/bgp-context.spec.ts
index 85a78d13..c616c31a 100644
--- a/tests/e2e/bgp-context.spec.ts
+++ b/tests/e2e/bgp-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import { test, expect } from "@playwright/test"
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,OPTIONS", "access-control-allow-headers": "Content-Type,Authorization" }
const session = (serverId: number, name = "Сессия " + serverId) => ({ id: "*1", serverId, serverName: "Роутер " + serverId, serverSite: "", serverCountry: "RU", name, peerIp: "192.0.2." + serverId, remoteAs: 64513, localAs: 64512, localId: "192.0.2.100", remoteId: "192.0.2." + serverId, state: "Established", type: "eBGP", uptime: "1h", holdTime: 90, keepalive: 30, prefixesRx: 12, prefixesTx: 2, inputMessages: 20, outputMessages: 10, capabilities: ["Тест capability"], lastError: null })
@@ -23,8 +24,7 @@ for (const change of ["backend", "mode"]) for (const fails of [false, true]) {
})
await page.getByRole("button", { name: "Обновить", exact: true }).click()
await expect.poll(() => started).toBe(true)
- await page.goBack()
- await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
if (change === "backend") {
const input = page.getByPlaceholder("http://localhost:8000")
await input.fill("http://localhost:8101")
diff --git a/tests/e2e/bridge-vlan/mcp-context.spec.ts b/tests/e2e/bridge-vlan/mcp-context.spec.ts
new file mode 100644
index 00000000..abb99e65
--- /dev/null
+++ b/tests/e2e/bridge-vlan/mcp-context.spec.ts
@@ -0,0 +1,177 @@
+import { test, expect, type Page, type Route } from "@playwright/test"
+import { bridgeVlanDesiredSchema } from "../../../packages/contracts/src/bridge-vlan"
+
+const connectionId = "fa58fa40-4bcb-4616-9316-cb69463b3150"
+const planId = "6b55ae20-2500-489a-af90-3c7345bf6267"
+const at = "2026-10-17T00:00:00Z"
+const connection = { id: connectionId, name: "VLAN editor", ownerId: "ui-admin", policy: { id: connectionId, version: 1, status: "active", mode: "approval", expiresAt: "2099-01-01T00:00:00Z", permissions: ["mm:network:read", "mm:network:write"], scope: { serverIds: [1, 2], operationIds: ["network.bridge-vlan.read", "network.bridge-vlan.configure"], allowGlobal: false }, dangerousPolicy: "approval", autonomousDangerousOperationIds: [], limits: { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 } }, createdAt: at, updatedAt: at, lastUsedAt: null, generationValid: true }
+function fixture() {
+ return {
+ bridges: [{ ".id": "*1", name: "br-users", pvid: "1", "vlan-filtering": "false", disabled: "false" }, { ".id": "*2", name: "br-other", pvid: "99", "vlan-filtering": "false", disabled: "false" }],
+ interfaces: [{ resource: "bridge", id: "*1", name: "br-users" }, { resource: "bridge", id: "*2", name: "br-other" }, ...[2, 3, 4, 5].map(n => ({ resource: "ethernet", id: `*${n + 1}`, name: `ether${n}`, disabled: "false" })), { resource: "wireguard", id: "*7", name: "wg-l3" }, { resource: "gre", id: "*8", name: "gre-l3" }],
+ ports: [
+ { ".id": "*10", bridge: "br-users", interface: "ether2", pvid: "10", "ingress-filtering": "true", "frame-types": "admit-all", disabled: "false", comment: "preserve port" },
+ { ".id": "*11", bridge: "br-users", interface: "ether3", pvid: "1", "ingress-filtering": "true", "frame-types": "admit-only-vlan-tagged", disabled: "false" },
+ { ".id": "*12", bridge: "br-users", interface: "ether5", dynamic: "true" },
+ ],
+ vlans: [
+ { ".id": "*20", bridge: "br-users", "vlan-ids": "10", tagged: "br-users", untagged: "ether2", disabled: "false", comment: "preserve VLAN" },
+ { ".id": "*21", bridge: "br-users", "vlan-ids": "30-32", tagged: "br-users,ether3", untagged: "", disabled: "false" },
+ { ".id": "*22", bridge: "br-users", "vlan-ids": "1", dynamic: "true" },
+ ], vlanInterfaces: [], ipv4Addresses: [], ipv6Addresses: [],
+ }
+}
+type Calls = { path: string; method: string; body: unknown }[]
+async function setup(page: Page, stateRoute?: (route: Route, server: string) => Promise) {
+ const calls: Calls = []
+ await page.addInitScript(() => localStorage.setItem("mmapp_token", "header." + btoa(JSON.stringify({ sub: "ui-admin", apps: ["mm"], permissions: ["mm:settings:admin", "mm:servers:read", "mm:network:admin"], exp: 4102444800 })) + ".signature"))
+ await page.route("**/api/**", async route => {
+ const request = route.request(), url = new URL(request.url()), path = url.pathname, method = request.method()
+ calls.push({ path, method, body: method === "POST" ? request.postDataJSON() : null })
+ if (method === "OPTIONS") return route.fulfill({ status: 204 })
+ const json = (body: unknown) => route.fulfill({ json: body })
+ if (path === "/api/auth/config") return json({ required: false })
+ if (path === "/api/mcp/connections") return json({ connections: [connection] })
+ if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [] })
+ if (path === "/api/mcp/devices/catalog") return json({ servers: [1, 2].map(id => ({ id, name: `CHR ${id}`, host: `192.0.2.${id}`, enabled: true })), resources: [{ id: "bridge", title: "Bridge", read: true, create: false, update: false, delete: false, fields: [] }] })
+ const state = path.match(/^\/api\/mcp\/devices\/(\d+)\/bridge-vlan\/configuration$/)
+ if (state) {
+ expect(url.searchParams.get("connectionId")).toBe(connectionId)
+ return stateRoute ? stateRoute(route, state[1]) : json({ state: fixture() })
+ }
+ if (path.endsWith("/bridge-vlan/configuration/plan")) return json({ planId, state: "awaiting-approval" })
+ if (/\/devices\/\d+\/bridge$/.test(path)) return json({ items: [], total: 0, nextOffset: null })
+ if (path === "/api/mcp/overview") return json({ connections: 1, calls: 0, errors: 0, approvals: 0, running: 0, enabled: true, observedAt: at })
+ if (path === "/api/mcp/coverage") return json({ version: 1, routes: [] })
+ if (path === "/api/servers") return json([])
+ return json({ items: [], total: 0, nextCursor: null })
+ })
+ return calls
+}
+async function open(page: Page) {
+ await page.goto("/mcp?tab=devices")
+ await page.getByLabel("Подключение для управления интерфейсами").selectOption(connectionId)
+ await page.getByLabel("Сервер интерфейсов").selectOption("1")
+ await page.getByLabel("Тип объектов устройства").selectOption("bridge")
+ const editor = page.getByRole("region", { name: "Связанная настройка Bridge VLAN" })
+ await expect(editor.getByLabel("Существующий мост")).toBeEnabled()
+ return editor
+}
+
+test("связанный VLAN: полный desired, явные удаления и только подготовка плана", async ({ page }) => {
+ const calls = await setup(page), editor = await open(page)
+ await editor.getByLabel("Существующий мост").selectOption("*1")
+ await expect(editor.getByRole("group", { name: "*10", exact: true })).toBeVisible()
+ await expect(editor.getByText("Динамический порт ether5", { exact: false })).toBeVisible()
+ await expect(editor.getByText("Динамический VLAN 1", { exact: false })).toBeVisible()
+ await expect(editor.getByRole("group", { name: "*12", exact: true })).toHaveCount(0)
+ await editor.getByRole("checkbox", { name: "VLAN filtering", exact: true }).check()
+ await editor.getByLabel("PVID моста", { exact: true }).fill("2")
+ await editor.getByRole("group", { name: "*10", exact: true }).getByLabel("PVID порта").fill("20")
+ await editor.getByRole("group", { name: "*20", exact: true }).getByRole("textbox").fill("20")
+ await editor.getByRole("group", { name: "*11", exact: true }).getByRole("button", { name: "Удалить порт из плана" }).click()
+ await editor.getByRole("group", { name: "*21", exact: true }).getByRole("button", { name: "Удалить запись VLAN из плана" }).click()
+ await editor.getByRole("button", { name: "Добавить порт", exact: true }).click()
+ const newPort = editor.getByRole("group", { name: "Новый порт", exact: true })
+ await expect(newPort.getByRole("option", { name: /wg-l3|gre-l3|br-users/ })).toHaveCount(0)
+ await newPort.getByLabel("Интерфейс порта").selectOption("ethernet/*5")
+ await newPort.getByLabel("Типы кадров").selectOption("admit-only-vlan-tagged")
+ await editor.getByRole("button", { name: "Добавить запись VLAN", exact: true }).click()
+ const newVlan = editor.getByRole("group", { name: "Новая запись VLAN", exact: true })
+ await newVlan.getByRole("textbox").fill("30-32")
+ const tagged = newVlan.getByRole("group", { name: "Tagged, включая CPU-порт моста при необходимости" })
+ await tagged.getByRole("checkbox", { name: "br-users", exact: true }).check()
+ await tagged.getByRole("checkbox", { name: "ether4", exact: true }).check()
+ await expect(editor).toContainText("Явное удаление портов: *11. Записей VLAN: *21")
+ await editor.screenshot({ path: "tmp/mcp-scoped-controller-two-chr-20261105/bridge-vlan-ui-edge.png" })
+ await page.setViewportSize({ width: 390, height: 844 })
+ expect(await editor.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
+ const bridgeSelect = editor.getByLabel("Существующий мост")
+ expect((await bridgeSelect.boundingBox())!.width).toBeGreaterThanOrEqual(150)
+ const heading = editor.getByRole("heading", { name: "Мост, порты и VLAN", exact: true })
+ await heading.evaluate(element => element.scrollIntoView({ block: "center", behavior: "instant" }))
+ await expect.poll(async () => (await heading.boundingBox())!.y).toBeGreaterThanOrEqual(48)
+ await expect(bridgeSelect).toBeInViewport()
+ await page.screenshot({ path: "tmp/mcp-scoped-controller-two-chr-20261105/bridge-vlan-ui-edge-mobile.png" })
+ await editor.getByRole("button", { name: "Подготовить связанный план VLAN" }).click()
+ await expect(editor.getByRole("status")).toContainText(planId)
+ await expect(editor.getByRole("link", { name: "Открыть планы для проверки и подтверждения" })).toHaveAttribute("href", "/mcp?tab=plans")
+ const posts = calls.filter(call => call.method === "POST")
+ expect(posts).toHaveLength(1)
+ expect(posts[0].path).toBe("/api/mcp/devices/1/bridge-vlan/configuration/plan")
+ const body = posts[0].body as { connectionId: string; bridgeId: string; desired: unknown }
+ expect(body.connectionId).toBe(connectionId); expect(body.bridgeId).toBe("*1")
+ const desired = bridgeVlanDesiredSchema.parse(body.desired)
+ expect(desired).toEqual({ filtering: true, pvid: 2,
+ ports: [{ id: "*10", interface: { resource: "ethernet", id: "*3" }, pvid: 20, ingressFiltering: true, frameTypes: "admit-all", disabled: false, comment: "preserve port" }, { interface: { resource: "ethernet", id: "*5" }, pvid: 1, ingressFiltering: true, frameTypes: "admit-only-vlan-tagged", disabled: false }],
+ vlans: [{ id: "*20", vlanIds: "20", tagged: [{ resource: "bridge", id: "*1" }], untagged: [{ resource: "ethernet", id: "*3" }], disabled: false, comment: "preserve VLAN" }, { vlanIds: "30-32", tagged: [{ resource: "bridge", id: "*1" }, { resource: "ethernet", id: "*5" }], untagged: [], disabled: false }], removePortIds: ["*11"], removeVlanIds: ["*21"],
+ })
+ await editor.getByLabel("PVID моста", { exact: true }).fill("3")
+ await expect(editor.getByRole("status")).toHaveCount(0)
+ expect(calls.filter(call => /\/apply|\/approve|\/bridge\/plan$/.test(call.path))).toHaveLength(0)
+})
+
+test("связанный VLAN: смена моста и перечитывание сбрасывают только черновик", async ({ page }) => {
+ const calls = await setup(page), editor = await open(page)
+ await editor.getByLabel("Существующий мост").selectOption("*1")
+ await editor.getByLabel("PVID моста", { exact: true }).fill("40")
+ await editor.getByRole("group", { name: "*11", exact: true }).getByRole("button", { name: "Удалить порт из плана" }).click()
+ await editor.getByLabel("Существующий мост").selectOption("*2")
+ await expect(editor.getByLabel("PVID моста", { exact: true })).toHaveValue("99")
+ await expect(editor.getByRole("group", { name: "*10", exact: true })).toHaveCount(0)
+ await expect(editor.getByText("Явное удаление портов:", { exact: false })).toHaveCount(0)
+ await editor.getByLabel("Существующий мост").selectOption("*1")
+ await expect(editor.getByLabel("PVID моста", { exact: true })).toHaveValue("1")
+ await expect(editor.getByRole("group", { name: "*11", exact: true })).toBeVisible()
+ const reads = () => calls.filter(call => call.path.endsWith("/bridge-vlan/configuration")).length
+ const before = reads()
+ await editor.getByLabel("PVID моста", { exact: true }).fill("40")
+ await editor.getByRole("button", { name: "Перечитать и сбросить черновик" }).click()
+ await expect.poll(reads).toBe(before + 1)
+ await expect(editor.getByLabel("PVID моста", { exact: true })).toHaveValue("1")
+ expect(calls.filter(call => call.method === "POST")).toHaveLength(0)
+})
+
+test("связанный VLAN: недостоверное состояние и отказ scope видны без отправки плана", async ({ page }) => {
+ const calls = await setup(page, async (route, server) => {
+ if (server === "2") return route.fulfill({ status: 403, json: { error: "Сервер вне scope подключения" } })
+ const state = fixture(); delete (state.bridges[0] as Record)["vlan-filtering"]
+ await route.fulfill({ json: { state } })
+ })
+ const editor = await open(page)
+ await editor.getByLabel("Существующий мост").selectOption("*1")
+ await expect(editor.getByRole("alert")).toContainText("Не подтверждено поле vlan-filtering")
+ await expect(editor.getByRole("button", { name: "Подготовить связанный план VLAN" })).toHaveCount(0)
+ await page.getByLabel("Сервер интерфейсов").selectOption("2")
+ await expect(editor.getByRole("alert")).toContainText("Сервер вне scope подключения")
+ await expect(editor.getByLabel("Существующий мост")).toBeDisabled()
+ expect(calls.filter(call => call.method === "POST")).toHaveLength(0)
+})
+
+test("связанный VLAN: отменённый ответ прежнего сервера не заменяет новый снимок", async ({ page }) => {
+ let release!: () => void, started!: () => void, finished!: () => void
+ const pending = new Promise(resolve => { release = resolve })
+ const requested = new Promise(resolve => { started = resolve })
+ const settled = new Promise(resolve => { finished = resolve })
+ await setup(page, async (route, server) => {
+ const state = fixture()
+ if (server === "1") {
+ started(); await pending
+ state.bridges[0].name = "late-old-bridge"
+ try { await route.fulfill({ json: { state } }) } catch { /* Aborted by scope change. */ } finally { finished() }
+ } else await route.fulfill({ json: { state } })
+ })
+ await page.goto("/mcp?tab=devices")
+ await page.getByLabel("Подключение для управления интерфейсами").selectOption(connectionId)
+ await page.getByLabel("Сервер интерфейсов").selectOption("1")
+ await page.getByLabel("Тип объектов устройства").selectOption("bridge")
+ await requested
+ await page.getByLabel("Сервер интерфейсов").selectOption("2")
+ const editor = page.getByRole("region", { name: "Связанная настройка Bridge VLAN" })
+ await expect(editor.getByLabel("Существующий мост")).toBeEnabled()
+ await editor.getByLabel("Существующий мост").selectOption("*1")
+ await editor.getByLabel("PVID моста", { exact: true }).fill("70")
+ release(); await settled
+ await expect(editor.getByLabel("PVID моста", { exact: true })).toHaveValue("70")
+ await expect(editor.getByRole("option", { name: "late-old-bridge", exact: false })).toHaveCount(0)
+})
diff --git a/tests/e2e/bridge-vlan/plan-review/mcp-context.spec.ts b/tests/e2e/bridge-vlan/plan-review/mcp-context.spec.ts
new file mode 100644
index 00000000..cc619c5a
--- /dev/null
+++ b/tests/e2e/bridge-vlan/plan-review/mcp-context.spec.ts
@@ -0,0 +1,111 @@
+import { test, expect } from "@playwright/test"
+import sdkPlan from "../sdk-public-plan.fixture.json"
+
+// Exact public SDK plan from tmp/mcp-bridge-vlan-sdk-20261105/result.json.
+// The records endpoint uses publicPlan(): planId becomes id and row metadata is
+// added; changes, their sequence, warnings, snapshots and expiry stay untouched.
+// This is a browser/mock-API acceptance check, not native RouterOS forwarding.
+const connectionId = "fa58fa40-4bcb-4616-9316-cb69463b3150"
+const operationId = "690212c5-6e20-423e-b0d9-9791aeb8dbe7"
+const action = "network.bridge-vlan.configure"
+
+for (const outcome of ["applied", "unknown"] as const) {
+ test(`linked VLAN: exact SDK review, human approval, apply and ${outcome} operation`, async ({ page }, testInfo) => {
+ await page.clock.setFixedTime(new Date("2026-11-05T10:42:00.000Z"))
+ const posts: { path: string; body: unknown }[] = []
+ const unexpected: string[] = []
+ let state = sdkPlan.state, applied = false
+ const record = () => ({ id: sdkPlan.planId, connectionId, operationId: action,
+ state, expiresAt: sdkPlan.expiresAt, createdAt: "2026-11-05T10:41:31.883Z",
+ approvedBy: state === "awaiting-approval" ? null : "human-reviewer",
+ changes: sdkPlan.changes })
+ // Operations list returns the redacted SQL row, not mm_operation_get's steps.
+ const result = { id: operationId, plan_id: sdkPlan.planId, connection_id: connectionId,
+ state: outcome, verification: outcome === "applied" ? "passed" : "inconclusive",
+ error_code: outcome === "applied" ? null : "RESULT_UNKNOWN",
+ result: outcome === "applied" ? { confirmedWrites: 3, verificationScope: "configuration" } : { confirmedWrites: 0, needsReview: true },
+ created_at: "2026-11-05T10:42:00.000Z", finished_at: "2026-11-05T10:42:01.000Z",
+ artifactReceipts: [] }
+ await page.route("**/api/**", async route => {
+ const request = route.request(), path = new URL(request.url()).pathname
+ const json = (body: unknown) => route.fulfill({ json: body })
+ if (request.method() === "POST") {
+ posts.push({ path, body: request.postDataJSON() })
+ if (path === `/api/mcp/plans/${sdkPlan.planId}/decision`) {
+ expect(state).toBe("awaiting-approval")
+ expect(request.postDataJSON()).toEqual({ approve: true })
+ state = "approved"
+ return json({ ok: true })
+ }
+ if (path === `/api/mcp/plans/${sdkPlan.planId}/apply`) {
+ expect(state).toBe("approved")
+ expect(request.postDataJSON()).toEqual({})
+ expect(applied).toBe(false)
+ applied = true; state = "completed"
+ return json({ id: operationId, state: "pending" })
+ }
+ unexpected.push(`${request.method()} ${path}`)
+ return route.fulfill({ status: 400, json: { error: "Unexpected mutation" } })
+ }
+ if (path === "/api/auth/config") return json({ required: false })
+ if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [] })
+ if (path === "/api/mcp/plans") return json({ items: [record()], total: 1, nextCursor: null })
+ if (path === "/api/mcp/operations") return json({ items: applied ? [result] : [], total: applied ? 1 : 0, nextCursor: null })
+ if (path === "/api/mcp/connections") return json({ connections: [] })
+ if (path === "/api/servers") return json([])
+ if (path.startsWith("/api/mcp/")) return json({ items: [], total: 0, nextCursor: null })
+ return json({})
+ })
+ await page.goto("/mcp?tab=plans")
+ const plans = page.locator("[data-slot=frame]").filter({ has: page.getByText("Планы изменений", { exact: true }) })
+ const operations = page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) })
+ await plans.getByRole("button", { name: "Открыть", exact: true }).click()
+ const dialog = page.getByRole("dialog", { name: "Детали плана" })
+ await expect(dialog.getByText("Шагов: 3", { exact: true })).toBeVisible()
+ await expect(dialog.getByText("Серверы: 1", { exact: true })).toBeVisible()
+ await expect(dialog.getByText("Сервер 1 · ipv4_address · *20", { exact: true })).toBeVisible()
+ for (const warning of sdkPlan.changes.warnings) await expect(dialog.getByText(warning, { exact: true })).toBeVisible()
+ const steps = dialog.locator("ol > li")
+ await expect(steps).toHaveCount(3)
+ for (const [index, value] of sdkPlan.changes.steps.entries()) {
+ await expect(steps.nth(index).locator("p")).toHaveText(`${index + 1}. ${value.step.action} · ${value.step.resource}`)
+ expect(JSON.parse(await steps.nth(index).locator("pre").innerText())).toEqual(value.step)
+ }
+ const snapshots = dialog.getByRole("heading", { name: "Исходное состояние", exact: true }).locator("..").locator("pre")
+ expect(JSON.parse(await snapshots.innerText())).toEqual(sdkPlan.changes.snapshots)
+ await dialog.getByText("Полные данные плана", { exact: true }).click()
+ expect(JSON.parse(await dialog.locator("details pre").innerText())).toEqual(record())
+ expect(posts).toEqual([])
+ await expect(dialog.getByRole("button", { name: "Применить план", exact: true })).toHaveCount(0)
+ await dialog.screenshot({ path: testInfo.outputPath("linked-vlan-review.png") })
+ await dialog.getByRole("button", { name: "Подтвердить план", exact: true }).click()
+ await expect(dialog).not.toBeVisible()
+ await expect(plans.getByText("approved", { exact: true })).toBeVisible()
+ expect(posts).toEqual([{ path: `/api/mcp/plans/${sdkPlan.planId}/decision`, body: { approve: true } }])
+ await plans.getByRole("button", { name: "Открыть", exact: true }).click()
+ await expect(dialog.getByRole("button", { name: "Подтвердить план", exact: true })).toHaveCount(0)
+ await expect(dialog.getByText("approved", { exact: true })).toBeVisible()
+ await dialog.getByText("Полные данные плана", { exact: true }).click()
+ expect(JSON.parse(await dialog.locator("details pre").innerText())).toEqual(record())
+ const applyResponse = page.waitForResponse(response => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/mcp/plans/${sdkPlan.planId}/apply`)
+ await dialog.getByRole("button", { name: "Применить план", exact: true }).click()
+ expect(await (await applyResponse).json()).toEqual({ id: operationId, state: "pending" })
+ await expect(dialog).not.toBeVisible()
+ await expect(plans.getByText("completed", { exact: true })).toBeVisible()
+ await expect(operations.getByText(outcome, { exact: true })).toBeVisible()
+ expect(posts).toEqual([
+ { path: `/api/mcp/plans/${sdkPlan.planId}/decision`, body: { approve: true } },
+ { path: `/api/mcp/plans/${sdkPlan.planId}/apply`, body: {} },
+ ])
+ await operations.getByRole("button", { name: "Открыть", exact: true }).click()
+ const operationDialog = page.getByRole("dialog", { name: "Детали операции" })
+ expect(JSON.parse(await operationDialog.locator("pre").innerText())).toEqual(result)
+ await operationDialog.screenshot({ path: testInfo.outputPath(`linked-vlan-operation-${outcome}.png`) })
+ await page.keyboard.press("Escape")
+ await operations.getByRole("button", { name: "Обновить", exact: true }).click()
+ await expect(operations.getByText(outcome, { exact: true })).toBeVisible()
+ expect(posts).toHaveLength(2)
+ expect(unexpected).toEqual([])
+ await testInfo.attach("mock-api-evidence", { body: JSON.stringify({ source: "external SDK public plan, synthetic router", planId: sdkPlan.planId, requestSequence: posts, operation: result, nativeForwardingVerified: false }, null, 2), contentType: "application/json" })
+ })
+}
diff --git a/tests/e2e/bridge-vlan/sdk-public-plan.fixture.json b/tests/e2e/bridge-vlan/sdk-public-plan.fixture.json
new file mode 100644
index 00000000..b2655d6d
--- /dev/null
+++ b/tests/e2e/bridge-vlan/sdk-public-plan.fixture.json
@@ -0,0 +1,261 @@
+{
+ "planId": "55205b80-071d-4037-b035-0136a1d02abe",
+ "expiresAt": "2026-11-05T10:56:31.883Z",
+ "state": "awaiting-approval",
+ "decision": {
+ "decision": "approval-required",
+ "reasons": [
+ {
+ "code": "APPROVAL_REQUIRED",
+ "message": "Защищённый объект требует подтверждения человеком"
+ },
+ {
+ "code": "APPROVAL_REQUIRED",
+ "message": "Опасная операция не разрешена для автономного выполнения"
+ }
+ ],
+ "limits": {
+ "callsPerMinute": 120,
+ "concurrentReads": 4,
+ "mutationsPerHour": 100,
+ "serversPerPlan": 5,
+ "objectsPerPlan": 100
+ }
+ },
+ "changes": {
+ "target": {
+ "scope": "servers",
+ "serverIds": [
+ 1
+ ]
+ },
+ "objects": [
+ {
+ "kind": "bridge",
+ "id": "*1",
+ "serverId": 1
+ },
+ {
+ "kind": "bridge_port",
+ "id": "*10",
+ "serverId": 1
+ },
+ {
+ "kind": "bridge_vlan",
+ "id": "*11",
+ "serverId": 1
+ },
+ {
+ "kind": "ethernet",
+ "id": "*2",
+ "serverId": 1
+ },
+ {
+ "kind": "ethernet",
+ "id": "*3",
+ "serverId": 1
+ },
+ {
+ "kind": "ipv4_address",
+ "id": "*20",
+ "serverId": 1
+ },
+ {
+ "kind": "ethernet",
+ "id": "*4",
+ "serverId": 1
+ }
+ ],
+ "snapshots": [
+ {
+ "serverId": 1,
+ "resource": "ethernet",
+ "rows": [
+ {
+ ".id": "*2",
+ "name": "ether2",
+ "disabled": "false"
+ },
+ {
+ ".id": "*3",
+ "name": "ether3",
+ "disabled": "false"
+ },
+ {
+ ".id": "*4",
+ "name": "ether-mgmt",
+ "disabled": "false"
+ }
+ ],
+ "fingerprint": "08c56d03417d39672c01875e949f888bff078a2a3c3219d10462372aff685fae",
+ "projectionVersion": 3,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "bridge",
+ "rows": [
+ {
+ ".id": "*1",
+ "name": "br-users",
+ "pvid": "1",
+ "vlan-filtering": "false",
+ "frame-types": "admit-all",
+ "ingress-filtering": "true",
+ "mvrp": "false",
+ "disabled": "false"
+ }
+ ],
+ "fingerprint": "b6cd139e68a4025879f73982c03458a0f3c1ef7b7a662f87b8421317b86ab5d6",
+ "projectionVersion": 4,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "vlan",
+ "rows": [],
+ "fingerprint": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
+ "projectionVersion": 3,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "gre",
+ "rows": [],
+ "fingerprint": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
+ "projectionVersion": 3,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "wireguard",
+ "rows": [],
+ "fingerprint": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
+ "projectionVersion": 3,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "vxlan",
+ "rows": [],
+ "fingerprint": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
+ "projectionVersion": 3,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "bridge_port",
+ "rows": [
+ {
+ ".id": "*10",
+ "bridge": "br-users",
+ "interface": "ether2",
+ "pvid": "10",
+ "ingress-filtering": "true",
+ "frame-types": "admit-all",
+ "disabled": "false",
+ "comment": ""
+ }
+ ],
+ "fingerprint": "c7e426b6e866bb95030738fef6a244ba1f4ea51bef1b465adb7bb0b524fcae80",
+ "projectionVersion": 4,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "bridge_vlan",
+ "rows": [
+ {
+ ".id": "*11",
+ "bridge": "br-users",
+ "vlan-ids": "10",
+ "tagged": "br-users",
+ "untagged": "ether2",
+ "disabled": "false",
+ "dynamic": "false",
+ "comment": ""
+ }
+ ],
+ "fingerprint": "fec705be87dbc8a3dab3aeb74b0127007d55759eea7dd2b4fc8ecc7f4757b5f6",
+ "projectionVersion": 4,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "ipv4_address",
+ "rows": [
+ {
+ ".id": "*20",
+ "interface": "ether-mgmt",
+ "address": "127.0.0.1/8",
+ "disabled": "false",
+ "dynamic": "false"
+ }
+ ],
+ "fingerprint": "f9c4d5c98f751e7cb3fd9663f57c7731d92a53c096e51a90fd63ed29e314964b",
+ "projectionVersion": 3,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ },
+ {
+ "serverId": 1,
+ "resource": "ipv6_address",
+ "rows": [],
+ "fingerprint": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
+ "projectionVersion": 3,
+ "sourceProof": "e0718c0c34d3799be2f02d129907b9043d4d7de70b24c88a6c65161726befe38"
+ }
+ ],
+ "steps": [
+ {
+ "kind": "ros",
+ "step": {
+ "serverId": 1,
+ "resource": "bridge_vlan",
+ "action": "create",
+ "fields": {
+ "bridge": "br-users",
+ "vlan-ids": "20",
+ "tagged": "br-users,ether3",
+ "disabled": "false"
+ }
+ }
+ },
+ {
+ "kind": "ros",
+ "step": {
+ "serverId": 1,
+ "resource": "bridge_port",
+ "action": "create",
+ "fields": {
+ "bridge": "br-users",
+ "interface": "ether3",
+ "pvid": "1",
+ "ingress-filtering": "true",
+ "frame-types": "admit-only-vlan-tagged",
+ "disabled": "false"
+ }
+ }
+ },
+ {
+ "kind": "ros",
+ "step": {
+ "serverId": 1,
+ "resource": "bridge",
+ "action": "update",
+ "id": "*1",
+ "fields": {
+ "vlan-filtering": "true"
+ }
+ }
+ }
+ ],
+ "requiresHuman": true,
+ "validUntil": "2026-11-05T11:11:31.385Z",
+ "warnings": [
+ "Связанный план изменяет VLAN memberships и PVID в указанном порядке; включение filtering выполняется последним.",
+ "Каждая подтверждённая запись проверяется до следующей. При неизвестном результате дальнейшие записи останавливаются.",
+ "Используется основной адрес управления; независимость канала не подтверждена. Обязательно подтверждение человеком; каждый префикс плана сохраняет подтверждённый management-доступ."
+ ]
+ },
+ "executionAvailable": true
+}
diff --git a/tests/e2e/filters-context.spec.ts b/tests/e2e/filters-context.spec.ts
index 0988d0ea..f374b621 100644
--- a/tests/e2e/filters-context.spec.ts
+++ b/tests/e2e/filters-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import { test, expect, type Page } from "@playwright/test"
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS", "access-control-allow-headers": "Content-Type,Authorization" }
const makeRule = (port: string) => ({ id: "rule-1", community: port === "8101" ? "65001:201" : "65001:101", gateway: "", gatewayTunnelId: "", action: "blackhole", description: port === "8101" ? "Новый источник" : "Старый источник" })
@@ -20,8 +21,7 @@ async function setup(page: Page) {
return () => oldReads
}
async function changeContext(page: Page, change: string) {
- await page.goBack()
- await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
if (change === "backend") {
const input = page.getByPlaceholder("http://localhost:8000")
await input.fill("http://localhost:8101")
diff --git a/tests/e2e/firewall-context.spec.ts b/tests/e2e/firewall-context.spec.ts
index 3a9c352a..15073d1a 100644
--- a/tests/e2e/firewall-context.spec.ts
+++ b/tests/e2e/firewall-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import { test, expect, type Page } from "@playwright/test"
const rule = { id: "rule-1", rosId: "*1", serverId: "1", serverName: "Роутер", family: "ip", table: "filter", chain: "forward", action: "accept", proto: "tcp", src: "", dst: "", port: "443", iface: "", comment: "Контекст правило", enabled: true, hits: 1 }
@@ -40,8 +41,7 @@ for (const fails of [false, true]) {
})
await page.getByRole("button", { name: "Обновить", exact: true }).click()
await expect.poll(() => started).toBe(true)
- await page.goBack()
- await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
await changeBackend(page)
await page.getByRole("link", { name: "Firewall", exact: true }).click()
await expect(page.locator("tr[data-row-id]")).toContainText("8443")
@@ -72,8 +72,7 @@ for (const change of ["backend", "mode"]) {
await page.getByRole("alertdialog").getByRole("button", { name: "Удалить", exact: true }).click()
await expect.poll(() => attempts).toBe(1)
const readsBefore = oldReads()
- await page.goBack()
- await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
if (change === "backend") await changeBackend(page)
else await page.getByRole("button", { name: "Моковые", exact: true }).click()
await page.getByRole("link", { name: "Firewall", exact: true }).click()
diff --git a/tests/e2e/fixtures/mcp-test-fonts.cjs b/tests/e2e/fixtures/mcp-test-fonts.cjs
new file mode 100644
index 00000000..bc5f1880
--- /dev/null
+++ b/tests/e2e/fixtures/mcp-test-fonts.cjs
@@ -0,0 +1,8 @@
+// The auth scenarios check access controls, so their Next server can render
+// with local fonts without reaching Google Fonts during compilation.
+module.exports = {
+ 'https://fonts.googleapis.com/css2?family=Geist:wght@100..900&display=swap':
+ "@font-face { font-family: 'Geist'; font-style: normal; font-weight: 100 900; src: local('Arial'); }",
+ 'https://fonts.googleapis.com/css2?family=Geist+Mono:wght@100..900&display=swap':
+ "@font-face { font-family: 'Geist Mono'; font-style: normal; font-weight: 100 900; src: local('Consolas'); }",
+}
diff --git a/tests/e2e/fixtures/open-settings.ts b/tests/e2e/fixtures/open-settings.ts
new file mode 100644
index 00000000..a1cf1b95
--- /dev/null
+++ b/tests/e2e/fixtures/open-settings.ts
@@ -0,0 +1,14 @@
+import { expect, type Page } from "@playwright/test"
+
+/** Keep the old request in flight while switching settings in the same app. */
+export async function openSettings(page: Page) {
+ // The open confirmation owns focus until the request settles. Browser
+ // Back can navigate while the test still holds that same response.
+ if (await page.getByRole("alertdialog").or(page.getByRole("dialog")).first().isVisible()) {
+ await page.goBack()
+ } else {
+ await page.locator('[data-slot="sidebar-footer"]').getByRole("button").click()
+ await page.getByRole("menuitem", { name: "Настройки", exact: true }).click()
+ }
+ await expect(page).toHaveURL(/\/settings(?:[/?#]|$)/)
+}
diff --git a/tests/e2e/gre-context.spec.ts b/tests/e2e/gre-context.spec.ts
index 51dbd288..45a5ff3d 100644
--- a/tests/e2e/gre-context.spec.ts
+++ b/tests/e2e/gre-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import { test, expect, type Page } from "@playwright/test"
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS", "access-control-allow-headers": "Content-Type,Authorization" }
const payload = (port: string) => ({ tunnels: [{ id: "*old", serverId: "1", name: port === "8101" ? "Новый источник" : "Старый источник", localAddress: "192.0.2.1", remoteAddress: "192.0.2.2", localInnerIp: "10.0.0.1/30", remoteInnerIp: "10.0.0.2/30", poolId: "live", ipsec: null, mtu: 1476, keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit", clampTcpMss: true, allowFastPath: true, comment: "", enabled: true, status: "up" }] })
@@ -16,8 +17,7 @@ async function setup(page: Page) {
return () => oldReads
}
async function change(page: Page, kind: string) {
- await page.goBack()
- await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
if (kind === "backend") {
const input = page.getByPlaceholder("http://localhost:8000")
await input.fill("http://localhost:8101")
diff --git a/tests/e2e/ipsec-cert.spec.ts b/tests/e2e/ipsec-cert.spec.ts
index 87500d21..8ee86623 100644
--- a/tests/e2e/ipsec-cert.spec.ts
+++ b/tests/e2e/ipsec-cert.spec.ts
@@ -1,65 +1,122 @@
-import { test, expect } from "@playwright/test"
+import { test, expect, type Page, type Route } from "@playwright/test"
+
+const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i
+const certificate = (name = "client-cert", role = "client") => ({ name, role, commonName: name, managed: false, hasPrivateKey: true })
+const summary = (certs = [certificate()]) => ({ serverId: "1", serverName: "Роутер", initialized: true, ike2Ready: true, peers: [], natRuleManaged: false, clientsTotal: 1, clientsOnline: 0, certs })
+async function fixture(page: Page, client: Record, certs: ReturnType[], post: (route: Route) => Promise) {
+ await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
+ await page.route("**/api/**", async route => {
+ const path = new URL(route.request().url()).pathname
+ if (route.request().method() === "POST") return post(route)
+ return route.fulfill({ json: path === "/api/auth/config" ? { required: false }
+ : path === "/api/ipsec" ? { servers: [summary(certs)], clients: [client] }
+ : path === "/api/servers" ? [{ id: 1, name: "Роутер", host: "192.0.2.1", enabled: true, type: "exit-node", country: "RU", status: "online" }] : {} })
+ })
+ await page.goto("/ipsec")
+}
+const client = (byName = false) => ({ id: "1", rosId: byName ? "cert:*C1" : "identity:*I1", serverId: "1", serverName: "Роутер", name: "Renamed label", authMethod: "certificate", kind: "cert", certName: "client-cert", online: false, disabled: false, managed: true })
for (const byName of [false, true]) {
- test(`IPsec: экспорт ${byName ? "по имени" : "по identity"} сохраняет контекст и пароль архива`, async ({ page }) => {
- const client = { id: "1", rosId: "*P/1", serverId: "1", serverName: "Роутер", name: "alice", authMethod: "certificate", kind: "cert", certName: byName ? "alice-cert" : undefined, online: false, disabled: false, managed: true }
- let attempts = 0
- let release: (() => void) | undefined
- const gate = new Promise(resolve => { release = resolve })
- let confirmedPassphrase = ""
- await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
- await page.route("**/api/**", async route => {
- const path = new URL(route.request().url()).pathname
- if (route.request().method() === "POST") {
- attempts++
- expect(decodeURIComponent(path)).toBe(byName ? "/api/ipsec/certs/1/export" : "/api/ipsec/users/1/*P/1/cert")
- const body = route.request().postDataJSON()
- if (byName) expect(body.name).toBe("alice-cert")
- expect(body.passphrase.length).toBeGreaterThanOrEqual(8)
- if (attempts === 1) { await gate; return route.fulfill({ json: { user: "stale", filename: "stale.p12", contentB64: "YQ==", passphrase: body.passphrase } }) }
- if (attempts === 2) return route.fulfill({ status: 403, json: { error: "Экспорт запрещён тест" } })
- if (attempts === 3) return route.fulfill({ json: { user: "alice", filename: "alice.p12", contentB64: "!invalid!", passphrase: body.passphrase } })
- if (attempts === 5) return route.fulfill({ status: 500, json: { error: "Повторный экспорт не выполнен" } })
- confirmedPassphrase = body.passphrase
- return route.fulfill({ json: { user: "alice", filename: "alice.p12", contentB64: "YQ==", passphrase: body.passphrase } })
- }
- return route.fulfill({ json: path === "/api/auth/config" ? { required: false }
- : path === "/api/ipsec" ? { servers: [], clients: [client] }
- : path === "/api/servers" ? [{ id: 1, name: "Роутер", host: "192.0.2.1", enabled: true, type: "exit-node", country: "RU", status: "online" }] : {} })
+ test(`IPsec ${byName ? "по имени" : "по identity"}: явный экспорт, UUID и повтор после unknown`, async ({ page }) => {
+ const keys: string[] = []
+ await fixture(page, client(byName), [certificate()], async route => {
+ const body = route.request().postDataJSON(), key = route.request().headers()["idempotency-key"]
+ expect(decodeURIComponent(new URL(route.request().url()).pathname)).toBe(byName ? "/api/ipsec/certs/1/export" : "/api/ipsec/users/1/identity:*I1/cert")
+ expect(body.privateKeyExport).toBe(true); expect(body.caPrivateKeyExport).toBe(false)
+ expect(typeof body.passphrase === "string" && body.passphrase.length >= 8).toBe(true)
+ if (byName) expect(body.name).toBe("client-cert")
+ expect(key).toMatch(uuid); keys.push(key)
+ if (keys.length === 1) return route.fulfill({ status: 502, json: { error: "Результат неизвестен", state: "unknown", needsReview: true } })
+ return route.fulfill({ json: { user: "Renamed label", filename: "client.p12", contentB64: "YQ==", passphrase: body.passphrase } })
})
- await page.goto("/ipsec")
const open = page.getByRole("button", { name: "Скачать сертификат", exact: true })
await open.click()
- const sheet = page.getByRole("dialog")
- await expect(sheet.getByRole("status")).toContainText("Загрузка сертификата")
- await expect.poll(() => attempts).toBe(1)
- await page.keyboard.press("Escape")
- await expect(sheet).toHaveCount(0)
+ let sheet = page.getByRole("dialog", { name: /^Сертификат/ })
+ await expect(sheet).toBeVisible(); expect(keys).toHaveLength(0)
+ await sheet.getByRole("button", { name: "Экспортировать .p12", exact: true }).click()
+ let confirmation = page.getByRole("dialog", { name: "Подтвердить экспорт сертификата", exact: true })
+ await expect(confirmation.getByRole("button", { name: "Подтвердить экспорт", exact: true })).toBeDisabled()
+ expect(keys).toHaveLength(0)
+ await confirmation.getByRole("checkbox", { name: /Разрешаю экспорт и получение/ }).click()
+ await confirmation.getByRole("button", { name: "Отмена", exact: true }).click()
+ expect(keys).toHaveLength(0)
+ await sheet.getByRole("button", { name: "Экспортировать .p12", exact: true }).click()
+ confirmation = page.getByRole("dialog", { name: "Подтвердить экспорт сертификата", exact: true })
+ await expect(confirmation.getByRole("checkbox", { name: /Разрешаю экспорт и получение/ })).not.toBeChecked()
+ await confirmation.getByRole("checkbox", { name: /Разрешаю экспорт и получение/ }).click()
+ await confirmation.getByRole("button", { name: "Подтвердить экспорт", exact: true }).evaluate(button => { (button as HTMLButtonElement).click(); (button as HTMLButtonElement).click() })
+ await expect(sheet.getByText("Результат неизвестен", { exact: true })).toBeVisible()
+ await page.waitForTimeout(100); expect(keys).toHaveLength(1)
+ await sheet.locator('[data-slot="sheet-footer"]').getByRole("button", { name: "Закрыть", exact: true }).click()
await open.click()
- await expect(sheet.getByRole("alert")).toContainText("Экспорт запрещён тест")
- const oldResponse = page.waitForResponse(r => r.request().method() === "POST")
- release!()
- await (await oldResponse).finished()
- await page.waitForTimeout(100)
- await expect(sheet.getByRole("alert")).toContainText("Экспорт запрещён тест")
- await expect(sheet.getByText("stale.p12", { exact: false })).toHaveCount(0)
- const retry = sheet.getByRole("button", { name: "Повторить экспорт" })
- await retry.evaluate(button => { (button as HTMLButtonElement).click(); (button as HTMLButtonElement).click() })
- await expect.poll(() => attempts).toBe(3)
- await expect(sheet.getByRole("alert")).toContainText("Некорректный ответ экспорта")
- await retry.click()
- const password = sheet.getByLabel("Пароль архива .p12")
- await expect(password).toHaveValue(confirmedPassphrase)
- await expect(password).toHaveAttribute("readonly", "")
- const original = confirmedPassphrase
- await sheet.getByRole("button", { name: "Сгенерировать и перекачать" }).click()
- await expect(sheet.getByRole("alert")).toContainText("Повторный экспорт не выполнен")
- await expect(password).toHaveValue(original)
- await expect(sheet.getByRole("button", { name: /alice.p12/ })).toBeEnabled()
- await sheet.getByRole("button", { name: "Сгенерировать и перекачать" }).click()
- await expect.poll(() => attempts).toBe(6)
- await expect(password).not.toHaveValue(original)
- await expect(password).toHaveValue(confirmedPassphrase)
- await expect(sheet.getByRole("alert")).toHaveCount(0)
+ sheet = page.getByRole("dialog", { name: /^Сертификат/ })
+ await expect(sheet.getByText(/Предыдущая попытка завершилась ошибкой/)).toBeVisible()
+ expect(keys).toHaveLength(1)
+ await sheet.getByRole("button", { name: "Подготовить новый запрос", exact: true }).click()
+ confirmation = page.getByRole("dialog", { name: "Подтвердить экспорт сертификата", exact: true })
+ await confirmation.getByRole("checkbox", { name: /Разрешаю экспорт и получение/ }).click()
+ await expect(confirmation.getByRole("button", { name: "Отправить новый запрос" })).toBeDisabled()
+ await confirmation.getByRole("checkbox", { name: /Я проверил состояние роутера/ }).click()
+ await confirmation.getByRole("button", { name: "Отправить новый запрос" }).click()
+ await expect(sheet.getByRole("button", { name: /client.p12/ })).toBeEnabled()
+ expect(keys).toHaveLength(2); expect(keys[1] === keys[0]).toBe(false)
+ await sheet.getByRole("button", { name: "Подтвердить экспорт с новым паролем", exact: true }).click()
+ await expect(page.getByRole("dialog", { name: "Подтвердить экспорт сертификата", exact: true }).getByRole("checkbox", { name: /Разрешаю экспорт и получение/ })).not.toBeChecked()
+ expect(keys).toHaveLength(2)
})
}
+
+for (const role of ["client", "server", "other", "ca"]) {
+ test(`IPsec by-name ${role}: карточка не экспортирует без подтверждения${role === "ca" ? " обоих ключевых согласий" : ""}`, async ({ page }) => {
+ let calls = 0
+ await fixture(page, client(), [certificate(`fixture-${role}`, role)], async route => {
+ calls++
+ const body = route.request().postDataJSON()
+ expect(body.name).toBe(`fixture-${role}`); expect(body.privateKeyExport).toBe(true); expect(body.caPrivateKeyExport).toBe(role === "ca")
+ expect(route.request().headers()["idempotency-key"]).toMatch(uuid)
+ return route.fulfill({ json: { user: role, filename: `${role}.p12`, contentB64: "YQ==", passphrase: body.passphrase } })
+ })
+ await page.getByRole("tab", { name: "Сервер", exact: true }).click()
+ await page.getByRole("button", { name: "Скачать .p12", exact: true }).click()
+ const sheet = page.getByRole("dialog", { name: /^Сертификат/ })
+ await expect(sheet).toBeVisible(); expect(calls).toBe(0)
+ await sheet.getByRole("button", { name: "Экспортировать .p12", exact: true }).click()
+ const confirmation = page.getByRole("dialog", { name: role === "ca" ? "Подтвердить экспорт CA" : "Подтвердить экспорт сертификата", exact: true })
+ await confirmation.getByRole("checkbox", { name: /Разрешаю экспорт и получение/ }).click()
+ const submit = confirmation.getByRole("button", { name: "Подтвердить экспорт", exact: true })
+ if (role === "ca") {
+ await expect(submit).toBeDisabled(); expect(calls).toBe(0)
+ await confirmation.getByRole("checkbox", { name: /Отдельно разрешаю экспорт закрытого ключа/ }).click()
+ } else await expect(confirmation.getByRole("checkbox")).toHaveCount(1)
+ await submit.click()
+ await expect(sheet.getByRole("button", { name: new RegExp(`${role}.p12`) })).toBeEnabled(); expect(calls).toBe(1)
+ })
+}
+
+test("IPsec: закрытие pending экспорта отменяет fetch и требует нового явного подтверждения", async ({ page }) => {
+ let calls = 0, release!: () => void
+ const gate = new Promise(resolve => { release = resolve })
+ await fixture(page, client(), [certificate()], async route => {
+ calls++
+ await gate
+ await route.fulfill({ json: { user: "stale", filename: "stale.p12", contentB64: "YQ==", passphrase: "synthetic-only" } }).catch(() => {})
+ })
+ const open = page.getByRole("button", { name: "Скачать сертификат", exact: true })
+ await open.click()
+ let sheet = page.getByRole("dialog", { name: /^Сертификат/ })
+ await sheet.getByRole("button", { name: "Экспортировать .p12", exact: true }).click()
+ const confirmation = page.getByRole("dialog", { name: "Подтвердить экспорт сертификата", exact: true })
+ await confirmation.getByRole("checkbox", { name: /Разрешаю экспорт и получение/ }).click()
+ await confirmation.getByRole("button", { name: "Подтвердить экспорт", exact: true }).click()
+ await expect.poll(() => calls).toBe(1)
+ const failed = page.waitForEvent("requestfailed", request => request.method() === "POST")
+ await sheet.locator('[data-slot="sheet-footer"]').getByRole("button", { name: "Закрыть", exact: true }).click()
+ await failed
+ await open.click()
+ sheet = page.getByRole("dialog", { name: /^Сертификат/ })
+ await expect(sheet.getByText(/Предыдущая попытка завершилась ошибкой/)).toBeVisible()
+ release()
+ await page.waitForTimeout(100)
+ expect(calls).toBe(1); await expect(sheet.getByText(/stale.p12/)).toHaveCount(0)
+ await expect(sheet.getByRole("button", { name: "Подготовить новый запрос", exact: true })).toBeVisible()
+})
diff --git a/tests/e2e/ipsec-context.spec.ts b/tests/e2e/ipsec-context.spec.ts
index b1c8fed1..e42d0dd2 100644
--- a/tests/e2e/ipsec-context.spec.ts
+++ b/tests/e2e/ipsec-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import { test, expect, type Page } from "@playwright/test"
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS", "access-control-allow-headers": "Content-Type,Authorization" }
const payload = (port: string) => ({ servers: [], clients: [{ id: "1-*1", rosId: "*1", serverId: "1", serverName: "Роутер", name: port === "8101" ? "Новый источник" : "Старый источник", authMethod: "certificate", kind: "cert", online: false, disabled: false, managed: true }] })
@@ -16,8 +17,7 @@ async function setup(page: Page) {
return () => oldReads
}
async function change(page: Page, kind: string) {
- await page.goBack()
- await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
if (kind === "backend") {
const input = page.getByPlaceholder("http://localhost:8000")
await input.fill("http://localhost:8101")
diff --git a/tests/e2e/logs-context.spec.ts b/tests/e2e/logs-context.spec.ts
index f2c52b40..b95587e1 100644
--- a/tests/e2e/logs-context.spec.ts
+++ b/tests/e2e/logs-context.spec.ts
@@ -47,6 +47,30 @@ test("Логи: общий выбор серверов, история и дет
await expect(page.getByText("Все серверы · сохранённая история")).toBeVisible()
expect(errors).toEqual([])
})
+test("Логи: контекст соответствует выбранной записи и устройству", async ({ page }) => {
+ await setup(page)
+ let payload = { entry: row(3), before: [row(81, 2)], after: [row(4)] }
+ await page.route("**/api/logs/3/context", route => route.fulfill({ headers, json: payload }))
+
+ await page.goto("/logs?server=1&live=0")
+ await page.getByRole("button", { name: "Открыть событие 3", exact: true }).click()
+ const detail = page.getByRole("dialog")
+ await detail.getByRole("tab", { name: "Контекст", exact: true }).click()
+ const context = detail.getByRole("tabpanel")
+ const retry = context.getByRole("button", { name: "Повторить", exact: true })
+ await expect(context.getByText("Контекст содержит события другого устройства")).toBeVisible()
+ await expect(context.getByText(/Событие 81/)).toHaveCount(0)
+
+ payload = { entry: row(82), before: [row(1)], after: [row(4)] }
+ await retry.click()
+ await expect(context.getByText("Контекст относится к другому событию")).toBeVisible()
+ await expect(context.getByText(/Событие 82/)).toHaveCount(0)
+
+ payload = { entry: row(3), before: [row(1)], after: [row(4)] }
+ await retry.click()
+ await expect(context.getByRole("button", { name: /Событие 3/ })).toHaveAttribute("aria-current", "true")
+ await expect(context.getByRole("button", { name: /Событие 4/ })).toBeVisible()
+})
test("Логи: поиск в URL, представления и экспорт используют фильтры", async ({ page }) => {
const calls = await setup(page)
await page.goto("/logs?server=1&live=0")
@@ -76,9 +100,13 @@ test("Логи: пауза буферизует новые события", asyn
})
await page.goto("/logs?server=1")
await expect.poll(() => started).toBe(true)
+ const receipt = page.getByLabel("Получение live-логов", { exact: true }).locator("time")
+ await expect(receipt).toHaveCount(0)
await page.getByRole("button", { name: "Пауза", exact: true }).click()
+ const releasedAt = Date.now()
release()
await expect(page.getByRole("button", { name: "Новых событий: 1", exact: true })).toBeVisible()
+ await expect.poll(async () => Date.parse(await receipt.getAttribute("datetime", { timeout: 1000 }) ?? "")).toBeGreaterThanOrEqual(releasedAt)
await expect(page.getByRole("button", { name: "Открыть событие 999", exact: true })).toHaveCount(0)
await page.getByRole("button", { name: "Новых событий: 1", exact: true }).click()
await expect(page.getByRole("button", { name: "Открыть событие 999", exact: true })).toBeVisible()
@@ -142,14 +170,95 @@ test("Логи: настройки сборщика сохраняют подт
expect(writes).toHaveLength(1)
})
test("Логи: обслуживание БД требует нового снимка истории", async ({ page }) => {
- await setup(page)
- let connections = 0
+ const calls = await setup(page)
+ const cursors: Array = []
+ await page.clock.install()
await page.route("**/api/logs/live?**", route => {
- connections++
- return route.fulfill({ headers: { ...headers, "content-type": "text/event-stream" }, body: 'event: reset\ndata: {"reason":"database-maintenance"}\n\n' })
+ cursors.push(new URL(route.request().url()).searchParams.get("cursor"))
+ const first = cursors.length === 1
+ const id = first ? 90 : 91
+ const batch = `event: batch\ndata: ${JSON.stringify({ entries: [row(id)], cursor: String(id), state: state(1), enabled: true })}\n\n`
+ const reset = 'event: reset\ndata: {"reason":"database-maintenance"}\n\n'
+ return route.fulfill({ headers: { ...headers, "content-type": "text/event-stream" }, body: first ? batch + reset : batch })
})
await page.goto("/logs?server=1")
await expect(page.getByText("Поток остановлен для обслуживания БД.", { exact: false })).toBeVisible()
+ await expect(page.getByText("Live остановлен", { exact: true })).toBeVisible()
+ await expect(page.getByText("Live подключён", { exact: true })).toHaveCount(0)
+ await expect(page.getByLabel("Получение live-логов", { exact: true })).toHaveCount(0)
+ await page.clock.fastForward(2000)
+ expect(cursors).toEqual(["3"])
+
+ const historyReads = calls.filter(url => url.pathname === "/api/logs").length
+ await page.getByRole("button", { name: "Повторить", exact: true }).click()
+ await expect(page.getByRole("button", { name: "Открыть событие 91", exact: true })).toBeVisible()
+ expect(calls.filter(url => url.pathname === "/api/logs")).toHaveLength(historyReads + 1)
+ expect(cursors.slice(0, 2)).toEqual(["3", "3"])
+ await expect(page.getByText("Поток остановлен для обслуживания БД.", { exact: false })).toHaveCount(0)
+})
+
+test("Логи: отказ в доступе останавливает Live", async ({ page }) => {
+ await setup(page)
+ await page.clock.install()
+ let connections = 0
+ await page.route("**/api/logs/live?**", route => {
+ connections++
+ return route.fulfill({ headers, status: 403, json: { error: "Доступ к потоку отозван" } })
+ })
+
+ await page.goto("/logs?server=1")
+ await expect(page.getByText("Live остановлен", { exact: true })).toBeVisible()
+ await expect(page.getByText("Доступ к потоку отозван", { exact: true })).toBeVisible()
+ await expect(page.getByText("Переподключение", { exact: true })).toHaveCount(0)
+ await page.clock.fastForward(2000)
expect(connections).toBe(1)
- await expect(page.getByRole("button", { name: "Повторить", exact: true })).toBeVisible()
+})
+
+test("Логи: пагинация использует фильтры текущего снимка после обновления", async ({ page }) => {
+ await setup(page)
+ await page.clock.install()
+ let refreshed = false
+ let releaseOldPage!: () => void
+ const oldPage = new Promise(resolve => { releaseOldPage = resolve })
+ const initialPages: URLSearchParams[] = [], continuations: URLSearchParams[] = []
+ await page.route("**/api/logs?**", async route => {
+ const params = new URL(route.request().url()).searchParams
+ if (params.has("cursor")) {
+ continuations.push(params)
+ const old = continuations.length === 1
+ if (old) await oldPage
+ await route.fulfill({ headers, json: { entries: [row(old ? 48 : 148)], nextCursor: null, watermark: old ? "100" : "200" } }).catch(() => {})
+ return
+ }
+ initialPages.push(params)
+ const watermark = refreshed ? "200" : "100"
+ const time = new Date().toISOString()
+ const entries = Array.from({ length: 50 }, (_, i) => ({ ...row(Number(watermark) - i), effectiveAt: time }))
+ return route.fulfill({ headers, json: { entries, nextCursor: `cursor-${watermark}`, watermark } })
+ })
+
+ await page.goto("/logs?server=1")
+ const more = page.getByRole("button", { name: "Загрузить ещё", exact: true })
+ await more.click()
+ await expect.poll(() => continuations.length).toBe(1)
+ await expect(page.getByRole("button", { name: "Загрузка…", exact: true })).toBeDisabled()
+ const oldFrom = initialPages.at(-1)?.get("from")
+
+ refreshed = true
+ await page.clock.fastForward(60_000)
+ await page.getByRole("button", { name: "Обновить", exact: true }).click()
+ try {
+ await expect(page.getByRole("button", { name: "Открыть событие 200", exact: true })).toBeVisible()
+ await more.click({ timeout: 5000 })
+ await expect.poll(() => continuations.length).toBe(2)
+ } finally { releaseOldPage() }
+ expect(initialPages.at(-1)?.get("from")).not.toBe(oldFrom)
+ const freshPage = new URLSearchParams(continuations[1])
+ expect(freshPage.get("cursor")).toBe("cursor-200")
+ expect(freshPage.get("watermark")).toBe("200")
+ freshPage.delete("cursor"); freshPage.delete("watermark")
+ expect(freshPage.toString()).toBe(initialPages.at(-1)?.toString())
+ await expect(more).toHaveCount(0)
+ await expect(page.getByRole("button", { name: "Открыть событие 148", exact: true })).toBeVisible()
+ await expect(page.getByRole("button", { name: "Открыть событие 48", exact: true })).toHaveCount(0)
})
diff --git a/tests/e2e/mcp-auth-context.spec.ts b/tests/e2e/mcp-auth-context.spec.ts
new file mode 100644
index 00000000..33fa9f77
--- /dev/null
+++ b/tests/e2e/mcp-auth-context.spec.ts
@@ -0,0 +1,392 @@
+import { test, expect, type Page } from '@playwright/test'
+
+// Synthetic JWT and routed API responses. This exercises the shipped UI only;
+// it does not verify backend enforcement, Portal/Sender or a live end-user route.
+const id = 'fa58fa40-4bcb-4616-9316-cb69463b3150'
+const at = '2026-10-29T00:00:00Z'
+const read = { id: 'logs.query', toolName: 'mm_logs_query', title: 'Поиск логов', section: 'logs', version: 1, effect: 'read', risk: 'ordinary', scope: 'servers', requiredPermissions: ['mm:servers:read'], implementation: 'available', annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true } }
+const forbidden = { ...read, id: 'users.delete', title: 'Запрещённая операция каталога', requiredPermissions: ['mm:users:admin'], effect: 'write' }
+async function setup(page: Page, permissions: string[], access: { expiresAt?: string; ownerValidUntil?: string; status?: string; generationValid?: boolean } = {}) {
+ await page.addInitScript(permissions => { localStorage.setItem('mmapp_token', 'header.' + btoa(JSON.stringify({ sub: 'synthetic-owner', apps: ['mm'], permissions, exp: 4102444800 })) + '.signature') }, permissions)
+ const connection = { id, name: 'Синтетический AI клиент', ownerId: 'synthetic-owner', policy: { id, version: 1, status: 'active', mode: 'observer', expiresAt: '2099-01-01T00:00:00Z', permissions: ['mm:servers:read'], scope: { serverIds: [1], operationIds: ['logs.query'], allowGlobal: false }, dangerousPolicy: 'approval', autonomousDangerousOperationIds: [], limits: { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 } }, createdAt: at, updatedAt: at, lastUsedAt: null, generationValid: true }
+ const mutations: { path: string, body: Record }[] = []
+ connection.policy.expiresAt = access.expiresAt ?? connection.policy.expiresAt
+ connection.policy.status = access.status ?? connection.policy.status
+ connection.generationValid = access.generationValid ?? connection.generationValid
+ const ownerValidUntil = access.ownerValidUntil ?? '2099-01-01T00:00:00Z'
+ let connectionReads = 0
+ let enabled = true
+ await page.route('**/api/**', async route => {
+ const request = route.request(), path = new URL(request.url()).pathname, method = request.method()
+ const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST,PUT,DELETE,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
+ if (method === 'OPTIONS') return route.fulfill({ status: 204, headers })
+ const json = (body: unknown) => route.fulfill({ headers, json: body })
+ if (method !== 'GET') mutations.push({ path, body: request.postDataJSON() })
+ if (path === '/api/auth/config') return json({ required: true })
+ if (path === '/api/mcp/catalog') return json({ stage: 'runtime', executionAvailable: true, operations: [read, forbidden] })
+ if (path === '/api/mcp/overview') return json({ connections: 1, calls: 3, errors: 1, approvals: 0, running: 0, enabled, observedAt: at })
+ if (path === '/api/mcp/connections') { connectionReads++; const visible = { ...connection, ownerValidUntil }; return json(method === 'POST' ? { connection: visible, token: 'synthetic-one-time-token' } : { connections: [visible] }) }
+ if (path === `/api/mcp/connections/${id}/status`) { connection.policy.status = request.postDataJSON().status; return json({ ok: true }) }
+ if (path === '/api/mcp/stop-automation') { enabled = false; return json({ ok: true }) }
+ if (path === '/api/mcp/requests') return json({ items: [{ id: 'synthetic-call', tool: 'mm_logs_query', created_at: at, connection_id: id, status: connection.policy.status === 'active' ? 'completed' : 'denied', error_code: connection.policy.status === 'active' ? null : `connection_${connection.policy.status}`, detail: 'synthetic fixture outcome' }], total: 1, nextCursor: null })
+ if (path.endsWith('/grants')) return json({ grants: [] })
+ if (path === '/api/servers') return json([])
+ return json({ items: [], total: 0, nextCursor: null })
+ })
+ return { mutations, get connectionReads() { return connectionReads } }
+}
+
+for (const [access, label, reason] of [
+ [{ expiresAt: '2000-01-01T00:00:00Z' }, 'Срок доступа истёк', 'Продлите срок в разрешениях подключения'],
+ [{ ownerValidUntil: '2000-01-01T00:00:00Z' }, 'Права владельца истекли', 'Владельцу нужно подтвердить актуальные права'],
+ [{ status: 'paused' }, 'На паузе', 'Новые вызовы подключения остановлены'],
+ [{ status: 'revoked' }, 'Доступ отозван', 'Подключение и его токены отозваны'],
+ [{ generationValid: false }, 'Доступ аннулирован', 'Поколение доступа больше не действительно'],
+] as const) test(`synthetic: connection state explains ${label}`, async ({ page }, testInfo) => {
+ await setup(page, ['mm:mcp:read'], access)
+ await page.goto('/mcp?tab=connections')
+ const row = page.getByRole('row').filter({ hasText: 'Синтетический AI клиент' })
+ await expect(row.getByText(label, { exact: true })).toBeVisible()
+ await expect(row.getByText(reason, { exact: true })).toBeVisible()
+ await expect(row.getByText('Активен', { exact: true })).toHaveCount(0)
+ await expect(page.getByRole('columnheader', { name: 'Доступ до', exact: true })).toBeVisible()
+ await expect(page.getByRole('columnheader', { name: 'Права владельца до', exact: true })).toBeVisible()
+ if (label === 'Срок доступа истёк') {
+ await row.screenshot({ path: testInfo.outputPath('connection-expired-desktop.png') })
+ await page.setViewportSize({ width: 390, height: 844 })
+ await row.getByText(label, { exact: true }).scrollIntoViewIfNeeded()
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true)
+ await page.screenshot({ path: testInfo.outputPath('connection-expired-mobile.png') })
+ }
+})
+
+for (const field of ['expiresAt', 'ownerValidUntil'] as const) test(`synthetic: connection clock crosses ${field} without another API response`, async ({ page }) => {
+ const start = new Date('2030-01-01T00:00:00Z')
+ await page.clock.install({ time: start })
+ const state = await setup(page, ['mm:mcp:read'], { [field]: '2030-01-01T01:00:02Z' })
+ await page.goto('/mcp?tab=connections')
+ const row = page.getByRole('row').filter({ hasText: 'Синтетический AI клиент' })
+ await expect(row.getByText('Активен', { exact: true })).toBeVisible()
+ await page.clock.pauseAt(new Date('2030-01-01T01:00:00Z'))
+ // Ignore any catch-up polling from pauseAt; the crossing below is <5 seconds.
+ await page.waitForLoadState('networkidle')
+ const reads = state.connectionReads
+ await page.clock.runFor(2100)
+ await expect(row.getByText(field === 'expiresAt' ? 'Срок доступа истёк' : 'Права владельца истекли', { exact: true })).toBeVisible()
+ await expect(row.getByText('Активен', { exact: true })).toHaveCount(0)
+ expect(state.connectionReads).toBe(reads)
+ expect(state.mutations).toEqual([])
+})
+
+test('synthetic: bind OAuth consent to the displayed request and submit only once', async ({ page }) => {
+ await setup(page, ['mm:mcp:read'])
+ const firstId = 'fa58fa40-4bcb-4616-9316-cb69463b3151'
+ const secondId = 'fa58fa40-4bcb-4616-9316-cb69463b3152'
+ const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
+ const first = { id: firstId, name: 'OAuth A', redirect_uri: 'https://a.example.test/callback', scope: 'mcp' }
+ const second = { id: secondId, name: 'OAuth B', redirect_uri: 'https://b.example.test/callback', scope: 'mcp' }
+ let releaseSecond!: () => void
+ const secondPending = new Promise(resolve => { releaseSecond = resolve })
+ await page.route('**/api/mcp/oauth/requests/*', async route => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
+ const isSecond = route.request().url().endsWith(secondId)
+ if (isSecond) await secondPending
+ await route.fulfill({ headers, json: isSecond ? second : first })
+ })
+ let releasePost!: () => void
+ const postPending = new Promise(resolve => { releasePost = resolve })
+ const decisions: unknown[] = []
+ await page.route('**/api/mcp/oauth/consent', async route => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
+ decisions.push(route.request().postDataJSON())
+ await postPending
+ await route.fulfill({ status: 409, headers, json: { message: 'Синтетический отказ' } })
+ })
+
+ await page.goto('/mcp?oauthRequest=' + firstId)
+ const connection = page.getByLabel('Подключение', { exact: true })
+ const approve = page.getByRole('button', { name: 'Разрешить', exact: true })
+ const deny = page.getByRole('button', { name: 'Отклонить', exact: true })
+ await expect(page.getByText(first.redirect_uri, { exact: false })).toBeVisible()
+ await connection.selectOption(id)
+ await expect(approve).toBeEnabled()
+ const secondRequest = page.waitForRequest(request => request.method() === 'GET' && request.url().endsWith('/oauth/requests/' + secondId))
+ await page.evaluate(id => window.history.pushState(null, '', '/mcp?oauthRequest=' + id), secondId)
+ await secondRequest
+ await expect(page.getByText(first.redirect_uri, { exact: false })).toHaveCount(0)
+ await expect(connection).toHaveValue('')
+ await expect(approve).toBeDisabled()
+ await expect(deny).toBeDisabled()
+ expect(decisions).toEqual([])
+
+ releaseSecond()
+ await expect(page.getByText(second.redirect_uri, { exact: false })).toBeVisible()
+ await connection.selectOption(id)
+ await expect(approve).toBeEnabled()
+ await approve.evaluate((button, denyLabel) => {
+ const approve = button as HTMLButtonElement
+ const deny = [...document.querySelectorAll('button')].find(node => node.textContent === denyLabel)
+ approve.click()
+ deny?.click()
+ }, 'Отклонить')
+ await expect.poll(() => decisions).toEqual([{ requestId: secondId, connectionId: id, approve: true }])
+ await expect(approve).toBeDisabled()
+ await expect(deny).toBeDisabled()
+ releasePost()
+ await expect(approve).toBeEnabled()
+ expect(decisions).toHaveLength(1)
+})
+
+test('synthetic: OAuth consent does not redirect after the Portal session changes', async ({ page, baseURL }) => {
+ await setup(page, ['mm:mcp:read'])
+ const requestId = 'fa58fa40-4bcb-4616-9316-cb69463b3153'
+ const callback = new URL('/local-oauth-callback', baseURL!)
+ const start = new URL(`/mcp?oauthRequest=${requestId}`, baseURL!)
+ const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
+ await page.route(`**/api/mcp/oauth/requests/${requestId}`, route => route.fulfill({ headers, json: { id: requestId, name: 'OAuth session binding', redirect_uri: callback.href, scope: 'mcp' } }))
+ callback.searchParams.set('code', 'synthetic-authorization-code')
+ let callbackRequests = 0
+ await page.route(callback.href, route => { callbackRequests++; return route.fulfill({ body: 'OAuth callback' }) })
+ let releasePost!: () => void
+ const pending = new Promise(resolve => { releasePost = resolve })
+ await page.route('**/api/mcp/oauth/consent', async route => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
+ await pending
+ return route.fulfill({ headers, json: { redirectUrl: callback.href } })
+ })
+
+ await page.goto(start.href)
+ const connection = page.getByLabel('Подключение', { exact: true })
+ const approve = page.getByRole('button', { name: 'Разрешить', exact: true })
+ await connection.selectOption(id)
+ const decision = page.waitForRequest(request => request.method() === 'POST' && request.url().endsWith('/api/mcp/oauth/consent'))
+ await approve.click()
+ expect((await decision).postDataJSON()).toEqual({ requestId, approve: true, connectionId: id })
+
+ try {
+ const otherTab = await page.context().newPage()
+ const portalReturn = new URL('/local-portal-session', baseURL!)
+ await otherTab.route(portalReturn.href, route => route.fulfill({ body: 'local Portal session fixture' }))
+ await otherTab.goto(portalReturn.href)
+ await otherTab.evaluate(() => {
+ localStorage.setItem('mmapp_token', 'header.' + btoa(JSON.stringify({ sub: 'other-owner', apps: ['mm'], permissions: ['mm:mcp:read'], exp: 4102444800 })) + '.signature')
+ })
+ await otherTab.close()
+ } finally { releasePost() }
+
+ await expect(page.getByRole('alert').filter({ hasText: 'Сессия портала изменилась' })).toBeVisible()
+ await expect(approve).toBeDisabled()
+ await expect(page.getByRole('button', { name: 'Отклонить', exact: true })).toBeDisabled()
+ await expect(page).toHaveURL(start.href)
+ expect(callbackRequests).toBe(0)
+})
+
+test('synthetic: concurrent unauthorized MCP reads hand off to Portal once', async ({ page, baseURL }) => {
+ await setup(page, ['mm:mcp:read'])
+ const portal = 'http://127.0.0.1:3165'
+ const operationPath = `/mcp?tab=plans&operation=${id}`
+ await page.route('**/api/auth/config', route => route.fulfill({ json: { required: true, portal_url: portal } }))
+ let revoked = false, refusals = 0
+ let delayedRefusal: Promise | undefined
+ const headers = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'Authorization' }
+ await page.route(/\/api\/mcp\/(operations|plans|drift)\?/, async route => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
+ const selected = new URL(route.request().url()).searchParams.get('operationId') === id
+ if (selected && delayedRefusal) {
+ const wait = delayedRefusal
+ delayedRefusal = undefined
+ await wait
+ return route.fulfill({ status: 401, headers, json: { error: 'Unauthorized' } })
+ }
+ if (revoked) {
+ refusals++
+ return route.fulfill({ status: 401, headers, json: { error: 'Unauthorized' } })
+ }
+ return route.fulfill({ headers, json: { items: selected ? [{ id, state: 'applied', steps: [{ step_index: 0, state: 'verified' }] }] : [], total: selected ? 1 : 0, nextCursor: null } })
+ })
+ const handoffs: URL[] = []
+ await page.route(url => url.origin === portal && url.pathname === '/', async route => {
+ handoffs.push(new URL(route.request().url()))
+ await expect.poll(() => refusals).toBeGreaterThan(1)
+ await route.fulfill({ contentType: 'text/html', body: 'Portal sign-in ' })
+ })
+
+ await page.goto(operationPath)
+ const step = page.getByRole('region', { name: 'Шаги выполнения' }).getByText('Результат проверен')
+ await expect(step).toBeVisible()
+ const refresh = page.getByRole('button', { name: 'Обновить выполнение' })
+ let releaseRefusal!: () => void
+ delayedRefusal = new Promise(resolve => { releaseRefusal = resolve })
+ try {
+ await Promise.all([
+ page.waitForRequest(request => request.method() === 'GET' && new URL(request.url()).searchParams.get('operationId') === id),
+ refresh.click(),
+ ])
+ await page.evaluate(() => {
+ localStorage.setItem('mmapp_token', 'header.' + btoa(JSON.stringify({ sub: 'new-session', apps: ['mm'], permissions: ['mm:mcp:read'], exp: 4102444800 })) + '.signature')
+ })
+ } finally { releaseRefusal() }
+ await expect(page.getByRole('alert').filter({ hasText: 'Unauthorized' })).toBeVisible()
+ expect(handoffs).toHaveLength(0)
+
+ revoked = true
+ await refresh.click()
+ await expect(page.getByRole('heading', { name: 'Portal sign-in' })).toBeVisible()
+ expect(handoffs).toHaveLength(1)
+ const callback = new URL(handoffs[0].searchParams.get('return_to')!)
+ expect(callback.origin).toBe(new URL(baseURL!).origin)
+ expect(callback.pathname).toBe('/auth/callback')
+ expect(callback.searchParams.get('next')).toBe(operationPath)
+ await expect(step).toHaveCount(0)
+})
+
+test('synthetic: deny OAuth consent without an available connection', async ({ page, baseURL }) => {
+ await setup(page, ['mm:mcp:read'])
+ const requestId = 'fa58fa40-4bcb-4616-9316-cb69463b3151'
+ const callback = new URL('/local-oauth-callback', baseURL!)
+ const response = { id: requestId, name: 'OAuth without connection', redirect_uri: callback.href, scope: 'mcp' }
+ callback.searchParams.set('error', 'access_denied')
+ const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
+ await page.route('**/api/mcp/connections', route => route.fulfill({ headers, json: { connections: [] } }))
+ await page.route(`**/api/mcp/oauth/requests/${requestId}`, route => route.fulfill({ headers, json: response }))
+ const decisions: unknown[] = []
+ await page.route('**/api/mcp/oauth/consent', async route => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers })
+ decisions.push(route.request().postDataJSON())
+ await route.fulfill({ headers, json: { redirectUrl: callback.href } })
+ })
+ await page.route(callback.href, route => route.fulfill({ body: 'OAuth request declined' }))
+
+ await page.goto('/mcp?oauthRequest=' + requestId)
+ await expect(page.getByText('OAuth without connection запрашивает доступ к MikrotikManager.')).toBeVisible()
+ await expect(page.getByLabel('Подключение', { exact: true }).locator('option')).toHaveCount(1)
+ await expect(page.getByRole('button', { name: 'Разрешить', exact: true })).toBeDisabled()
+ await page.getByRole('button', { name: 'Отклонить', exact: true }).click()
+ await expect(page).toHaveURL(callback.href)
+ expect(decisions).toEqual([{ requestId, approve: false }])
+})
+
+test('synthetic: OAuth approval becomes unavailable when the selected connection expires', async ({ page }) => {
+ const start = new Date('2030-01-01T00:00:00Z')
+ await page.clock.install({ time: start })
+ await page.clock.pauseAt(new Date('2030-01-01T00:00:01Z'))
+ const state = await setup(page, ['mm:mcp:read'], { expiresAt: '2030-01-01T00:00:03Z' })
+ const requestId = 'fa58fa40-4bcb-4616-9316-cb69463b3151'
+ const headers = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,OPTIONS', 'access-control-allow-headers': 'Authorization,Content-Type' }
+ await page.route(`**/api/mcp/oauth/requests/${requestId}`, route => route.request().method() === 'OPTIONS'
+ ? route.fulfill({ status: 204, headers })
+ : route.fulfill({ headers, json: { id: requestId, name: 'OAuth expiry', redirect_uri: 'https://a.example.test/callback', scope: 'mcp' } }))
+ await page.goto('/mcp?oauthRequest=' + requestId)
+ const connection = page.getByLabel('Подключение', { exact: true })
+ const approve = page.getByRole('button', { name: 'Разрешить', exact: true })
+ await connection.selectOption(id)
+ await expect(approve).toBeEnabled()
+ const reads = state.connectionReads
+ await page.clock.runFor(2100)
+ await expect(approve).toBeDisabled()
+ await expect(connection.locator('option')).toHaveCount(1)
+ await expect(page.getByRole('button', { name: 'Отклонить', exact: true })).toBeEnabled()
+ expect(state.connectionReads).toBe(reads)
+ expect(state.mutations).toEqual([])
+})
+
+test('synthetic: issue only selected server/read permission and hide one-time token', async ({ page }) => {
+ const state = await setup(page, ['mm:mcp:admin', 'mm:servers:read'])
+ await page.goto('/mcp?tab=connections')
+ await page.getByRole('button', { name: 'Выдать доступ', exact: true }).click()
+ const dialog = page.getByRole('dialog')
+ await dialog.getByLabel('Название', { exact: true }).fill('Ограниченная диагностика')
+ await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
+ await expect(dialog.getByRole('checkbox', { name: forbidden.title, exact: true })).toHaveCount(0)
+ await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1')
+ await dialog.getByRole('checkbox', { name: read.title, exact: true }).check()
+ await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
+ await dialog.getByRole('button', { name: 'Далее', exact: true }).click()
+ await expect(dialog).toContainText('Глобальный доступ: нет')
+ await dialog.getByRole('button', { name: 'Сохранить доступ', exact: true }).click()
+ const token = page.getByLabel('Одноразовый токен MCP')
+ await expect(token).toHaveValue('synthetic-one-time-token')
+ await expect(token).toHaveAttribute('type', 'password')
+ expect(state.mutations).toHaveLength(1)
+ expect(state.mutations[0]).toMatchObject({ path: '/api/mcp/connections', body: { permissions: ['mm:servers:read'], scope: { serverIds: [1], operationIds: ['logs.query'], allowGlobal: false }, mode: 'observer' } })
+ await page.getByRole('button', { name: 'Закрыть и скрыть токен' }).click()
+ await expect(token).toHaveCount(0)
+ await page.reload()
+ await expect(token).toHaveCount(0)
+})
+
+test('synthetic: pause, resume, cancelled revoke, revoke, monitor denied outcome, stop automation', async ({ page }) => {
+ const state = await setup(page, ['mm:mcp:admin', 'mm:mcp:pause', 'mm:servers:read'])
+ await page.goto('/mcp?tab=connections')
+ await page.getByRole('button', { name: 'Пауза', exact: true }).click()
+ await expect(page.getByRole('button', { name: 'Включить', exact: true })).toBeEnabled()
+ expect(state.mutations.at(-1)?.body).toEqual({ status: 'paused' })
+ await page.getByRole('tab', { name: 'Обращения', exact: true }).click()
+ await expect(page.getByRole('cell', { name: 'connection_paused', exact: true })).toBeVisible()
+ await page.getByRole('button', { name: 'Открыть', exact: true }).click()
+ await expect(page.getByRole('dialog')).toContainText('synthetic fixture outcome')
+ await page.keyboard.press('Escape')
+ await page.getByRole('tab', { name: 'Подключения', exact: true }).click()
+ await page.getByRole('button', { name: 'Включить', exact: true }).click()
+ await expect(page.getByRole('button', { name: 'Пауза', exact: true })).toBeEnabled()
+ page.once('dialog', dialog => dialog.dismiss())
+ await page.getByRole('button', { name: 'Отозвать', exact: true }).click()
+ expect(state.mutations.filter(x => x.body.status === 'revoked')).toHaveLength(0)
+ page.once('dialog', dialog => dialog.accept())
+ await page.getByRole('button', { name: 'Отозвать', exact: true }).click()
+ await expect(page.getByRole('button', { name: 'Отозвать', exact: true })).toBeDisabled()
+ await expect(page.getByRole('button', { name: 'Включить', exact: true })).toBeDisabled()
+ await expect(page.getByRole('button', { name: 'Новый токен', exact: true })).toBeDisabled()
+ await page.getByRole('tab', { name: 'Обращения', exact: true }).click()
+ await expect(page.getByRole('cell', { name: 'connection_revoked', exact: true })).toBeVisible()
+ await expect(page.getByRole('cell', { name: 'denied', exact: true })).toBeVisible()
+ await page.getByRole('tab', { name: 'Обзор', exact: true }).click()
+ page.once('dialog', dialog => dialog.accept())
+ await page.getByRole('button', { name: 'Остановить автоматические изменения', exact: true }).click()
+ await expect(page.getByText('MCP выключен', { exact: true })).toBeVisible()
+ expect(state.mutations.map(x => [x.path, x.body])).toEqual([
+ [`/api/mcp/connections/${id}/status`, { status: 'paused' }],
+ [`/api/mcp/connections/${id}/status`, { status: 'active' }],
+ [`/api/mcp/connections/${id}/status`, { status: 'revoked' }],
+ ['/api/mcp/stop-automation', {}],
+ ])
+})
+
+test('synthetic: read-only role cannot issue/revoke/pause or reach settings', async ({ page }) => {
+ const state = await setup(page, ['mm:mcp:read'])
+ await page.goto('/mcp?tab=connections')
+ await expect(page.getByText('Синтетический AI клиент', { exact: true })).toBeVisible()
+ await expect(page.getByRole('tab', { name: 'Настройки', exact: true })).toHaveCount(0)
+ await expect(page.getByRole('link', { name: 'Проверить права', exact: true })).toHaveCount(0)
+ await expect(page.getByRole('link', { name: 'Журнал подключения', exact: true })).toBeVisible()
+ for (const name of ['Выдать доступ', 'Пауза', 'Отозвать', 'Новый токен', 'Выдать временный допуск']) await expect(page.getByRole('button', { name, exact: true })).toHaveCount(0)
+ await page.getByRole('tab', { name: 'Обзор', exact: true }).click()
+ await expect(page.getByText('MCP включён', { exact: true })).toBeVisible()
+ await expect(page.getByRole('button', { name: 'Остановить автоматические изменения', exact: true })).toHaveCount(0)
+ await page.goto('/mcp?tab=settings')
+ await expect(page.getByRole('heading', { name: 'MCP', exact: true })).toBeVisible()
+ await expect(page.getByText('Настройки MCP', { exact: true })).toHaveCount(0)
+ await expect(page.getByRole('tab', { name: 'Обзор', exact: true })).toHaveAttribute('aria-selected', 'true')
+ await page.goto(`/mcp?tab=permissions&connection=${id}`)
+ await expect(page.getByLabel('Подключение', { exact: true })).toHaveValue(id)
+ await expect(page.getByRole('button', { name: 'Проверить', exact: true })).toHaveCount(0)
+ await expect(page.getByRole('button', { name: 'Добавить защиту', exact: true })).toHaveCount(0)
+ await page.goto(`/mcp?tab=plans&reconcile=${id}`)
+ await expect(page.getByRole('button', { name: 'Сверить состояние операции', exact: true })).toHaveCount(0)
+ expect(state.mutations).toEqual([])
+})
+
+test('synthetic: direct application URLs enforce declared route permissions', async ({ page }) => {
+ await setup(page, ['mm:mcp:read', 'mm:servers:read'])
+
+ await page.goto('/logs')
+ await expect(page.getByRole('heading', { name: 'Логи MikroTik', exact: true })).toBeVisible()
+ await page.goto('/mcp?tab=settings')
+ await expect(page.getByRole('heading', { name: 'MCP', exact: true })).toBeVisible()
+
+ for (const path of ['/settings', '/traffic']) {
+ await page.goto(path)
+ await expect(page).toHaveURL(/\/access-denied$/)
+ await expect(page.getByRole('heading', { name: 'Нет доступа', exact: true })).toBeVisible()
+ }
+})
diff --git a/tests/e2e/mcp-context.spec.ts b/tests/e2e/mcp-context.spec.ts
new file mode 100644
index 00000000..bcf12986
--- /dev/null
+++ b/tests/e2e/mcp-context.spec.ts
@@ -0,0 +1,1193 @@
+import { test, expect, type Page } from "@playwright/test"
+import { createHash } from "node:crypto"
+import { evaluateMcpPolicy } from "../../backend/src/modules/mcp/policy"
+import type { McpPolicyPreviewRequest } from "@mmapp/contracts/mcp"
+const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
+const at = "2026-10-17T00:00:00Z"
+const operation = { id: "logs.query", toolName: "mm_logs_query", title: "Поиск логов", section: "logs", version: 1, effect: "read", risk: "ordinary", scope: "servers", requiredPermissions: ["mm:servers:read"], implementation: "available", annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true } }
+const connection = { id, name: "Диагностика WAN", ownerId: "ui-admin", policy: { id, version: 1, status: "active", mode: "approval", expiresAt: "2099-01-01T00:00:00Z", permissions: ["mm:servers:read"], scope: { serverIds: [1], operationIds: ["logs.query", "routing.profiles.save"], allowGlobal: false }, dangerousPolicy: "approval", autonomousDangerousOperationIds: [], limits: { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 } }, createdAt: at, updatedAt: at, lastUsedAt: null, generationValid: true }
+async function setup(page: Page, fail = false) {
+ await page.addInitScript(() => { localStorage.setItem("mmapp_token", "header." + btoa(JSON.stringify({ sub: "ui-admin", apps: ["mm"], permissions: ["mm:settings:admin", "mm:servers:read", "mm:network:admin"], exp: 4102444800 })) + ".signature") })
+ const calls: string[] = []
+ await page.route("**/api/**", route => {
+ const path = new URL(route.request().url()).pathname, method = route.request().method()
+ calls.push(method + " " + path)
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,PUT,DELETE,OPTIONS", "access-control-allow-headers": "Authorization,Content-Type" }
+ if (method === "OPTIONS") return route.fulfill({ headers, status: 204 })
+ const json = (body: unknown) => route.fulfill({ headers, json: body })
+ if (path === "/api/auth/config") return json({ required: false })
+ if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [operation] })
+ if (path === "/api/mcp/coverage") return json({ version: 1, routes: [{ method: "POST", path: "/api/geoip/update", status: "pending", operations: [], reason: "Нужен отдельный сервисный адаптер" }] })
+ if (path === "/api/mcp/overview") return fail ? route.fulfill({ headers, status: 503, json: { error: "Аудит временно недоступен" } }) : json({ connections: 1, calls: 7, errors: 1, approvals: 1, running: 0, enabled: true, observedAt: at })
+ if (path === "/api/mcp/connections") return json(method === "POST" ? { connection, token: "test-one-time-secret" } : { connections: [connection] })
+ if (path === "/api/mcp/devices/catalog") return json({ servers: [{ id: 1, name: "CHR lab", host: "192.0.2.1", enabled: true }], resources: [{ id: "bridge", title: "Bridge", read: true, create: true, update: true, delete: true, fields: [{ key: "name", type: "string", requiredOnCreate: true }, { key: "comment", type: "string", requiredOnCreate: false }, { key: "disabled", type: "boolean", requiredOnCreate: false }] }] })
+ if (path === "/api/mcp/devices/1/bridge/plan") return json({ planId: id, state: "awaiting-approval" })
+ if (path === "/api/mcp/devices/1/bridge") return json({ items: [{ ".id": "*A", name: "lab-bridge", comment: "baseline", disabled: "true" }], total: 1, nextOffset: null })
+ if (path.endsWith("/check")) return json({ ok: true, checks: { enabled: true, active: true, protocolHandshake: true }, checkedAt: at, protocolProbe: { status: "passed", elapsedMs: 12, credentialType: "temporary-capabilities-read", capabilitiesRead: "passed", clientCredentialsVerified: false } })
+ if (path.endsWith("/grants")) return json({ grants: [] })
+ if (path === "/api/mcp/routing-profiles/plan") return json({ planId: id, state: "awaiting-approval" })
+ if (path === "/api/mcp/routing-profiles") return json({ profiles: [{ id, connection_id: id, config: { name: "Community WAN", community: "65000:10", family: "ipv6", table: "main" }, state: { pausedReason: "Допуск контроллера истёк" }, enabled: false, grant_expires_at: at }] })
+ if (path === "/api/mcp/protections") return json({ protections: [] })
+ if (path === "/api/mcp/settings") return json({ enabled: true, requestsRetentionDays: 30, auditRetentionDays: 180 })
+ if (path === "/api/mcp/management-channels") return json(method === "POST" ? { id, serverId: 1, expiresAt: at, verification: "identity-and-reachability", independence: "human-attestation" } : { channels: [] })
+ if (path === `/api/mcp/operations/${id}/recover`) return json({ planId: id, state: "awaiting-approval" })
+ if (path === `/api/mcp/operations/${id}/reconcile`) return json({ operationId: id, state: "applied", results: [], automaticRetry: false })
+ if (path === "/api/mcp/oauth/clients") return json({ clients: [] })
+ if (path.startsWith("/api/mcp/")) return json({ items: [], total: 0, nextCursor: null })
+ if (path === "/api/servers") return json([])
+ return json({})
+ })
+ return calls
+}
+
+test("MCP приостанавливает опрос по сигналу скрытия документа и возобновляет при показе", async ({ page }) => {
+ const calls = await setup(page)
+ const overviewCalls = () => calls.filter(call => call === "GET /api/mcp/overview").length
+ await page.clock.install()
+ await page.goto("/mcp?tab=overview")
+ await expect.poll(overviewCalls).toBeGreaterThan(0)
+
+ const setDocumentHidden = (hidden: boolean) => page.evaluate(value => {
+ Object.defineProperty(document, "hidden", { configurable: true, value })
+ document.dispatchEvent(new Event("visibilitychange"))
+ }, hidden)
+
+ await setDocumentHidden(true)
+ await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1_000))
+ const before = overviewCalls()
+ await page.clock.runFor(6_000)
+ expect(overviewCalls()).toBe(before)
+
+ const resumed = page.waitForRequest(request =>
+ request.method() === "GET" && new URL(request.url()).pathname === "/api/mcp/overview",
+ )
+ await setDocumentHidden(false)
+ await resumed
+ await expect.poll(overviewCalls).toBeGreaterThan(before)
+})
+
+test("MCP завершает начатое чтение и ждёт показа вкладки перед следующим опросом", async ({ page }) => {
+ await setup(page)
+ await page.clock.install()
+ let starts = 0
+ let finishFirstRequest!: () => void
+ const firstRequest = new Promise(resolve => { finishFirstRequest = resolve })
+ await page.route("**/api/mcp/overview", async route => {
+ if (route.request().method() !== "GET") return route.fallback()
+ starts++
+ if (starts === 1) await firstRequest
+ return route.fallback()
+ })
+ const setDocumentHidden = (hidden: boolean) => page.evaluate(value => {
+ Object.defineProperty(document, "hidden", { configurable: true, value })
+ document.dispatchEvent(new Event("visibilitychange"))
+ }, hidden)
+
+ try {
+ await page.goto("/mcp?tab=overview")
+ await expect.poll(() => starts).toBe(1)
+ await setDocumentHidden(true)
+ const completed = page.waitForResponse(response => new URL(response.url()).pathname === "/api/mcp/overview" &&
+ response.request().method() === "GET" && response.ok())
+ finishFirstRequest()
+ await completed
+ await page.clock.runFor(11_000)
+ expect(starts).toBe(1)
+
+ await setDocumentHidden(false)
+ await expect.poll(() => starts).toBe(2)
+ } finally {
+ finishFirstRequest()
+ }
+})
+
+test("MCP: медленное чтение завершается без отмены очередным опросом", async ({ page }) => {
+ await setup(page)
+ let calls = 0
+ let release!: () => void
+ const pending = new Promise(resolve => { release = resolve })
+ await page.route("**/api/mcp/overview", async route => {
+ calls++
+ await pending
+ await route.fulfill({ json: { connections: 1, calls: 7, errors: 1, approvals: 1, running: 0, enabled: true, observedAt: at } })
+ })
+ await page.clock.install()
+ await page.goto("/mcp?tab=overview")
+ try {
+ await expect.poll(() => calls).toBeGreaterThan(0)
+ const initialCalls = calls
+ await page.clock.runFor(11_000)
+ expect(calls).toBe(initialCalls)
+ } finally {
+ release()
+ }
+ await expect(page.getByText("MCP включён", { exact: true })).toBeVisible()
+ await page.clock.runFor(5_000)
+ await expect.poll(() => calls).toBeGreaterThan(1)
+})
+
+test("MCP: явное обновление заменяет медленное чтение и сохраняет свежий ответ", async ({ page }) => {
+ await setup(page)
+ let calls = 0
+ let release!: () => void
+ const pending = new Promise(resolve => { release = resolve })
+ await page.route("**/api/mcp/overview", async route => {
+ const current = ++calls
+ if (current === 1) await pending
+ await route.fulfill({ json: { connections: 1, calls: current === 1 ? 7 : 99, errors: 0, approvals: 0, running: 0, enabled: true, observedAt: at } })
+ })
+ await page.clock.install()
+ await page.goto("/mcp?tab=overview")
+ try {
+ await expect.poll(() => calls).toBe(1)
+ await page.evaluate(() => window.dispatchEvent(new Event("mcp-refresh")))
+ await expect.poll(() => calls).toBe(2)
+ await expect(page.getByText("99", { exact: true })).toBeVisible()
+ } finally {
+ release()
+ }
+ await page.clock.runFor(1_000)
+ await expect(page.getByText("99", { exact: true })).toBeVisible()
+ await expect(page.getByText("7", { exact: true })).toHaveCount(0)
+})
+
+test("MCP: зависшее чтение показывает ошибку и повторяется после срока ожидания", async ({ page }) => {
+ await setup(page)
+ let calls = 0
+ let release!: () => void
+ const pending = new Promise(resolve => { release = resolve })
+ await page.route("**/api/mcp/overview", async route => {
+ if (++calls === 1) await pending
+ await route.fulfill({ json: { connections: 1, calls: 7, errors: 0, approvals: 0, running: 0, enabled: true, observedAt: at } })
+ })
+ await page.clock.install()
+ await page.goto("/mcp?tab=overview")
+ try {
+ await expect.poll(() => calls).toBe(1)
+ await page.clock.runFor(60_001)
+ await expect(page.getByRole("alert").filter({ hasText: "Обновление не завершилось за минуту" })).toBeVisible()
+ await page.clock.runFor(5_000)
+ await expect.poll(() => calls).toBeGreaterThan(1)
+ await expect(page.getByText("MCP включён", { exact: true })).toBeVisible()
+ await expect(page.getByRole("alert").filter({ hasText: "Обновление не завершилось за минуту" })).toHaveCount(0)
+ } finally {
+ release()
+ }
+})
+
+test("MCP журнал: заполненная квота объясняет удержание и показывает admin counters",async({page})=>{
+ await setup(page)
+ await page.route("**/api/mcp/overview",route=>route.fulfill({json:{connections:1,calls:7,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:8,limit:8,remaining:0},global:{exhausted:true,usage:{used:128,limit:128,remaining:0}},retentionDays:14}}}))
+ await page.goto("/mcp")
+ const capacity=page.getByRole("region",{name:"Журнал полных опросов"})
+ await expect(capacity.getByText("8 / 8",{exact:false})).toBeVisible()
+ await expect(capacity.getByText("128 / 128",{exact:false})).toBeVisible()
+ await expect(capacity.getByRole("alert")).toContainText("Личная и общая квоты журнала заполнены")
+ await expect(capacity).toContainText("Счётчик учитывает резерв под выполнение и журналы, ожидающие архивирования")
+ await expect(capacity).toContainText("Архив сохраняет все исходные записи и продолжает занимать место")
+ await expect(capacity).toContainText("14 дн.")
+ await capacity.screenshot({path:"test-results/mcp-poll-capacity-full.png"})
+})
+test("MCP журнал: non-admin global usage скрыт, ошибка обновления не сохраняет зелёный статус",async({page})=>{
+ await setup(page)
+ let failed=false
+ await page.route("**/api/mcp/overview",route=>route.fulfill(failed?{status:503,json:{error:"Аудит временно недоступен"}}:{json:{connections:1,calls:0,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:1,limit:8,remaining:7},global:{exhausted:false,usage:null},retentionDays:14}}}))
+ await page.goto("/mcp")
+ const capacity=page.getByRole("region",{name:"Журнал полных опросов"})
+ await expect(capacity).toContainText("Квота не заполнена")
+ await expect(capacity).not.toContainText("128")
+ failed=true;await capacity.getByRole("button",{name:"Обновить статус"}).click()
+ await expect(capacity.getByRole("status")).toContainText("Свободное место не подтверждено")
+ await expect(capacity).not.toContainText("Квота не заполнена")
+})
+test("MCP журнал: на мобильном общая квота блокирует запуск при свободной личной",async({page})=>{
+ await setup(page);await page.setViewportSize({width:390,height:844})
+ await page.route("**/api/mcp/overview",route=>route.fulfill({json:{connections:1,calls:0,errors:0,approvals:0,running:0,enabled:true,observedAt:at,pollStorageCapacity:{status:"observed",owner:{used:1,limit:8,remaining:7},global:{exhausted:true,usage:null},retentionDays:14}}}))
+ await page.goto("/mcp")
+ const capacity=page.getByRole("region",{name:"Журнал полных опросов"})
+ await expect(capacity.getByRole("alert")).toContainText("Общая квота журнала заполнена")
+ await expect(capacity).toContainText("Осталось: 7")
+ expect(await capacity.evaluate(element=>element.scrollWidth<=element.clientWidth)).toBe(true)
+ await capacity.screenshot({path:"test-results/mcp-poll-capacity-mobile.png"})
+})
+const routePathCheckConfig = {
+ name: "Проверка назначения", serverId: 1, community: "65000:10", family: "ipv4", table: "main", probeVrf: "main",
+ candidates: [{ id: "probe", wanInterface: "wan", downstreamInterface: "down", jumpHostId: 2, exitNodeId: 3, gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*r" }, controlProbe: { targetInterface: "exit", expectedHops: [{ serverId: 3, interface: "exit" }] } }],
+}
+
+test("MCP: строки и курсор обращений принадлежат текущей странице и фильтру", async ({ page }) => {
+ await setup(page)
+ const secondCursor = "fa58fa40-4bcb-4616-9316-cb69463b3151"
+ let releaseSecond!: () => void
+ const holdSecond = new Promise(resolve => { releaseSecond = resolve })
+ let failFiltered = true
+ await page.route(url => url.pathname === "/api/mcp/requests", async route => {
+ const params = new URL(route.request().url()).searchParams
+ const filtered = params.get("tool") === "mm_servers_list"
+ const cursor = params.get("cursor")
+ if (cursor === id) await holdSecond
+ if (filtered && failFiltered) return route.fulfill({ status: 503, json: { error: "Обращения временно недоступны" } })
+ const tool = filtered ? "mm_servers_list" : cursor === id ? "mm_logs_follow" : "mm_logs_query"
+ return route.fulfill({ json: { items: [{ id, tool, status: "completed", created_at: at }], total: 1, nextCursor: filtered ? null : cursor === id ? secondCursor : id } })
+ })
+ await page.goto("/mcp?tab=requests")
+ const next = page.getByRole("button", { name: "Далее", exact: true })
+ const first = page.getByText("mm_logs_query", { exact: true })
+ const second = page.getByText("mm_logs_follow", { exact: true })
+ const filtered = page.getByText("mm_servers_list", { exact: true })
+ const staleNotice = page.getByText("показаны ранее полученные данные", { exact: false })
+ const refresh = page.getByRole("button", { name: "Обновить", exact: true })
+ try {
+ await expect(first).toBeVisible()
+ const secondRequest = page.waitForRequest(request => {
+ const url = new URL(request.url())
+ return url.pathname === "/api/mcp/requests" && url.searchParams.get("cursor") === id
+ })
+ await next.click()
+ expect(new URL((await secondRequest).url()).searchParams.get("limit")).toBe("50")
+ await expect(first).toHaveCount(0)
+ await expect(next).toBeDisabled()
+ } finally {
+ releaseSecond()
+ }
+ await expect(second).toBeVisible()
+ await expect(next).toBeEnabled()
+ const filteredRequest = page.waitForRequest(request => {
+ const url = new URL(request.url())
+ return url.pathname === "/api/mcp/requests" && url.searchParams.get("tool") === "mm_servers_list"
+ })
+ await page.getByRole("textbox", { name: "Имя инструмента" }).fill("mm_servers_list")
+ expect(Object.fromEntries(new URL((await filteredRequest).url()).searchParams)).toEqual({ limit: "50", tool: "mm_servers_list" })
+ await expect(page.getByRole("alert").filter({ hasText: "Обращения временно недоступны" })).toBeVisible()
+ await expect(second).toHaveCount(0)
+ await expect(staleNotice).toHaveCount(0)
+ await expect(next).toBeDisabled()
+
+ failFiltered = false
+ await refresh.click()
+ await expect(filtered).toBeVisible()
+ failFiltered = true
+ await refresh.click()
+ await expect(staleNotice).toBeVisible()
+ await expect(filtered).toBeVisible()
+})
+
+test("MCP: аудит передаёт поддерживаемый фильтр пользователя и сбрасывает курсор", async ({ page }) => {
+ await setup(page)
+ const requests: Record[] = []
+ await page.route(url => url.pathname === "/api/mcp/audit", route => {
+ const params = Object.fromEntries(new URL(route.request().url()).searchParams)
+ requests.push(params)
+ return route.fulfill({ json: { items: [{ id: "10", action: params.userId ? "audit-filtered" : "audit-initial", created_at: at }], total: 1, nextCursor: null } })
+ })
+ await page.goto(`/mcp?tab=settings&audit.connectionId=${id}&audit.cursor=11&audit.status=denied&audit.serverId=7`)
+ await expect(page.getByText("audit-initial", { exact: true })).toBeVisible()
+ expect(requests[0]).toEqual({ limit: "50", connectionId: id, cursor: "11" })
+ await expect(page.getByRole("textbox", { name: "Фильтр состояния" })).toHaveCount(0)
+ await expect(page.getByLabel("Фильтр ID сервера")).toHaveCount(0)
+ await page.getByLabel("Фильтр пользователя").fill("ui-admin")
+ await expect(page.getByText("audit-filtered", { exact: true })).toBeVisible()
+ expect(requests.at(-1)).toEqual({ limit: "50", connectionId: id, userId: "ui-admin" })
+ expect(new URL(page.url()).searchParams.has("audit.cursor")).toBe(false)
+})
+
+test("Route AI: самостоятельная проба имеет отдельное назначение и не разрешает Community", async ({ page }) => {
+ await setup(page)
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,OPTIONS", "access-control-allow-headers": "Authorization,Content-Type" }
+ await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ headers, json: { profiles: [{ id, connection_id: id, config: routePathCheckConfig, enabled: false }] } }))
+ await page.route(`**/api/mcp/routing-profiles/${id}/check`, route => {
+ if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
+ return route.fulfill({ headers, json: { proofPurpose: route.request().postDataJSON().proofPurpose, status: "verified", returnPathVerified: false } })
+ })
+ await page.goto("/mcp?tab=routing")
+ await page.getByLabel("Профиль для проверки пути").selectOption(id)
+ await page.getByLabel("Проверяемый путь").selectOption("probe")
+ const purpose = page.getByLabel("Назначение проверки")
+ await expect(purpose).toHaveValue("community")
+ for (const value of ["community", "control-path"] as const) {
+ await purpose.selectOption(value)
+ const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith(`/api/mcp/routing-profiles/${id}/check`))
+ await page.getByRole("button", { name: "Проверить контрольный путь", exact: true }).click()
+ expect((await sent).postDataJSON()).toEqual({ candidateId: "probe", proofPurpose: value })
+ await expect(page.locator("pre[role=status]").filter({ hasText: '"proofPurpose"' })).toContainText(`"${value}"`)
+ }
+ await expect(page.getByText("Результат не разрешает переключение Community", { exact: false })).toBeVisible()
+})
+
+test("Route AI: смена выбора отбрасывает запоздалый результат и ошибку пробы", async ({ page }) => {
+ await setup(page)
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,OPTIONS", "access-control-allow-headers": "Authorization,Content-Type" }
+ const anotherId = "fa58fa40-4bcb-4616-9316-cb69463b3151"
+ const candidate = routePathCheckConfig.candidates[0]
+ const config = { ...routePathCheckConfig, candidates: [candidate, { ...candidate, id: "reserve", wanInterface: "wan-b", gateway: "192.0.2.2", gatewayRef: { resource: "ipv4_route", id: "*s" } }] }
+ await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ headers, json: { profiles: [id, anotherId].map(profileId => ({ id: profileId, config, version: 1, enabled: false })) } }))
+ let requestCount = 0
+ let release: () => void = () => {}
+ await page.route("**/api/mcp/routing-profiles/*/check", async route => {
+ if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
+ const request = ++requestCount
+ if (request < 3) await new Promise(resolve => { release = resolve })
+ return request === 2
+ ? route.fulfill({ status: 502, headers, json: { error: "Старая ошибка пробы" } })
+ : route.fulfill({ headers, json: { marker: request === 1 ? "old-proof" : "current-proof", ...route.request().postDataJSON() } })
+ })
+ await page.goto("/mcp?tab=routing")
+ const profile = page.getByLabel("Профиль для проверки пути")
+ const path = page.getByLabel("Проверяемый путь")
+ const purpose = page.getByLabel("Назначение проверки")
+ const check = page.getByRole("button", { name: "Проверить контрольный путь", exact: true })
+ const start = async (number: number) => {
+ await check.click()
+ await expect.poll(() => requestCount).toBe(number)
+ }
+ await profile.selectOption(id)
+ await path.selectOption("probe")
+ await start(1)
+ await path.selectOption("reserve")
+ await path.selectOption("probe")
+ release()
+ await expect(check).toBeEnabled()
+ await expect(page.getByText("old-proof", { exact: false })).toHaveCount(0)
+
+ await start(2)
+ await profile.selectOption(anotherId)
+ await path.selectOption("reserve")
+ await purpose.selectOption("control-path")
+ release()
+ await expect(check).toBeEnabled()
+ await expect(page.getByText("Старая ошибка пробы", { exact: false })).toHaveCount(0)
+
+ await start(3)
+ const result = page.locator("pre[role=status]").filter({ hasText: "current-proof" })
+ await expect(result).toContainText('"candidateId": "reserve"')
+ await expect(result).toContainText('"proofPurpose": "control-path"')
+})
+
+test("Route AI: автовосстановление блокирует активацию, но позволяет сохранить выключенный профиль", async ({ page }) => {
+ await setup(page)
+ const config = { name: "Профиль восстановления", serverId: 1, community: "65000:10", family: "ipv4", table: "main", probeVrf: "main", autoRecovery: true, candidates: [{ id: "probe", wanInterface: "wan", downstreamInterface: "down", jumpHostId: 2, exitNodeId: 3, gateway: "192.0.2.1", gatewayRef: { resource: "ipv4_route", id: "*r" }, controlProbe: { targetInterface: "exit", expectedHops: [{ serverId: 3, interface: "exit" }] } }] }
+ await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ json: { profiles: [{ id, connection_id: id, config, enabled: true }] } }))
+ await page.goto("/mcp?tab=routing")
+ await page.getByRole("cell", { name: config.name, exact: true }).click()
+ await page.getByRole("button", { name: "Изменить профиль", exact: true }).click()
+ const dialog = page.getByRole("dialog"), save = dialog.getByRole("button", { name: "Подготовить план профиля", exact: true })
+ await expect(dialog.getByRole("status")).toContainText("ROUTE_RECOVERY_EXECUTOR_UNAVAILABLE")
+ await expect(dialog.getByRole("status")).toContainText("подтверждённая непрерывность событий RouterOS")
+ await expect(save).toBeDisabled()
+ await dialog.getByRole("checkbox", { name: "Разрешить работу контроллера после применения плана", exact: true }).uncheck()
+ await expect(save).toBeEnabled()
+ const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/routing-profiles/plan"))
+ await save.click()
+ const input = (await sent).postDataJSON()
+ expect(input.enabled).toBe(false)
+ expect(input.profile.autoRecovery).toBe(true)
+})
+test("MCP: доступ, проверка подключения, выдача токена и состояние Route AI", async ({ page }) => {
+ test.setTimeout(90000)
+ const errors: string[] = []; page.on("pageerror", error => errors.push(error.message))
+ const calls = await setup(page)
+ await page.goto("/mcp")
+ await expect(page.getByRole("heading", { name: "MCP", exact: true })).toBeVisible({ timeout: 60000 })
+ await page.getByRole("tab", { name: "Подключения", exact: true }).click()
+ await expect(page.getByText("Диагностика WAN", { exact: true }).first()).toBeVisible()
+ await page.getByLabel("Подключение для проверки").selectOption(id)
+ await page.getByRole("button", { name: "Проверить готовность доступа" }).click()
+ await expect.poll(() => calls.includes(`POST /api/mcp/connections/${id}/check`)).toBe(true)
+ const readiness = page.locator("pre").filter({ hasText: "protocolProbe" })
+ await expect(readiness).toContainText('"protocolHandshake": true')
+ await expect(readiness).toContainText('"clientCredentialsVerified": false')
+ await expect(page.getByRole("status").filter({ hasText: "Проверочное чтение возможностей прошло." })).toBeVisible()
+ await page.getByRole("button", { name: "Выдать доступ", exact: true }).click()
+ await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент")
+ await page.getByRole("button", { name: "Далее", exact: true }).click()
+ await page.getByLabel("ID разрешённых серверов через запятую").fill("1")
+ await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check()
+ await page.getByRole("button", { name: "Далее", exact: true }).click()
+ await page.getByRole("button", { name: "Далее", exact: true }).click()
+ await page.getByRole("button", { name: "Сохранить доступ", exact: true }).click()
+ await expect(page.getByLabel("Одноразовый токен MCP")).toHaveValue("test-one-time-secret")
+ await page.getByRole("button", { name: "Закрыть и скрыть токен" }).click()
+ await expect(page.getByLabel("Одноразовый токен MCP")).toHaveCount(0)
+ await page.getByRole("tab", { name: "Route AI", exact: true }).click()
+ await expect(page.getByText("Допуск контроллера истёк", { exact: true })).toBeVisible()
+ await page.screenshot({ path: "test-results/mcp-route-ai.png", fullPage: true })
+ expect(errors).toEqual([])
+})
+test("MCP: временные допуски и результаты проверки привязаны к подключению", async ({ page }) => {
+ await setup(page)
+ const otherId = "fa58fa40-4bcb-4616-9316-cb69463b3151"
+ const other = { ...connection, id: otherId, name: "Мониторинг LAN", policy: { ...connection.policy, id: otherId } }
+ let listed = [connection, other]
+ await page.route("**/api/mcp/connections", route => route.fulfill({ json: { connections: listed } }))
+
+ let releaseOtherGrants!: () => void
+ let releaseIssue!: () => void
+ let releaseFirstCheck!: () => void
+ let releaseStaleCheck!: () => void
+ const otherGrants = new Promise(resolve => { releaseOtherGrants = resolve })
+ const issue = new Promise(resolve => { releaseIssue = resolve })
+ const firstCheck = new Promise(resolve => { releaseFirstCheck = resolve })
+ const staleCheck = new Promise(resolve => { releaseStaleCheck = resolve })
+ const grant = (id: string) => ({ id, grant: { expiresAt: at }, revoked_at: null })
+
+ await page.route(`**/api/mcp/connections/${id}/grants`, async route => {
+ if (route.request().method() === "GET") return route.fulfill({ json: { grants: [grant(id)] } })
+ await issue
+ return route.fulfill({ json: { token: "issued-for-wan", expiresAt: at } })
+ })
+ await page.route(`**/api/mcp/connections/${otherId}/grants`, async route => {
+ await otherGrants
+ await route.fulfill({ json: { grants: [grant(otherId)] } })
+ })
+ await page.route("**/api/mcp/grants/*", route => route.fulfill({ json: { ok: true } }))
+ await page.route(`**/api/mcp/connections/${id}/check`, async route => {
+ await firstCheck
+ await route.fulfill({ json: { ok: true, checks: { wan: true }, checkedAt: at } })
+ })
+ let otherChecks = 0
+ await page.route(`**/api/mcp/connections/${otherId}/check`, async route => {
+ const stale = ++otherChecks === 1
+ if (stale) await staleCheck
+ await route.fulfill({ json: { ok: true, checks: stale ? { stale: true } : { lan: true }, checkedAt: at } })
+ })
+
+ await page.goto("/mcp?tab=connections")
+ const selection = page.getByLabel("Подключение для проверки")
+ const revoke = page.getByRole("button", { name: "Отозвать допуск", exact: true })
+ const check = page.getByRole("button", { name: "Проверить готовность доступа", exact: true })
+ const create = page.getByRole("button", { name: "Выдать временный допуск", exact: true })
+ const readiness = page.locator("pre")
+
+ try {
+ await selection.selectOption(id)
+ await expect(revoke).toBeVisible()
+ await Promise.all([page.waitForRequest(`**/api/mcp/connections/${id}/check`), check.click()])
+ await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
+ await Promise.all([
+ page.waitForRequest(request => request.method() === "POST" && request.url().endsWith(`/connections/${id}/grants`)),
+ create.click(),
+ ])
+
+ await Promise.all([page.waitForRequest(`**/api/mcp/connections/${otherId}/grants`), selection.selectOption(otherId)])
+ await expect(revoke).toHaveCount(0)
+ await page.getByRole("checkbox", { name: "logs.query", exact: true }).check()
+ await expect(create).toBeDisabled()
+ releaseOtherGrants()
+ await expect(revoke).toBeVisible()
+ const revoked = page.waitForRequest(request => request.method() === "DELETE" && request.url().includes("/api/mcp/grants/"))
+ await revoke.click()
+ expect(new URL((await revoked).url()).pathname).toBe(`/api/mcp/grants/${otherId}`)
+
+ await Promise.all([page.waitForRequest(`**/api/mcp/connections/${otherId}/check`), check.click()])
+ await check.click()
+ await expect(readiness).toContainText('"lan": true')
+ const lateResponses = Promise.all([
+ page.waitForResponse(`**/api/mcp/connections/${id}/check`),
+ page.waitForResponse(`**/api/mcp/connections/${otherId}/check`),
+ ])
+ releaseFirstCheck()
+ releaseStaleCheck()
+ for (const response of await lateResponses) await response.finished()
+
+ listed = [other]
+ releaseIssue()
+ const dialog = page.getByRole("dialog")
+ await expect(dialog).toContainText(`Подключение «${connection.name}»`)
+ await expect(dialog.getByLabel("Одноразовый токен MCP")).toHaveValue("issued-for-wan")
+ await expect(selection.locator(`option[value="${id}"]`)).toHaveCount(0)
+ await dialog.getByRole("button", { name: "Закрыть и скрыть токен" }).click()
+ await expect(selection).toHaveValue(otherId)
+ await expect(readiness).toContainText('"lan": true')
+ await expect(readiness).not.toContainText('"wan": true')
+ await expect(readiness).not.toContainText('"stale": true')
+ await expect(create).toBeEnabled()
+ } finally {
+ releaseOtherGrants()
+ releaseIssue()
+ releaseFirstCheck()
+ releaseStaleCheck()
+ }
+})
+
+test("MCP: симулятор разрешений использует область операции из каталога", async ({ page }) => {
+ await setup(page)
+ const otherId = "fa58fa40-4bcb-4616-9316-cb69463b3158"
+ const capabilities = { ...operation, id: "capabilities.read", toolName: "mm_capabilities_get", title: "Доступные возможности", scope: "connection", requiredPermissions: [] }
+ const users = { ...operation, id: "users.list", toolName: "mm_users_list", title: "Каталог пользователей", scope: "global", requiredPermissions: ["mm:users:read"] }
+ const ownerPermissions = ["mm:servers:read", "mm:users:read"]
+ const policy = { ...connection.policy, permissions: ownerPermissions, scope: { serverIds: [1, 2], operationIds: [capabilities.id, users.id, operation.id], allowGlobal: true } } as McpPolicyPreviewRequest["policy"]
+ const foreign = { ...connection, ownerId: "other-owner", policy }
+ const other = { ...foreign, id: otherId, name: "Другой доступ", policy: { ...policy, id: otherId } }
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,OPTIONS", "access-control-allow-headers": "Authorization,Content-Type" }
+ await page.route("**/api/mcp/catalog", route => route.fulfill({ headers, json: { stage: "runtime", executionAvailable: true, operations: [operation, capabilities, users] } }))
+ await page.route("**/api/mcp/connections", route => route.fulfill({ headers, json: { connections: [foreign, other] } }))
+ const previews: unknown[] = [], protections: unknown[] = []
+ let releaseStale!: () => void
+ const stale = new Promise(resolve => { releaseStale = resolve })
+ await page.route("**/api/mcp/policy/preview", async route => {
+ if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
+ const input = route.request().postDataJSON() as Pick
+ previews.push(input)
+ if (input.target.scope === "servers" && input.target.serverIds.includes(3)) await stale
+ const result = evaluateMcpPolicy({ operationId: input.operationId, target: input.target, policy, ownerPermissions, objects: [], protections: [], objectCount: 0, usage: { callsInMinute: 0, concurrentReads: 0, mutationsInHour: 0 }, auditAvailable: true })
+ await route.fulfill({ headers, json: { simulation: true, executionAvailable: false, evaluatedAt: at, policyVersion: 1, result } })
+ })
+ await page.route("**/api/mcp/protections", route => {
+ if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
+ if (route.request().method() === "POST") { protections.push(route.request().postDataJSON()); return route.fulfill({ headers, json: { id } }) }
+ return route.fulfill({ headers, json: { protections: [] } })
+ })
+
+ try {
+ await page.goto("/mcp?tab=permissions")
+ const selectConnection = page.getByLabel("Подключение", { exact: true })
+ const selectOperation = page.getByLabel("Операция", { exact: true })
+ const serverIds = page.getByLabel("ID серверов", { exact: true })
+ const preview = page.getByRole("button", { name: "Проверить", exact: true })
+ const allowed = page.getByText("Разрешено", { exact: true })
+ await selectConnection.selectOption(id)
+ await selectOperation.selectOption(capabilities.id)
+ await expect(page.getByText("Область операции — подключение")).toBeVisible()
+ await expect(serverIds).toHaveCount(0)
+ await preview.click()
+ await expect(allowed).toBeVisible()
+ expect(previews[0]).toEqual({ connectionId: id, operationId: capabilities.id, target: { scope: "connection" } })
+
+ await selectOperation.selectOption(operation.id)
+ await expect(allowed).toHaveCount(0)
+ await expect(preview).toBeDisabled()
+ await serverIds.fill("1,1")
+ await expect(preview).toBeDisabled()
+ await serverIds.fill("2, 1")
+ await preview.click()
+ await expect(allowed).toBeVisible()
+ expect(previews[1]).toEqual({ connectionId: id, operationId: operation.id, target: { scope: "servers", serverIds: [2, 1] } })
+
+ await serverIds.fill("1, 3")
+ await expect(allowed).toHaveCount(0)
+ await preview.click()
+ await expect.poll(() => previews.length).toBe(3)
+ await selectOperation.selectOption(users.id)
+ await expect(page.getByText("Область операции — всё приложение")).toBeVisible()
+ await expect(serverIds).toHaveCount(0)
+ await preview.click()
+ await expect(allowed).toBeVisible()
+ expect(previews[3]).toEqual({ connectionId: id, operationId: users.id, target: { scope: "global" } })
+ const late = page.waitForResponse(response => response.url().endsWith("/api/mcp/policy/preview") && response.request().postDataJSON().target.scope === "servers")
+ releaseStale()
+ await (await late).finished()
+ await expect(allowed).toBeVisible()
+ await expect(page.getByText("Запрещено", { exact: true })).toHaveCount(0)
+
+ await selectConnection.selectOption(otherId)
+ await expect(selectOperation).toHaveValue("")
+ await expect(allowed).toHaveCount(0)
+ await expect(preview).toBeDisabled()
+
+ await page.getByLabel("Тип объекта", { exact: true }).fill("ethernet")
+ await page.getByLabel("Стабильный ID", { exact: true }).fill("*A")
+ const protect = page.getByRole("button", { name: "Добавить защиту" })
+ await expect(protect).toBeDisabled()
+ await page.getByLabel("ID сервера защищаемого объекта").fill("9")
+ await protect.click()
+ await expect.poll(() => protections).toEqual([{ object: { kind: "ethernet", id: "*A", protection: "human-approval-required", serverId: 9 }, reason: "" }])
+ } finally { releaseStale() }
+})
+test("MCP: ошибки остаются видимыми, узкий экран не переполняется", async ({ page }) => {
+ await setup(page, true)
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.goto("/mcp")
+ await expect(page.getByRole("alert").filter({ hasText: "Аудит временно недоступен" })).toBeVisible()
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true)
+})
+test("Route AI: редактор создаёт план с конкретными путями и SLA", async ({ page }) => {
+ const calls = await setup(page)
+ await page.goto("/mcp?tab=routing")
+ await page.getByRole("button", { name: "Создать профиль", exact: true }).click()
+ await page.getByLabel("Подключение контроллера").selectOption(id)
+ await page.getByLabel("Название профиля").fill("WAN Community")
+ await page.getByLabel("ID домашнего сервера").fill("1")
+ await page.getByLabel("Community", { exact: true }).fill("65000:20")
+ await page.getByLabel("Таблица маршрутизации", { exact: true }).fill("customer-routes")
+ await page.getByLabel("VRF диагностических проб", { exact: true }).fill("probe-only")
+ await page.getByRole("checkbox", { name: "Привязать профиль к конкретному BGP-подключению RouterOS", exact: true }).check()
+ await page.getByLabel("ID BGP-подключения RouterOS", { exact: true }).fill("*A")
+ await page.getByLabel("Экземпляр BGP", { exact: true }).fill("edge-instance")
+ await page.getByLabel("Входящая цепочка BGP", { exact: true }).fill("customer-in")
+ await page.getByLabel("Транспортная VRF BGP", { exact: true }).fill("bgp-transport")
+ await expect(page.getByRole("status").filter({ hasText: "контрольную пробу с исходным адресом" })).toContainText("Профиль можно сохранить")
+ await page.getByRole("checkbox", { name: "Разрешить работу контроллера после применения плана", exact: true }).check()
+ await expect(page.getByRole("button", { name: "Подготовить план профиля", exact: true })).toBeDisabled()
+ await page.getByLabel("WAN-интерфейс дома").fill("ether1")
+ await page.getByLabel("ID JumpHost").fill("2")
+ await page.getByLabel("ID ExitNode").fill("3")
+ await page.getByLabel("Интерфейс JumpHost к ExitNode").fill("gre1")
+ await page.getByLabel("Адрес gateway").fill("192.0.2.1")
+ await page.getByLabel("ID шлюза на устройстве").fill("*1")
+ await page.getByLabel("Максимум RTT, мс").fill("80")
+ await page.getByRole("checkbox", { name: "Включить контроль пути 1", exact: true }).check()
+ await page.getByLabel("Контрольный интерфейс ExitNode пути 1").fill("loopback")
+ await page.getByLabel("Исходный IP контрольной пробы пути 1").fill("192.0.2.10")
+ await page.getByLabel("Интерфейс hop 1 пути 1").fill("wan-in")
+ await page.getByLabel("Интерфейс hop 2 пути 1").fill("loopback")
+ await page.screenshot({ path: "test-results/mcp-route-profile-editor.png", fullPage: true })
+ const sent = page.waitForRequest(request => request.method() === "POST" && request.url().includes("/api/mcp/routing-profiles/plan"))
+ await page.getByRole("button", { name: "Подготовить план профиля" }).click()
+ const body = (await sent).postDataJSON()
+ expect(body.profile.candidates[0].jumpHostId).toBe(2)
+ expect(body.profile.maxPingMs).toBe(80)
+ expect(body.profile.table).toBe("customer-routes")
+ expect(body.profile.probeVrf).toBe("probe-only")
+ expect(body.profile.bgpContext).toEqual({ connectionId: "*A", instance: "edge-instance", inputChain: "customer-in", vrf: "bgp-transport" })
+ expect(body.profile.candidates[0].controlProbe).toEqual({ targetInterface: "loopback", sourceAddress: "192.0.2.10", expectedHops: [{ serverId: 2, interface: "wan-in" }, { serverId: 3, interface: "loopback" }] })
+ expect(body.enabled).toBe(true)
+ await expect(page.getByText(/Создан план/)).toBeVisible()
+ expect(calls).toContain("POST /api/mcp/routing-profiles/plan")
+})
+test("Route AI: редактирование сохраняет контексты и скрытые настройки профиля", async ({ page }) => {
+ await setup(page)
+ const config = {
+ name: "Scoped community", serverId: 1, community: "65000:20", family: "ipv4", table: "customer-routes", probeVrf: "probe-only",
+ bgpContext: { connectionId: "*B", instance: "edge-instance", inputChain: "customer-in", vrf: "bgp-transport" },
+ pingFreshnessSec: 180, bandwidthFreshnessSec: 7200, hysteresis: 12, confirmationSamples: 4, maxSwitchesPerHour: 2,
+ candidates: [{ id: "edge", wanInterface: "ether1", jumpHostId: 2, exitNodeId: 3, downstreamInterface: "gre1", gateway: "192.0.2.1", gatewayRef: { resource: "gre", id: "*1" }, wanRemoteInterface: "wan-in" }],
+ }
+ await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ json: { profiles: [{ id, connection_id: id, config, enabled: true }] } }))
+ await page.goto("/mcp?tab=routing")
+ await page.getByRole("cell", { name: config.name, exact: true }).click()
+ await page.getByRole("button", { name: "Изменить профиль", exact: true }).click()
+ const enableController = page.getByRole("checkbox", { name: "Разрешить работу контроллера после применения плана", exact: true })
+ await expect(enableController).toBeChecked()
+ await expect(page.getByRole("button", { name: "Подготовить план профиля", exact: true })).toBeDisabled()
+ await enableController.uncheck()
+ await expect(page.getByLabel("VRF диагностических проб", { exact: true })).toHaveValue("probe-only")
+ await expect(page.getByLabel("Транспортная VRF BGP", { exact: true })).toHaveValue("bgp-transport")
+ await page.getByLabel("Название профиля", { exact: true }).fill("Renamed community")
+ const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/routing-profiles/plan"))
+ await page.getByRole("button", { name: "Подготовить план профиля", exact: true }).click()
+ const body = (await sent).postDataJSON()
+ expect(body.profileId).toBe(id)
+ expect(body.profile).toMatchObject({ ...config, name: "Renamed community" })
+ expect(body.enabled).toBe(false)
+})
+
+test("Route AI: неполная BGP-привязка не отправляется, снятие привязки явно удаляет контекст", async ({ page }) => {
+ const calls = await setup(page)
+ const config = { name: "BGP scope", serverId: 1, community: "65000:20", family: "ipv4", table: "main", probeVrf: "main", bgpContext: { connectionId: "*B", instance: "edge-instance", inputChain: "bgp-in", vrf: "main" }, candidates: [{ id: "edge", wanInterface: "ether1", jumpHostId: 2, exitNodeId: 3, downstreamInterface: "gre1", gateway: "192.0.2.1", gatewayRef: { resource: "gre", id: "*1" } }] }
+ await page.route("**/api/mcp/routing-profiles", route => route.fulfill({ json: { profiles: [{ id, connection_id: id, config, enabled: false }] } }))
+ await page.goto("/mcp?tab=routing")
+ await page.getByRole("cell", { name: config.name, exact: true }).click()
+ await page.getByRole("button", { name: "Изменить профиль", exact: true }).click()
+ await page.getByLabel("Экземпляр BGP", { exact: true }).fill("")
+ await page.getByRole("button", { name: "Подготовить план профиля", exact: true }).click()
+ await expect(page.getByRole("dialog").getByRole("alert")).toBeVisible()
+ expect(calls.filter(call => call === "POST /api/mcp/routing-profiles/plan")).toHaveLength(0)
+ await page.getByRole("checkbox", { name: "Привязать профиль к конкретному BGP-подключению RouterOS", exact: true }).uncheck()
+ const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/routing-profiles/plan"))
+ await page.getByRole("button", { name: "Подготовить план профиля", exact: true }).click()
+ const body = (await sent).postDataJSON()
+ expect(body.profile).not.toHaveProperty("bgpContext")
+ expect(body.profile.probeVrf).toBe("main")
+ expect(body.enabled).toBe(false)
+})
+
+test("MCP: независимое управление скрывает пароль после регистрации", async ({ page }) => {
+ await setup(page)
+ await page.goto("/mcp?tab=settings")
+ await expect(page.getByText("/api/geoip/update", { exact: true })).toBeVisible()
+ await expect(page.getByText("Ожидают реализации: 1", { exact: true })).toBeVisible()
+ await page.getByLabel("ID сервера независимого канала").fill("1")
+ await page.getByLabel("IP независимого управления").fill("192.0.2.25")
+ await page.getByLabel("Пользователь независимого канала").fill("lab")
+ await page.getByLabel("Пароль независимого канала").fill("fixture-no-real-secret")
+ await page.getByLabel("Подтверждение независимости пути").fill("Отдельный management-интерфейс и отдельная сеть лабораторного стенда")
+ const request = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/management-channels"))
+ await page.getByRole("button", { name: "Проверить и зарегистрировать канал" }).click()
+ expect((await request).postDataJSON().verifySsl).toBe(true)
+ await expect(page.getByLabel("Пароль независимого канала")).toHaveValue("")
+})
+test("MCP: восстановление создаёт отдельный план без автоматического применения", async ({ page }) => {
+ const calls = await setup(page)
+ const maliciousTarget = "../plans/another/apply"
+ await page.goto(`/mcp?${new URLSearchParams({ tab: "plans", reconcile: maliciousTarget })}`)
+ await expect(page.getByLabel("ID исходной операции")).toHaveValue(maliciousTarget)
+ await expect(page.getByRole("button", { name: "Сверить состояние операции" })).toBeDisabled()
+ await expect(page.getByRole("button", { name: "Подготовить обратный план" })).toBeDisabled()
+ await page.getByLabel("ID исходной операции").fill(id)
+ await page.getByRole("button", { name: "Подготовить обратный план" }).click()
+ await expect(page.getByRole("status").filter({ hasText: "awaiting-approval" })).toBeVisible()
+ expect(calls.filter(call => call.endsWith("/apply"))).toEqual([])
+})
+test("MCP: фильтры обращений сохраняются в URL и применяются сервером", async ({ page }) => {
+ await setup(page)
+ await page.goto("/mcp?tab=requests&requests.tool=mm_logs_query&requests.serverId=1")
+ await expect(page.getByLabel("Имя инструмента")).toHaveValue("mm_logs_query")
+ await expect(page.getByLabel("Фильтр ID сервера")).toHaveValue("1")
+ const filtered = page.waitForRequest(request => { const url = new URL(request.url()); return url.pathname === "/api/mcp/requests" && url.searchParams.get("userId") === "ui-admin" && url.searchParams.get("serverId") === "1" && url.searchParams.get("tool") === "mm_logs_query" })
+ await page.getByLabel("Фильтр пользователя").fill("ui-admin")
+ await filtered
+ expect(new URL(page.url()).searchParams.get("requests.userId")).toBe("ui-admin")
+ await page.reload()
+ await expect(page.getByLabel("Фильтр пользователя")).toHaveValue("ui-admin")
+})
+
+test("MCP: файл операции скачивается с JWT, безопасным путём и освобождением Blob URL", async ({ page }) => {
+ await setup(page)
+ const artifactPath = `/api/mcp/artifacts/${id}`
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "Authorization,Content-Type", "access-control-expose-headers": "Content-Disposition" }
+ let downloads = 0
+ await page.addInitScript(() => {
+ const original = URL.revokeObjectURL
+ Object.assign(window, { artifactUrlRevoked: false })
+ URL.revokeObjectURL = url => { Object.assign(window, { artifactUrlRevoked: true }); original(url) }
+ })
+ await page.route("**/api/mcp/operations?*", route => route.fulfill({ headers, json: { items: [{ id, connection_id: id, state: "applied", artifactReceipts: [
+ { artifactId: id, humanDownloadOnly: true, downloadPath: artifactPath },
+ { artifactId: id, humanDownloadOnly: true, downloadPath: "https://unsafe.example/private" },
+ { artifactId: "../unsafe", humanDownloadOnly: true },
+ ] }], total: 1, nextCursor: null } }))
+ await page.route(`**${artifactPath}`, async route => {
+ if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
+ downloads++
+ expect(route.request().headers().authorization).toMatch(/^Bearer header\./)
+ await new Promise(resolve => setTimeout(resolve, 250))
+ return route.fulfill({ body: Buffer.from([0, 255, 128, 1]), headers: { ...headers, "content-type": "application/octet-stream", "content-disposition": 'attachment; filename="backup.rsc"' } })
+ })
+ await page.goto("/mcp?tab=plans")
+ const operations = page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) })
+ await operations.getByRole("button", { name: "Открыть", exact: true }).click()
+ const dialog = page.getByRole("dialog")
+ await expect(dialog.getByRole("heading", { name: "Детали операции", exact: true })).toBeVisible()
+ await expect(dialog.getByRole("button", { name: "Скачать файл", exact: true })).toHaveCount(1)
+ const downloaded = page.waitForEvent("download")
+ await dialog.getByRole("button", { name: "Скачать файл", exact: true }).click()
+ await expect(dialog.getByRole("button", { name: "Скачивание…", exact: true })).toBeDisabled()
+ expect((await downloaded).suggestedFilename()).toBe("backup.rsc")
+ await expect(dialog.getByRole("status")).toContainText("Файл передан браузеру")
+ await expect.poll(() => page.evaluate(() => Reflect.get(window, "artifactUrlRevoked"))).toBe(true)
+ expect(downloads).toBe(1)
+ expect(new URL(page.url()).pathname).toBe("/mcp")
+})
+
+test("MCP: квитанция backup БД скачивает dump через общий путь артефактов", async ({ page }) => {
+ await setup(page)
+ const artifactPath = `/api/mcp/artifacts/${id}`
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "Authorization,Content-Type", "access-control-expose-headers": "Content-Disposition" }
+ await page.route("**/api/mcp/operations?*", route => route.fulfill({ json: { items: [{ id, connection_id: id, operationId: "database.backup", state: "applied", databaseContentReturned: false, artifactReceipts: [{ artifactId: id, humanDownloadOnly: true, downloadPath: artifactPath }] }], total: 1, nextCursor: null } }))
+ await page.route(`**${artifactPath}`, route => {
+ if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers })
+ return route.fulfill({ body: Buffer.from("PGDMPfixture"), headers: { ...headers, "content-type": "application/octet-stream", "content-disposition": 'attachment; filename="mmapp-database.dump"' } })
+ })
+ await page.goto("/mcp?tab=plans")
+ await page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) }).getByRole("button", { name: "Открыть", exact: true }).click()
+ const dialog = page.getByRole("dialog")
+ await expect(dialog).toContainText('"databaseContentReturned": false')
+ const downloaded = page.waitForEvent("download")
+ await dialog.getByRole("button", { name: "Скачать файл", exact: true }).click()
+ expect((await downloaded).suggestedFilename()).toBe("mmapp-database.dump")
+ await expect(dialog.getByRole("status")).toContainText("Файл передан браузеру")
+})
+
+test("MCP: ошибки файла скрывают тело ответа; без JWT скачивание не начинается", async ({ page }) => {
+ await setup(page)
+ let status = 403, requests = 0, downloads = 0
+ page.on("download", () => { downloads++ })
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "Authorization,Content-Type" }
+ await page.route("**/api/mcp/operations?*", route => route.fulfill({ headers, json: { items: [{ id, connection_id: id, state: "applied", artifactReceipts: [{ artifactId: id, humanDownloadOnly: true }] }], total: 1, nextCursor: null } }))
+ await page.route(`**/api/mcp/artifacts/${id}`, route => { if (route.request().method() === "OPTIONS") return route.fulfill({ status: 204, headers }); requests++; return route.fulfill({ status, headers, json: { error: "NEVER_RENDER_PROVIDER_SECRET" } }) })
+ await page.goto("/mcp?tab=plans")
+ await page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) }).getByRole("button", { name: "Открыть", exact: true }).click()
+ const dialog = page.getByRole("dialog"), button = dialog.getByRole("button", { name: "Скачать файл", exact: true })
+ await expect(dialog.getByRole("status")).toHaveText("Доступ и срок хранения проверяются при скачивании.")
+ for (const [code, message] of [[403, "Доступ к файлу отозван"], [404, "срок хранения истёк"], [409, "Файл изменился"], [410, "срок хранения истёк"]] as const) {
+ status = code
+ await button.click()
+ await expect(dialog.getByRole("alert")).toContainText(message)
+ await expect(dialog.getByRole("status")).toBeEmpty()
+ await expect(dialog).not.toContainText("NEVER_RENDER_PROVIDER_SECRET")
+ await expect(button).toBeEnabled()
+ }
+ await page.evaluate(() => localStorage.removeItem("mmapp_token"))
+ await button.click()
+ await expect(dialog.getByRole("alert")).toContainText("Войдите в портал")
+ await expect(dialog.getByRole("status")).toBeEmpty()
+ expect(requests).toBe(4)
+ expect(downloads).toBe(0)
+})
+
+test("MCP: выгрузка проверяет SHA-256 и показывает исчезновение квитанции", async ({ page }) => {
+ const calls = await setup(page)
+ const payload = Buffer.from("PGDMP")
+ const artifactPath = `/api/mcp/artifacts/${id}`
+ const receipt = { artifactId: id, humanDownloadOnly: true, bytes: payload.length, sha256: createHash("sha256").update(payload).digest("hex") }
+ const headers = { "access-control-allow-origin": "*", "access-control-allow-headers": "Authorization,Content-Type" }
+ let visible = true, payloadMatches = false, downloadCount = 0
+ page.on("download", () => { downloadCount++ })
+ await page.route("**/api/mcp/operations?*", route => route.fulfill({ json: {
+ items: [{ id, connection_id: id, state: "applied", artifactReceipts: visible ? [receipt] : [] }], total: 1, nextCursor: null,
+ } }))
+ await page.route(`**${artifactPath}`, route => route.request().method() === "OPTIONS" ? route.fulfill({ status: 204, headers }) :
+ route.fulfill({ headers, body: payloadMatches ? payload : Buffer.from("OTHER") }))
+ await page.goto(`/mcp?tab=plans&operation=${id}`)
+ const dialog = page.getByRole("dialog")
+ const save = dialog.getByRole("button", { name: "Скачать файл", exact: true })
+ await save.click()
+ await expect(dialog.getByRole("alert")).toContainText("Файл изменился")
+ expect(downloadCount).toBe(0)
+
+ payloadMatches = true
+ const downloaded = page.waitForEvent("download")
+ await save.click()
+ await downloaded
+ expect(downloadCount).toBe(1)
+ visible = false
+ await dialog.getByRole("button", { name: "Обновить выполнение" }).click()
+ await expect(dialog.getByRole("status")).toContainText("Файл больше недоступен")
+ await expect(save).toHaveCount(0)
+ expect(calls.filter(call => call.startsWith("POST") && call.endsWith("/apply"))).toEqual([])
+})
+
+test("MCP: изменение интерфейса готовит план только с изменёнными свойствами", async ({ page }) => {
+ await setup(page)
+ await page.goto("/mcp?tab=devices")
+ await page.getByLabel("Подключение для управления интерфейсами").selectOption(id)
+ await page.getByLabel("Сервер интерфейсов").selectOption("1")
+ await page.getByLabel("Тип объектов устройства").selectOption("bridge")
+ await page.getByText("lab-bridge", { exact: true }).click()
+ await page.getByRole("textbox", { name: "comment", exact: true }).fill("reviewed change")
+ const sent = page.waitForRequest(request => request.method() === "POST" && request.url().includes("/api/mcp/devices/1/bridge/plan"))
+ await page.getByRole("button", { name: "Подготовить план изменения", exact: true }).click()
+ expect((await sent).postDataJSON()).toEqual({ connectionId: id, action: "update", id: "*A", fields: { comment: "reviewed change" } })
+ await expect(page.getByRole("status").filter({ hasText: "Создан план" })).toBeVisible()
+ await page.screenshot({ path: "test-results/mcp-device-editor.png", fullPage: true })
+})
+
+test("MCP: можно добавить первый комментарий интерфейса без подстановки остальных свойств", async ({ page }) => {
+ await setup(page)
+ await page.route("**/api/mcp/devices/1/bridge?*", route => route.fulfill({ json: {
+ items: [{ ".id": "*A", name: "lab-bridge", disabled: "true" }], total: 1, nextOffset: null,
+ } }))
+ await page.goto("/mcp?tab=devices")
+ await page.getByLabel("Подключение для управления интерфейсами").selectOption(id)
+ await page.getByLabel("Сервер интерфейсов").selectOption("1")
+ await page.getByLabel("Тип объектов устройства").selectOption("bridge")
+ await page.getByText("lab-bridge", { exact: true }).click()
+ await page.getByRole("textbox", { name: "comment", exact: true }).fill("first comment")
+ const sent = page.waitForRequest(request => request.method() === "POST" && request.url().includes("/api/mcp/devices/1/bridge/plan"))
+ await page.getByRole("button", { name: "Подготовить план изменения", exact: true }).click()
+ expect((await sent).postDataJSON()).toEqual({ connectionId: id, action: "update", id: "*A", fields: { comment: "first comment" } })
+ await expect(page.getByRole("status").filter({ hasText: "Создан план" })).toBeVisible()
+})
+
+test("MCP: Ethernet допускает явное изменение неизвестного disabled", async ({ page }) => {
+ await setup(page)
+ await page.route("**/api/mcp/devices/catalog?*", route => route.fulfill({ json: {
+ servers: [{ id: 1, name: "CHR lab", host: "192.0.2.1", enabled: true }],
+ resources: [{ id: "ethernet", title: "Ethernet", read: true, create: false, update: true, delete: false, fields: [
+ { key: "name", type: "string", requiredOnCreate: false },
+ { key: "disabled", type: "boolean", requiredOnCreate: false },
+ { key: "auto-negotiation", type: "boolean", requiredOnCreate: false },
+ ] }],
+ } }))
+ await page.route("**/api/mcp/devices/1/ethernet?*", route => route.fulfill({ json: {
+ items: [{ ".id": "*E", name: "lab-ethernet", running: "true" }], total: 1, nextOffset: null,
+ } }))
+ await page.route("**/api/mcp/devices/1/ethernet/plan", route => route.fulfill({ json: { planId: id, state: "awaiting-approval" } }))
+ await page.goto("/mcp?tab=devices")
+ await page.getByLabel("Подключение для управления интерфейсами").selectOption(id)
+ await page.getByLabel("Сервер интерфейсов").selectOption("1")
+ await page.getByLabel("Тип объектов устройства").selectOption("ethernet")
+ await page.getByText("lab-ethernet", { exact: true }).click()
+
+ const disabled = page.getByRole("combobox", { name: "disabled", exact: true })
+ const prepare = page.getByRole("button", { name: "Подготовить план изменения", exact: true })
+ const warning = page.getByText("Исходное состояние неизвестно. Для этого изменения обратный план недоступен.")
+ await expect(disabled.locator("option:checked")).toHaveText("Текущее значение неизвестно")
+ await expect(disabled).toHaveValue("")
+ await expect(prepare).toBeDisabled()
+ await expect(page.getByRole("combobox", { name: "auto-negotiation", exact: true })).toHaveCount(0)
+ await disabled.selectOption("false")
+ await expect(prepare).toBeEnabled()
+ await expect(warning).toBeVisible()
+ await disabled.selectOption("")
+ await expect(prepare).toBeDisabled()
+ await expect(warning).toHaveCount(0)
+ await disabled.selectOption("true")
+ const sent = page.waitForRequest(request => request.method() === "POST" && request.url().endsWith("/api/mcp/devices/1/ethernet/plan"))
+ await prepare.click()
+ expect((await sent).postDataJSON()).toEqual({ connectionId: id, action: "update", id: "*E", fields: { disabled: true } })
+ await expect(page.getByRole("status").filter({ hasText: "Создан план" })).toBeVisible()
+})
+
+test("MCP: архив БД загружает человек, подготовка плана не запускает restore", async ({ page }) => {
+ const calls = await setup(page)
+ await page.route("**/api/mcp/connections", route => route.fulfill({ json: { connections: [{ ...connection, policy: { ...connection.policy, permissions: ["mm:settings:admin"], scope: { serverIds: [1], operationIds: ["database.restore"], allowGlobal: true } } }] } }))
+ await page.route("**/api/mcp/database/**", route => {
+ calls.push(route.request().method() + " " + new URL(route.request().url()).pathname)
+ if (route.request().url().endsWith("/archives")) return route.fulfill({ json: { archiveRef: id, sha256: "a".repeat(64), sizeBytes: 12, expiresAt: "2099-01-01T00:00:00Z" } })
+ if (route.request().url().endsWith("/plan")) return route.fulfill({ json: { planId: id, state: "awaiting-approval" } })
+ return route.fulfill({ json: { operationId: id, state: "applied", accessRevoked: true, automaticRetry: false } })
+ })
+ await page.goto("/mcp?tab=settings")
+ await page.getByLabel("Подключение для восстановления").selectOption(id)
+ await page.getByLabel("Архив PostgreSQL, до 64 МиБ").setInputFiles({ name: "test.dump", mimeType: "application/octet-stream", buffer: Buffer.from("PGDMPfixture") })
+ const uploaded = page.waitForRequest(request => request.url().endsWith("/api/mcp/database/archives"))
+ await page.getByRole("button", { name: "Загрузить архив", exact: true }).click()
+ expect((await uploaded).headers()["content-type"]).toBe("application/octet-stream")
+ await expect(page.getByRole("button", { name: "Подготовить план восстановления БД" })).toBeEnabled()
+ const plan = page.waitForRequest(request => request.url().endsWith("/api/mcp/database/plan"))
+ await page.getByRole("button", { name: "Подготовить план восстановления БД" }).click()
+ expect((await plan).postDataJSON()).toEqual({ connectionId: id, archiveRef: id, expectedSha256: "a".repeat(64) })
+ await expect(page.getByRole("status").filter({ hasText: "awaiting-approval" })).toBeVisible()
+ expect(calls.some(call => call.endsWith("/apply"))).toBe(false)
+ await page.getByLabel("ID операции восстановления БД").fill(id)
+ await page.getByRole("button", { name: "Прочитать внешнюю квитанцию" }).click()
+ await expect(page.getByRole("status").filter({ hasText: '"accessRevoked": true' })).toBeVisible()
+})
+
+test("MCP: архив восстановления привязан к выбранному файлу и блокируется по истечении срока", async ({ page }) => {
+ const calls = await setup(page)
+ const start = new Date("2026-11-15T03:00:00Z")
+ await page.clock.install({ time: start })
+ const secondId = "fa58fa40-4bcb-4616-9316-cb69463b3158"
+ const otherId = "fa58fa40-4bcb-4616-9316-cb69463b3159"
+ const policy = { ...connection.policy, permissions: ["mm:settings:admin"], scope: { serverIds: [], operationIds: ["database.restore"], allowGlobal: true } }
+ await page.route("**/api/mcp/connections", route => route.fulfill({ json: { connections: [
+ { ...connection, policy }, { ...connection, id: secondId, policy: { ...policy, id: secondId }, name: "Резервный допуск" },
+ { ...connection, id: otherId, policy: { ...policy, id: otherId }, ownerId: "other", name: "Чужой допуск" },
+ ] } }))
+ let releaseUpload!: () => void
+ const heldUpload = new Promise(resolve => { releaseUpload = resolve })
+ const plans: unknown[] = []
+ let uploads = 0
+ await page.route("**/api/mcp/database/archives", async route => {
+ const first = ++uploads === 1
+ if (first) await heldUpload
+ await route.fulfill({ json: { archiveRef: id, sha256: "a".repeat(64), sizeBytes: first ? 999 : 5, expiresAt: new Date(start.getTime() + 60_000).toISOString() } })
+ })
+ await page.route("**/api/mcp/database/plan", route => {
+ plans.push(route.request().postDataJSON())
+ return route.fulfill({ json: { planId: id, state: "awaiting-approval" } })
+ })
+ await page.goto("/mcp?tab=settings")
+ const section = page.getByRole("region", { name: "Восстановление БД через MCP" })
+ const selector = section.getByLabel("Подключение для восстановления")
+ const file = section.getByLabel("Архив PostgreSQL, до 64 МиБ")
+ const upload = section.getByRole("button", { name: "Загрузить архив" })
+ const prepare = section.getByRole("button", { name: "Подготовить план восстановления БД" })
+ await selector.selectOption(id)
+ await expect(selector.getByRole("option", { name: "Чужой допуск" })).toHaveCount(0)
+ await file.setInputFiles({ name: "first.dump", mimeType: "application/octet-stream", buffer: Buffer.from("PGDMP") })
+ try {
+ await upload.click()
+ await expect(selector).toBeDisabled()
+ await expect(file).toBeDisabled()
+ await expect(prepare).toBeDisabled()
+ } finally { releaseUpload() }
+ await expect(section.getByRole("alert")).toContainText("Размер загруженного архива не совпадает")
+ await expect(prepare).toBeDisabled()
+
+ await file.setInputFiles({ name: "another.dump", mimeType: "application/octet-stream", buffer: Buffer.from("PGDMP") })
+ await upload.click()
+ await expect(prepare).toBeEnabled()
+ await prepare.click()
+ await expect(section.getByRole("status")).toContainText("awaiting-approval")
+ await selector.selectOption(secondId)
+ await expect(section.getByRole("status")).toHaveCount(0)
+ await expect(prepare).toBeEnabled()
+ await page.clock.fastForward(61_000)
+ await expect(section.getByRole("status")).toContainText("Срок архива истёк")
+ await expect(prepare).toBeDisabled()
+ expect(plans).toEqual([{ connectionId: id, archiveRef: id, expectedSha256: "a".repeat(64) }])
+ expect(uploads).toBe(2)
+ expect(calls.filter(call => call.startsWith("POST") && call.endsWith("/apply"))).toEqual([])
+})
+
+test("MCP: обзор плана показывает исходное состояние, зависимости и шаги до подтверждения", async ({ page }) => {
+ await setup(page)
+ await page.route(url => url.pathname === "/api/mcp/plans", route => route.fulfill({ json: { items: [{ id, operationId: "routing.community.switch", state: "awaiting-approval", createdAt: at, expiresAt: "2099-01-01T00:00:00Z", changes: { target: { scope: "servers", serverIds: [1, 2] }, objects: [{ kind: "gre", id: "*A", serverId: 1 }], before: { gateway: "192.0.2.1" }, steps: [{ kind: "service", service: "routing.community", input: { gateway: "192.0.2.2" } }], warnings: ["Изменится gateway выбранного Community"] } }], total: 1, nextCursor: null } }))
+ await page.goto("/mcp?tab=plans")
+ await page.getByText("routing.community.switch", { exact: true }).click()
+ const dialog = page.getByRole("dialog")
+ await expect(dialog.getByRole("heading", { name: "Исходное состояние" })).toBeVisible()
+ await expect(dialog.getByRole("heading", { name: "Запланированные шаги" })).toBeVisible()
+ await expect(dialog.getByText("Изменится gateway выбранного Community", { exact: true })).toBeVisible()
+ await expect(dialog.getByText("Серверы: 1, 2", { exact: true })).toBeVisible()
+ await expect(dialog.getByRole("button", { name: "Подтвердить план", exact: true })).toBeVisible()
+ await dialog.screenshot({ path: "test-results/mcp-plan-review.png" })
+})
+
+test("MCP: права, аудит и ход операции связаны с выбранным подключением", async ({ page }) => {
+ const calls = await setup(page)
+ const operationId = "fa58fa40-4bcb-4616-9316-cb69463b3159"
+ const plan = { id, connectionId: id, operationId: "routing.profiles.save", state: "awaiting-approval", createdAt: at,
+ expiresAt: "2099-01-01T00:00:00Z", changes: { target: { scope: "servers", serverIds: [1] }, warnings: ["Изменится профиль WAN"] } }
+ const records = (items: unknown[]) => ({ items, total: items.length, nextCursor: null })
+ let outcome = "running"
+ await page.route(url => url.pathname === "/api/mcp/policy/preview", async route => {
+ expect(route.request().postDataJSON()).toMatchObject({ connectionId: id, operationId: operation.id, target: { scope: "servers", serverIds: [2] } })
+ await route.fulfill({ json: { simulation: true, executionAvailable: false, evaluatedAt: at, policyVersion: 1,
+ result: { decision: "denied", reasons: [{ code: "SERVER_DENIED", message: "Сервер 2 вне области доступа" }], limits: connection.policy.limits } } })
+ })
+ await page.route(url => url.pathname === "/api/mcp/requests" && url.searchParams.has("connectionId"), route => route.fulfill({
+ json: records([{ id, connection_id: id, tool: "mm_logs_query", status: "denied", error_code: "SERVER_DENIED", created_at: at }]),
+ }))
+ await page.route(url => url.pathname === "/api/mcp/audit" && url.searchParams.has("connectionId"), route => route.fulfill({
+ json: records([{ id: 1, connection_id: id, action: "connection.create", created_at: at }]),
+ }))
+ await page.route(url => url.pathname === "/api/mcp/plans", route => route.fulfill({ json: records([plan]) }))
+ const decisions: unknown[] = [], applications: unknown[] = [], reconciliations: unknown[] = []
+ await page.route(`**/api/mcp/plans/${id}/decision`, async route => {
+ decisions.push(route.request().postDataJSON())
+ plan.state = "approved"
+ await route.fulfill({ json: { ok: true } })
+ })
+ await page.route(`**/api/mcp/plans/${id}/apply`, async route => {
+ applications.push(route.request().postDataJSON())
+ plan.state = "applied"
+ await route.fulfill({ json: { id: operationId, state: "pending" } })
+ })
+ await page.route(url => url.pathname === "/api/mcp/operations", route => {
+ const params = new URL(route.request().url()).searchParams
+ if (params.get("operationId") === operationId) {
+ expect(Object.fromEntries(params)).toEqual({ operationId, limit: "1" })
+ return route.fulfill({ json: records([{ id: operationId, state: outcome, steps: [{ step_index: 0, server_id: 1, state: "verified" }] }]) })
+ }
+ return route.fulfill({ json: records([]) })
+ })
+ await page.route(`**/api/mcp/operations/${operationId}/reconcile`, async route => {
+ reconciliations.push(route.request().postDataJSON())
+ await route.fulfill({ json: { operationId, state: "partial", automaticRetry: false } })
+ })
+
+ await page.goto("/mcp?tab=connections")
+ await page.getByRole("link", { name: "Проверить права", exact: true }).click()
+ await expect(page.getByLabel("Подключение", { exact: true })).toHaveValue(id)
+ await page.getByLabel("Операция", { exact: true }).selectOption(operation.id)
+ await page.getByLabel("ID серверов", { exact: true }).fill("2")
+ await page.getByRole("button", { name: "Проверить", exact: true }).click()
+ await expect(page.getByText("Сервер 2 вне области доступа", { exact: false })).toBeVisible()
+ await page.getByRole("link", { name: "Открыть обращения подключения" }).click()
+ await expect(page.getByLabel("Фильтр подключения MCP")).toHaveValue(id)
+ await expect(page.getByRole("cell", { name: "SERVER_DENIED", exact: true })).toBeVisible()
+ await page.getByRole("link", { name: "Административный аудит подключения" }).click()
+ await expect(page.getByRole("cell", { name: "connection.create", exact: true })).toBeVisible()
+ await page.goBack()
+ await page.getByRole("link", { name: "Планы и операции подключения" }).click()
+ const operationsPanel = page.locator("[data-slot=frame]").filter({ has: page.getByText("Выполнение операций", { exact: true }) })
+ const plansPanel = page.locator("[data-slot=frame]").filter({ has: page.getByText("Планы изменений", { exact: true }) })
+ await expect(plansPanel.getByLabel("Фильтр подключения MCP")).toHaveValue(id)
+ await expect(operationsPanel.getByLabel("Фильтр подключения MCP")).toHaveValue(id)
+ await operationsPanel.getByLabel("Фильтр состояния").fill("running")
+ const dialog = page.getByRole("dialog")
+ await page.getByText(plan.operationId, { exact: true }).click()
+ await expect(dialog).toContainText("Изменится профиль WAN")
+ await dialog.getByRole("button", { name: "Подтвердить план", exact: true }).click()
+ await expect(dialog).toHaveCount(0)
+ await expect(plansPanel.getByText("approved", { exact: true })).toBeVisible()
+ await page.getByText(plan.operationId, { exact: true }).click()
+ await dialog.getByRole("button", { name: "Применить план", exact: true }).click()
+ await page.getByRole("link", { name: "Открыть выполнение операции" }).click()
+ await expect(dialog.getByText("Выполняется", { exact: true })).toBeVisible()
+ outcome = "partial"
+ await dialog.getByRole("button", { name: "Обновить выполнение" }).click()
+ await expect(dialog.getByText("Выполнена частично", { exact: true })).toBeVisible()
+ await expect(dialog.getByRole("region", { name: "Шаги выполнения" })).toContainText("Результат проверен · сервер 1")
+ await dialog.getByRole("link", { name: "Перейти к сверке" }).click()
+ await expect(dialog).toHaveCount(0)
+ await expect(page.getByLabel("ID исходной операции")).toHaveValue(operationId)
+ expect(reconciliations).toEqual([])
+ await page.getByRole("button", { name: "Сверить состояние операции" }).click()
+ await expect(page.getByText('"automaticRetry": false', { exact: false })).toBeVisible()
+ expect(decisions).toEqual([{ approve: true }])
+ expect(applications).toEqual([{}])
+ expect(reconciliations).toEqual([{}])
+ expect(calls).not.toContain(`POST /api/mcp/operations/${operationId}/recover`)
+})
+
+test("MCP: открытый обратный план блокирует подтверждение после истечения срока", async ({ page }) => {
+ await setup(page)
+ const now = new Date("2026-11-14T09:00:00Z")
+ await page.clock.install({ time: new Date(now.getTime() - 1000) })
+ await page.clock.pauseAt(now)
+ const expiresAt = new Date(now.getTime() + 60_000).toISOString()
+ const plan = { id, operationId: "operations.recover", state: "awaiting-approval", createdAt: at, expiresAt, changes: {} }
+ await page.route(url => url.pathname === "/api/mcp/plans", route =>
+ route.fulfill({ json: { items: [plan], total: 1, nextCursor: null } }))
+ const writes: string[] = []
+ page.on("request", request => {
+ if (request.method() === "POST" && new URL(request.url()).pathname.startsWith("/api/mcp/plans/")) writes.push(request.url())
+ })
+ await page.goto("/mcp?tab=plans")
+ await page.getByText("operations.recover", { exact: true }).click()
+ const dialog = page.getByRole("dialog")
+ const approve = dialog.getByRole("button", { name: "Подтвердить план", exact: true })
+ await expect(approve).toBeEnabled()
+ await page.clock.fastForward(60_001)
+ await expect(dialog.getByText("Срок плана истёк. Подготовьте новый план.", { exact: true })).toBeVisible()
+ await expect(approve).toBeDisabled()
+ await expect(dialog.getByRole("button", { name: "Отклонить", exact: true })).toBeDisabled()
+ await approve.press("Enter")
+ expect(writes).toEqual([])
+})
+
+test("MCP: запоздалое решение не закрывает другой план и повторная отправка блокируется", async ({ page }) => {
+ await setup(page)
+ const secondId = "fa58fa40-4bcb-4616-9316-cb69463b3199"
+ const first = { id, operationId: "routing.community.switch", state: "awaiting-approval", createdAt: at, expiresAt: "2099-01-01T00:00:00Z", changes: {} }
+ const second = { ...first, id: secondId, operationId: "ros.ethernet.update", state: "approved" }
+ let finishDecision!: () => void
+ let finishApply!: () => void
+ const decisionGate = new Promise(resolve => { finishDecision = resolve })
+ const applyGate = new Promise(resolve => { finishApply = resolve })
+ const decisions: unknown[] = []
+ const applications: unknown[] = []
+ await page.route(url => url.pathname === "/api/mcp/plans", route => route.fulfill({ json: { items: [first, second], total: 2, nextCursor: null } }))
+ await page.route(`**/api/mcp/plans/${id}/decision`, async route => {
+ decisions.push(route.request().postDataJSON())
+ await decisionGate
+ first.state = "approved"
+ await route.fulfill({ json: { ok: true } })
+ })
+ await page.route(`**/api/mcp/plans/${secondId}/apply`, async route => {
+ applications.push(route.request().postDataJSON())
+ await applyGate
+ await route.fulfill({ json: { id: secondId, state: "pending" } })
+ })
+ try {
+ await page.goto("/mcp?tab=plans")
+ await page.getByText(first.operationId, { exact: true }).click()
+ const dialog = page.getByRole("dialog")
+ await dialog.getByRole("button", { name: "Подтвердить план", exact: true }).click()
+ await expect(dialog.getByRole("button", { name: "Подтвердить план", exact: true })).toBeDisabled()
+ await expect(dialog.getByRole("button", { name: "Отклонить", exact: true })).toBeDisabled()
+ await page.keyboard.press("Escape")
+ await expect(dialog).toHaveCount(0)
+
+ await page.getByText(first.operationId, { exact: true }).click()
+ await expect(dialog.getByRole("button", { name: "Подтвердить план", exact: true })).toBeDisabled()
+ await page.keyboard.press("Escape")
+ await expect(dialog).toHaveCount(0)
+
+ await page.getByText(second.operationId, { exact: true }).click()
+ const apply = dialog.getByRole("button", { name: "Применить план", exact: true })
+ await expect(apply).toBeEnabled()
+ const decisionResponse = page.waitForResponse(response => response.url().endsWith(`/plans/${id}/decision`))
+ const refreshed = page.waitForResponse(response => new URL(response.url()).pathname === "/api/mcp/plans" && response.json().then(payload => payload.items?.some((item: { id: string; state: string }) => item.id === id && item.state === "approved")))
+ finishDecision()
+ await decisionResponse
+ await refreshed
+ await expect(apply).toBeEnabled()
+ expect(decisions).toEqual([{ approve: true }])
+
+ await apply.click()
+ await expect(apply).toBeDisabled()
+ await expect.poll(() => applications).toEqual([{}])
+ finishApply()
+ await expect(dialog).toHaveCount(0)
+ expect(applications).toEqual([{}])
+ } finally {
+ finishDecision()
+ finishApply()
+ }
+})
diff --git a/tests/e2e/network-map-context.spec.ts b/tests/e2e/network-map-context.spec.ts
index 27eaa0fe..113d3c9e 100644
--- a/tests/e2e/network-map-context.spec.ts
+++ b/tests/e2e/network-map-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import {test,expect} from "@playwright/test"
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
const headers={"access-control-allow-origin":"*","access-control-allow-methods":"GET,POST,OPTIONS","access-control-allow-headers":"Content-Type,Authorization"}
@@ -20,7 +21,7 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns
try{await r.fulfill(fails?{headers,status:503,json:{error:"Старая ошибка карты"}}:{headers,json:part==="snapshot"?[row("Поздняя карта")]:part==="flow"?{...empty,services:[{id:"svc:late",label:"Поздний сервис",category:"Web",bytes:1,bps:1,share:1}]}:{results:{"router.example":null}}})}catch{}finally{completed=true}
})
await page.getByRole("button",{name:"Обновить",exact:true}).click()
- await expect.poll(()=>started).toBe(true);await page.goBack();await expect(page).toHaveURL(/settings/)
+ await expect.poll(()=>started).toBe(true);await openSettings(page)
if(change==="backend"){const input=page.getByPlaceholder("http://localhost:8000");await input.fill("http://localhost:8101");await input.press("Enter")}
else await page.getByRole("button",{name:"Моковые",exact:true}).click()
await page.getByRole("link",{name:/^Карта сети/}).click()
diff --git a/tests/e2e/object-permissions/mcp-context.spec.ts b/tests/e2e/object-permissions/mcp-context.spec.ts
new file mode 100644
index 00000000..6a46a276
--- /dev/null
+++ b/tests/e2e/object-permissions/mcp-context.spec.ts
@@ -0,0 +1,59 @@
+import { test, expect } from "@playwright/test"
+const id = "fa58fa40-4bcb-4616-9316-cb69463b3150"
+const at = "2026-10-17T00:00:00Z"
+const policy = { id, version: 1, status: "active", mode: "autonomous", expiresAt: "2099-01-01T00:00:00Z", permissions: ["mm:network:read", "mm:network:write"], scope: { serverIds: [1, 2], operationIds: ["ros.ethernet.list", "ros.ethernet.update"], allowGlobal: false }, dangerousPolicy: "approval", autonomousDangerousOperationIds: [], limits: { callsPerMinute: 60, concurrentReads: 4, mutationsPerHour: 10, serversPerPlan: 5, objectsPerPlan: 100 } }
+const updateOperation = { id: "ros.ethernet.update", toolName: "mm_ethernet_update_plan", version: 1, title: "Изменить Ethernet", section: "network", effect: "write", risk: "dangerous", scope: "servers", requiredPermissions: ["mm:network:write"], implementation: "available", annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true } }
+test("объектная проверка и защита сохраняют server/resource/native ID и сбрасывают контекст", async ({ page }) => {
+ const previews: unknown[] = [], writes: { object: unknown; reason: string }[] = []
+ const duplicateKeys: string[] = []
+ page.on("console", message => { if (message.type() === "error" && message.text().includes("same key")) duplicateKeys.push(message.text()) })
+ await page.addInitScript(() => localStorage.setItem("mmapp_token", "header." + btoa(JSON.stringify({ sub: "ui-admin", apps: ["mm"], permissions: ["mm:settings:admin", "mm:network:admin"], exp: 4102444800 })) + ".signature"))
+ await page.route("**/api/**", async route => {
+ const path = new URL(route.request().url()).pathname, method = route.request().method()
+ const json = (body: unknown) => route.fulfill({ json: body })
+ if (method === "OPTIONS") return route.fulfill({ status: 204 })
+ if (path === "/api/auth/config") return json({ required: false })
+ if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [updateOperation] })
+ if (path === "/api/mcp/connections") return json({ connections: [{ id, name: "Owner", ownerId: "ui-admin", policy, createdAt: at, updatedAt: at, lastUsedAt: null, generationValid: true }] })
+ if (path === "/api/mcp/devices/catalog") return json({ servers: [1, 2].map(id => ({ id, name: `CHR ${id}`, host: `192.0.2.${id}`, enabled: true })), resources: [{ id: "ethernet", title: "Ethernet", read: true, create: false, update: true, delete: false, fields: [] }] })
+ if (/\/devices\/[12]\/ethernet$/.test(path)) return json({ items: [{ ".id": "*A", name: "Ethernet" }], total: 1, nextOffset: null })
+ if (path === "/api/mcp/protections") {
+ if (method === "POST") { writes.push(route.request().postDataJSON()); return json({ id }) }
+ return json({ protections: [{ id, object_ref: { kind: "ethernet", id: "*A", serverId: 1, protection: "deny" }, reason: "Management" }] })
+ }
+ if (path === "/api/mcp/policy/preview") {
+ previews.push(route.request().postDataJSON())
+ return json({ simulation: true, executionAvailable: false, evaluatedAt: at, policyVersion: 1, result: { decision: "denied", reasons: [{ code: "PROTECTED_OBJECT", message: "Изменение интерфейса управления запрещено защитой" }], limits: policy.limits } })
+ }
+ return json({ items: [], total: 0, nextCursor: null })
+ })
+ await page.goto("/mcp?tab=permissions")
+ await page.getByLabel("Подключение", { exact: true }).selectOption(id)
+ const object = page.getByRole("region", { name: "Проверка объекта устройства" })
+ await object.getByLabel("Сервер проверяемого объекта").selectOption("1")
+ await object.getByLabel("Тип проверяемого объекта").selectOption("ethernet")
+ await object.getByLabel("Стабильный ID объекта").selectOption("*A")
+ await object.getByLabel("Операция над объектом").selectOption("ros.ethernet.update")
+ await object.getByRole("button", { name: "Проверить выбранный объект" }).click()
+ await expect(object.getByRole("status")).toContainText("Запрещено")
+ await expect(object.getByRole("status")).toContainText("Изменение интерфейса управления запрещено защитой")
+ await expect(object.getByRole("status")).toContainText("PROTECTED_OBJECT")
+ await expect(object.getByRole("status")).toContainText("60 вызовов/мин")
+ await expect(object.locator("pre")).toHaveCount(0)
+ expect(previews).toHaveLength(1)
+ expect(previews[0]).toEqual({ connectionId: id, operationId: "ros.ethernet.update", objects: [{ kind: "ethernet", id: "*A", serverId: 1 }], objectCount: 1, target: { scope: "servers", serverIds: [1] } })
+ await object.getByLabel("Защита выбранного объекта").selectOption("deny")
+ await object.getByLabel("Причина защиты объекта").fill("Management")
+ await object.getByRole("button", { name: "Защитить выбранный объект" }).click()
+ await expect(object.getByRole("status")).toContainText("Защита сохранена")
+ expect(writes).toEqual([{ object: { kind: "ethernet", id: "*A", serverId: 1, protection: "deny" }, reason: "Management" }])
+ await object.getByLabel("Сервер проверяемого объекта").selectOption("2")
+ await expect(object.getByRole("status")).toHaveCount(0)
+ await expect(object.getByRole("button", { name: "Защитить выбранный объект" })).toBeDisabled()
+ await expect(object.getByRole("button", { name: "Проверить выбранный объект" })).toBeDisabled()
+ await object.getByLabel("Стабильный ID объекта").selectOption("*A")
+ await object.getByRole("button", { name: "Защитить выбранный объект" }).click()
+ await expect.poll(() => writes.length).toBe(2)
+ expect(writes[1].object).toMatchObject({ serverId: 2, kind: "ethernet", id: "*A" })
+ expect(duplicateKeys).toEqual([])
+})
diff --git a/tests/e2e/ospf-context.spec.ts b/tests/e2e/ospf-context.spec.ts
index abf5a6b7..b468ea20 100644
--- a/tests/e2e/ospf-context.spec.ts
+++ b/tests/e2e/ospf-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import { test, expect } from "@playwright/test"
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,POST,OPTIONS", "access-control-allow-headers": "Content-Type,Authorization" }
const device = { id: 1, name: "Роутер 1", host: "192.0.2.1", enabled: true, country: "RU", status: null }
@@ -29,9 +30,7 @@ for (const change of ["backend", "mode"]) for (const operation of ["read", "writ
})
await page.getByRole("button", { name: operation === "read" ? "Обновить" : "Оптимизировать OSPF", exact: true }).click()
await expect.poll(() => started).toBe(true)
- await page.goBack()
- await page.goBack()
- await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
if (change === "backend") {
const input = page.getByPlaceholder("http://localhost:8000")
await input.fill("http://localhost:8101")
diff --git a/tests/e2e/recursive-routes-context.spec.ts b/tests/e2e/recursive-routes-context.spec.ts
index fb7f6351..103e563b 100644
--- a/tests/e2e/recursive-routes-context.spec.ts
+++ b/tests/e2e/recursive-routes-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import {test,expect} from "@playwright/test"
const headers={"access-control-allow-origin":"*","access-control-allow-methods":"GET,PUT,POST,OPTIONS","access-control-allow-headers":"Content-Type,Authorization"}
const device={id:1,name:"Роутер 1",host:"192.0.2.1",country:"RU",enabled:true,status:null}
@@ -23,7 +24,7 @@ for(const change of ["backend","mode"])for(const operation of ["read","write"])f
const sheet=page.getByRole("dialog");await sheet.getByPlaceholder("8.8.8.8/32").fill("203.0.113.0/24");await sheet.getByPlaceholder("1.2.3.4%GW-NAME").fill("192.0.2.9")
await sheet.getByRole("button",{name:"Добавить",exact:true}).click()
}
- await expect.poll(()=>started).toBe(true);await page.goBack();await expect(page).toHaveURL(/settings/)
+ await expect.poll(()=>started).toBe(true);await openSettings(page)
if(change==="backend"){const input=page.getByPlaceholder("http://localhost:8000");await input.fill("http://localhost:8101");await input.press("Enter")}
else await page.getByRole("button",{name:"Моковые",exact:true}).click()
await page.getByRole("link",{name:/^Рекурсивные маршруты/}).click()
diff --git a/tests/e2e/route-optimizer-context.spec.ts b/tests/e2e/route-optimizer-context.spec.ts
index f443a555..1ac085f0 100644
--- a/tests/e2e/route-optimizer-context.spec.ts
+++ b/tests/e2e/route-optimizer-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import {test,expect} from "@playwright/test"
const headers={"access-control-allow-origin":"*","access-control-allow-methods":"GET,POST,OPTIONS","access-control-allow-headers":"Content-Type,Authorization"}
const item=(name:string)=>({id:"i",interface:name,currentCost:10,optimalCost:20,score:50,pingMs:10,dlMbps:100,ulMbps:50})
@@ -19,7 +20,7 @@ for(const change of ["backend","mode"])for(const operation of ["preview","write"
return r.fulfill(fails?{headers,status:503,json:{error:"Старая ошибка оптимизатора"}}:{headers,json:operation==="preview"?{serverId:1,serverName:"Старый сервер",pingWeight:60,interfacesTotal:1,changedCount:1,unchangedCount:0,interfaces:[row],changes:[row]}:{serverId:1,serverName:"Старый сервер",pingWeight:60,optimizedCount:1,applied:[{interface:"ether-late",from:10,to:20}],interfaces:[row]}})
})
await page.getByRole("button",{name:operation==="preview"?"Обновить preview OSPF":"Оптимизировать OSPF",exact:true}).click()
- await expect.poll(()=>started).toBe(true);await page.goBack();await expect(page).toHaveURL(/settings/)
+ await expect.poll(()=>started).toBe(true);await openSettings(page)
if(change==="backend"){const input=page.getByPlaceholder("http://localhost:8000");await input.fill("http://localhost:8101");await input.press("Enter")}
else await page.getByRole("button",{name:"Моковые",exact:true}).click()
await page.getByRole("link",{name:/^Оптимизатор маршрутов/}).click()
diff --git a/tests/e2e/servers.spec.ts b/tests/e2e/servers.spec.ts
index 86435ab1..e588a0fa 100644
--- a/tests/e2e/servers.spec.ts
+++ b/tests/e2e/servers.spec.ts
@@ -260,7 +260,7 @@ test("поздний ответ первого сервера не переза
await expect(page.getByPlaceholder("api-user", { exact: true })).toHaveValue("test-user")
})
-test("массовый опрос ограничен четырьмя запросами и повторяет только ошибки", async ({ page }) => {
+test("массовый опрос последователен и повторяет только явно выбранные ошибки", async ({ page }) => {
let active = 0, maximum = 0
const calls: string[] = []
let fail = true
@@ -276,7 +276,7 @@ test("массовый опрос ограничен четырьмя запро
}, 6)
await page.getByRole("button", { name: "Проверить все", exact: true }).click()
await expect(page.getByText("Опрос: успешно 5 из 6", { exact: true })).toBeVisible()
- expect(maximum).toBeLessThanOrEqual(4)
+ expect(maximum).toBe(1)
expect(calls).toHaveLength(6)
fail = false
await page.getByRole("button", { name: "Повторить неуспешные", exact: true }).click()
diff --git a/tests/e2e/system-database-receipt.spec.ts b/tests/e2e/system-database-receipt.spec.ts
index 6921c29b..d02aae72 100644
--- a/tests/e2e/system-database-receipt.spec.ts
+++ b/tests/e2e/system-database-receipt.spec.ts
@@ -1,9 +1,16 @@
import {test,expect} from "@playwright/test"
-for(const confirmed of [false,true])test("System DB: choose is not restore; strict receipt and cleanup warning/"+confirmed,async({page})=>{
+for(const confirmed of [false,true,"maintenance"] as const)test("System DB: choose is not restore; strict receipt and cleanup warning/"+confirmed,async({page})=>{
let restores=0
- await page.route("**/health",r=>r.fulfill({json:{status:"ok"}}));await page.route("**/api/**",r=>{const path=new URL(r.request().url()).pathname;if(path==="/api/auth/config")return r.fulfill({json:{required:false}});if(path==="/api/system/database/restore"){restores++;return r.fulfill({json:confirmed?{ok:true,cleanupError:"temporary dump cleanup failed"}:{ok:false}})}return r.fulfill({status:503,json:{error:"outside database fixture"}})})
+ const receipt = confirmed === "maintenance" ? { ok: true, maintenanceError: "Карантин сохранён до публикации внешней контрольной записи" }
+ : confirmed ? { ok: true, cleanupError: "temporary dump cleanup failed" } : { ok: false }
+ await page.route("**/health",r=>r.fulfill({json:{status:"ok"}}));await page.route("**/api/**",r=>{const path=new URL(r.request().url()).pathname;if(path==="/api/auth/config")return r.fulfill({json:{required:false}});if(path==="/api/system/database/restore"){restores++;return r.fulfill({json:receipt})}return r.fulfill({status:503,json:{error:"outside database fixture"}})})
await page.goto("/settings");await page.getByRole("button",{name:"Выбрать файл",exact:true}).click();await page.getByRole("dialog").locator('input[type="file"]').setInputFiles({name:"fixture.dump",mimeType:"application/octet-stream",buffer:Buffer.from("PGDMPfixture")});await page.getByRole("button",{name:"Продолжить",exact:true}).click();await expect(page.getByRole("alertdialog")).toBeVisible();await expect(page.getByText("Импорт выполнен",{exact:true})).toHaveCount(0);expect(restores).toBe(0)
await page.getByRole("alertdialog").getByRole("button",{name:"Восстановить",exact:true}).click()
- if(confirmed){await expect(page.getByText("База приложения восстановлена",{exact:true})).toBeVisible();await expect(page.getByText("temporary dump cleanup failed",{exact:true})).toBeVisible();await expect(page.getByRole("alertdialog")).toHaveCount(0)}else{await expect(page.getByText("Восстановление базы не подтверждено сервером",{exact:true})).toBeVisible();await expect(page.getByText("База приложения восстановлена",{exact:true})).toHaveCount(0);await expect(page.getByRole("alertdialog")).toBeVisible()}
+ if (confirmed === "maintenance") {
+ await expect(page.getByText("Завершение восстановления базы требует проверки", { exact: true })).toBeVisible()
+ await expect(page.getByText(receipt.maintenanceError!, { exact: true })).toBeVisible()
+ await expect(page.getByText("База приложения восстановлена", { exact: true })).toHaveCount(0)
+ await expect(page.getByRole("alertdialog")).toHaveCount(0)
+ } else if(confirmed){await expect(page.getByText("База приложения восстановлена",{exact:true})).toBeVisible();await expect(page.getByText("temporary dump cleanup failed",{exact:true})).toBeVisible();await expect(page.getByRole("alertdialog")).toHaveCount(0)}else{await expect(page.getByText("Восстановление базы не подтверждено сервером",{exact:true})).toBeVisible();await expect(page.getByText("База приложения восстановлена",{exact:true})).toHaveCount(0);await expect(page.getByRole("alertdialog")).toBeVisible()}
expect(restores).toBe(1)
})
diff --git a/tests/e2e/traffic-flow.spec.ts b/tests/e2e/traffic-flow.spec.ts
index 12508ee6..56535f2b 100644
--- a/tests/e2e/traffic-flow.spec.ts
+++ b/tests/e2e/traffic-flow.spec.ts
@@ -1,8 +1,8 @@
import { installOpenLiveStream, resumeLiveStream, sendLiveHeartbeat } from "./live-stream-fixture"
import { test, expect, type Page } from '@playwright/test'
-async function setup(page: Page) {
- const control = { emptyExporters: false, failCatalog: false, hold: '', holdIface: '', fail: false, failList: false, invalidSample: undefined as unknown, mergeSample: false, metrics: {} as Record, release: () => {} }
+async function setup(page: Page, liveRefusals = 0, unknownServer = false) {
+ const control = { emptyExporters: false, failCatalog: false, hold: '', holdIface: '', fail: false, failList: false, invalidSample: undefined as unknown, mergeSample: false, metrics: {} as Record, release: () => {}, liveCalls: 0 }
const gate = new Promise(resolve => { control.release = resolve })
const card = { id: '1', name: 'Экспортёр тест', subtitle: '', site: 'TEST', country: 'RU', status: 'online', rxNow: 2, txNow: 3, sessions: 1, rxSeries: [1, 2], txSeries: [2, 3], bytes: 200 }
const data = { bpsNow: 1000000, bytes: 200, packets: 2, conversations: 1, uniqueSrc: 1, uniqueDst: 1, topProto: 'TCP', rxSeries: [1], txSeries: [2], applications: [], protocols: [], sources: [], destinations: [], interfaces: [], conversationsList: [], ifaces: [], live: false }
@@ -17,24 +17,55 @@ async function setup(page: Page) {
if (control.fail) return route.fulfill({ status: 500, json: { error: 'Срез временно недоступен' } })
return route.fulfill({ json: { ...data, ...control.metrics, topCategory: url.searchParams.get('serverId') === '2' ? 'Второй сервер' : 'Категория ' + range } })
}
- if (path === '/api/traffic/flow/live') return route.fulfill({ contentType: 'text/event-stream', body: 'event: sample\ndata: ' + JSON.stringify({ ...data, live: true }) + '\n\n' + (control.invalidSample === undefined ? '' : 'event: sample\ndata: ' + JSON.stringify(control.mergeSample ? { ...data, ...(control.invalidSample as object) } : control.invalidSample) + '\n\n') })
+ if (path === '/api/traffic/flow/live') {
+ control.liveCalls++
+ if (control.liveCalls <= liveRefusals) return route.fulfill({ status: 429, json: { error: 'Ресурс чтения NetFlow занят; повторите запрос позже' } })
+ return route.fulfill({ contentType: 'text/event-stream', body: 'event: sample\ndata: ' + JSON.stringify({ ...data, live: true }) + '\n\n' + (control.invalidSample === undefined ? '' : 'event: sample\ndata: ' + JSON.stringify(control.mergeSample ? { ...data, ...(control.invalidSample as object) } : control.invalidSample) + '\n\n') })
+ }
if (path === '/api/traffic/flow/exporters' && control.failList) return route.fulfill({ status: 403, json: { error: 'Нет доступа к экспортёрам' } })
const json = path === '/api/auth/config' ? { required: false }
: path === '/api/traffic/flow/exporters' ? { exporters: control.emptyExporters ? [] : [card, { ...card, id: '2', name: 'Экспортёр второй' }] }
: path === '/api/traffic/flow/clients' ? { clients: [{ ...card, id: 'client1', name: 'Клиент тест' }] }
: path === '/api/traffic/flows' ? { exportersOnline: 1, bytesPerMin: 1, uniqueSrc: 1, uniqueDst: 1, topProto: 'TCP', talkers: [], listenerBound: true }
- : path === '/api/traffic/servers' ? { servers: [] }
+ : path === '/api/traffic/servers' ? { servers: unknownServer ? [{ ...card, name: 'Маршрутизатор без страны', country: '', rxPeak: null, txPeak: null, rxTotal: null, txTotal: null }] : [] }
: path.endsWith('/interfaces') || path.endsWith('/bound-interfaces') ? { interfaces: [] }
: path === '/api/traffic/users' ? { users: [] }
: path === '/api/servers' ? [] : {}
return route.fulfill({ json })
})
await page.goto('/traffic')
+ if (unknownServer) {
+ const server = page.getByRole('button').filter({ hasText: 'Маршрутизатор без страны' })
+ await expect(server).toBeVisible()
+ await expect(server.locator('img[src$="/un.png"]')).toHaveCount(0)
+ }
await page.getByRole('button', { name: 'Потоки', exact: true }).click()
await expect(page.getByLabel('Скорость потоков')).toBeVisible()
return control
}
+test('Flow: начальный HTTP 429 сменяется фактическими данными SSE', async ({ page }) => {
+ const statuses: number[] = []
+ page.on('response', response => {
+ if (new URL(response.url()).pathname === '/api/traffic/flow/live') statuses.push(response.status())
+ })
+ const control = await setup(page, 1)
+ await expect(page.getByLabel('Получение аналитики потоков')).toContainText('Получено (live-поток)')
+ await expect(page.getByText('live HTTP 429', { exact: true })).toHaveCount(0)
+ expect(statuses).toEqual([429, 200])
+ expect(control.liveCalls).toBe(2)
+})
+
+test('Flow: переход с сервера без страны в потоки не загружает флаг UN', async ({ page }) => {
+ let placeholderRequests = 0
+ await page.route('https://flagcdn.com/**', async route => {
+ if (new URL(route.request().url()).pathname.endsWith('/un.png')) placeholderRequests++
+ await route.abort()
+ })
+ await setup(page, 0, true)
+ expect(placeholderRequests).toBe(0)
+})
+
test('Flow: поздний ответ периода не заменяет текущую аналитику', async ({ page }) => {
const control = await setup(page)
control.hold = '24h'
diff --git a/tests/e2e/users-operations.spec.ts b/tests/e2e/users-operations.spec.ts
index 06620284..fe27d00f 100644
--- a/tests/e2e/users-operations.spec.ts
+++ b/tests/e2e/users-operations.spec.ts
@@ -3,6 +3,33 @@ import {user,server,catalogResponse} from "./fixtures/users"
test.beforeEach(async({page})=>{
await page.route("**/health",r=>catalogResponse(r, {json:{ok:true}}));await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return catalogResponse(r, {json:p==="/api/auth/config"?{required:false}:p==="/api/users"?{users:[user]}:p==="/api/servers"?[server]:{interfaces:[]}})})
})
+
+test("Редактор профиля видит права только для чтения", async ({ page }) => {
+ await page.addInitScript(() => localStorage.setItem("mmapp_token", "header." + btoa(JSON.stringify({
+ sub: "users-editor", apps: ["mm"], permissions: ["mm:users:write", "mm:servers:read"],
+ exp: Math.floor(Date.now() / 1000) + 3600,
+ })) + ".signature"))
+ await page.route("**/api/auth/config", route => catalogResponse(route, { json: { required: true } }))
+ let submitted: Record | undefined
+ await page.route("**/api/users/u-test", route => {
+ submitted = route.request().postDataJSON()
+ return catalogResponse(route, { json: { user: { ...user, ...submitted } } })
+ })
+ await page.goto("/users")
+ await page.getByRole("button", { name: "Редактировать пользователя " + user.name }).click()
+ const dialog = page.getByRole("dialog")
+ await expect(dialog.getByRole("button", { name: "Оператор", exact: true })).toHaveCount(0)
+ await dialog.getByPlaceholder("Иван Иванов").fill("Изменённый профиль")
+ await dialog.getByRole("button", { name: "Далее", exact: true }).click()
+ await expect(dialog.getByRole("button", { name: "Просмотр", exact: true }).first()).toBeDisabled()
+ await dialog.getByRole("button", { name: "Далее", exact: true }).click()
+ await expect(dialog.getByRole("button", { name: "Просмотр", exact: true }).first()).toBeDisabled()
+ await dialog.getByRole("button", { name: "Далее", exact: true }).click()
+ await dialog.getByRole("button", { name: "Сохранить", exact: true }).click()
+ await expect(dialog).toHaveCount(0)
+ expect(submitted).toMatchObject({ name: "Изменённый профиль" })
+ for (const field of ["role", "sections", "servers"]) expect(submitted).not.toHaveProperty(field)
+})
for(const kind of ["403","503","malformed"] as const)test("Удаление пользователя: ошибка сохраняет диалог "+kind,async({page})=>{
let fail=true,deleted=false;await page.route("**/api/users",r=>catalogResponse(r, {json:{users:deleted?[]:[user]}}))
await page.route("**/api/users/u-test",r=>{if(fail)return catalogResponse(r, kind==="malformed"?{status:200,json:{success:true}}:{status:Number(kind),json:{error:"УДАЛЕНИЕ ОТКЛОНЕНО"}});deleted=true;return catalogResponse(r, {status:204,body:""})})
diff --git a/tests/e2e/vxlan-context.spec.ts b/tests/e2e/vxlan-context.spec.ts
index 1c8efb9c..39ae6785 100644
--- a/tests/e2e/vxlan-context.spec.ts
+++ b/tests/e2e/vxlan-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import { test, expect } from "@playwright/test"
const headers = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET,OPTIONS", "access-control-allow-headers": "Content-Type,Authorization" }
const tunnel = (port: string) => ({ id: "*1", name: port === "8101" ? "Новый VXLAN" : "Старый VXLAN", serverId: "1", vni: port === "8101" ? 200 : 100, port: 0, dstPort: 8472, vtepIp: "192.0.2.1", remoteVteps: [], l2mtu: 1500, arpProxy: false, macLearning: true, comment: "", enabled: true, status: "up" })
@@ -22,8 +23,7 @@ for (const change of ["backend", "mode"]) for (const fails of [false, true]) {
})
await page.getByRole("button", { name: "Обновить", exact: true }).click()
await expect.poll(() => started).toBe(true)
- await page.goBack()
- await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
if (change === "backend") {
const input = page.getByPlaceholder("http://localhost:8000")
await input.fill("http://localhost:8101")
diff --git a/tests/e2e/wireguard-context.spec.ts b/tests/e2e/wireguard-context.spec.ts
index 758823b1..637d4ff7 100644
--- a/tests/e2e/wireguard-context.spec.ts
+++ b/tests/e2e/wireguard-context.spec.ts
@@ -1,3 +1,4 @@
+import { openSettings } from "./fixtures/open-settings"
import { test, expect } from "@playwright/test"
const headers={"access-control-allow-origin":"*","access-control-allow-methods":"GET,PATCH,OPTIONS","access-control-allow-headers":"Content-Type,Authorization"}
const iface=(port:string)=>({id:"*1",rosId:"*1",name:port==="8101"?"Новый WireGuard":"Старый WireGuard",serverId:"1",serverName:"Роутер",listenPort:13231,mtu:1420,comment:"",enabled:true,status:"up",peers:[]})
@@ -17,7 +18,7 @@ for(const operation of ["read","toggle"])for(const change of ["backend","mode"])
if(operation==="read")await page.getByRole("button",{name:"Обновить",exact:true}).click()
else{await page.getByRole("button",{name:"Действия: Старый WireGuard",exact:true}).click();await page.getByRole("menuitem",{name:"Отключить",exact:true}).click()}
await expect.poll(()=>started).toBe(true)
- await page.goBack();await expect(page).toHaveURL(/settings/)
+ await openSettings(page)
if(change==="backend"){const input=page.getByPlaceholder("http://localhost:8000");await input.fill("http://localhost:8101");await input.press("Enter")}
else await page.getByRole("button",{name:"Моковые",exact:true}).click()
await page.getByRole("link",{name:/^WireGuard/}).click()
diff --git a/tests/unit/flow-live-admission.test.ts b/tests/unit/flow-live-admission.test.ts
new file mode 100644
index 00000000..ac1fb199
--- /dev/null
+++ b/tests/unit/flow-live-admission.test.ts
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict"
+import test from "node:test"
+import { openFlowLiveResponse } from "../../hooks/use-flow-live"
+
+const url = "http://127.0.0.1/api/traffic/flow/live"
+
+test("opens the NetFlow stream after a transient 429", async () => {
+ const { signal } = new AbortController()
+ let calls = 0
+ let discarded = false
+ const response = await openFlowLiveResponse(url, signal, async (target, init) => {
+ calls++
+ assert.equal(target, url)
+ assert.equal(init?.signal, signal)
+ assert.equal(new Headers(init?.headers).get("Accept"), "text/event-stream")
+ if (calls === 1) {
+ return new Response(new ReadableStream({ cancel() { discarded = true } }), { status: 429 })
+ }
+ return new Response("event: sample\ndata: {}\n\n", { headers: { "Content-Type": "text/event-stream" } })
+ })
+ assert.equal(calls, 2)
+ assert.equal(discarded, true)
+ assert.equal(response.status, 200)
+})
+
+test("stops retrying when the NetFlow live view unmounts", async () => {
+ const controller = new AbortController()
+ let calls = 0
+ const response = openFlowLiveResponse(url, controller.signal, async () => {
+ calls++
+ return new Response(new ReadableStream({
+ cancel() { setTimeout(() => controller.abort(), 20) },
+ }), { status: 429 })
+ })
+ await assert.rejects(response, { name: "AbortError" })
+ assert.equal(calls, 1)
+})
+
+test("keeps the live admission budget bounded and leaves authorization failures terminal", async () => {
+ const { signal } = new AbortController()
+ let calls = 0
+ const limited = await openFlowLiveResponse(url, signal, async () => {
+ calls++
+ return new Response(null, { status: 429 })
+ })
+ assert.equal(limited.status, 429)
+ assert.equal(calls, 4)
+ const unauthorized = await openFlowLiveResponse(url, signal, async () => {
+ calls++
+ return new Response(null, { status: 401 })
+ })
+ assert.equal(unauthorized.status, 401)
+ assert.equal(calls, 5)
+})
diff --git a/tests/unit/server-poll-batch.test.ts b/tests/unit/server-poll-batch.test.ts
new file mode 100644
index 00000000..84cdeaa5
--- /dev/null
+++ b/tests/unit/server-poll-batch.test.ts
@@ -0,0 +1,15 @@
+import assert from "node:assert/strict"
+import { test } from "node:test"
+import { pollServers } from "../../lib/server-operations.js"
+test("full poll batches serialize global maintenance and never retry a failed target",async()=>{
+ let active=0,maxActive=0
+ const calls:string[]=[]
+ const results=await pollServers(["1","2","1","3"],async id=>{
+ calls.push(id);active++;maxActive=Math.max(maxActive,active)
+ try{await new Promise(done=>setImmediate(done));if(id==="2")throw Error("uncertain; refresh first")}
+ finally{active--}
+ })
+ assert.equal(maxActive,1)
+ assert.deepEqual(calls,["1","2","3"])
+ assert.deepEqual(results,[{id:"1",error:null},{id:"2",error:"uncertain; refresh first"},{id:"3",error:null}])
+})
diff --git a/tsconfig.json b/tsconfig.json
index 638708d4..823876fa 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,7 +1,11 @@
{
"compilerOptions": {
"target": "ES2017",
- "lib": ["dom", "dom.iterable", "esnext"],
+ "lib": [
+ "dom",
+ "dom.iterable",
+ "esnext"
+ ],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
@@ -19,7 +23,9 @@
}
],
"paths": {
- "@/*": ["./*"]
+ "@/*": [
+ "./*"
+ ]
}
},
"include": [
@@ -28,7 +34,40 @@
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
- "**/*.mts"
+ "**/*.mts",
+ "tmp/next-mcp-test/types/**/*.ts",
+ "tmp/next-mcp-test/dev/types/**/*.ts",
+ "tmp/next-mcp-auth-test/types/**/*.ts",
+ "tmp/next-mcp-auth-test/dev/types/**/*.ts",
+ "tmp/next-mcp-object-test/types/**/*.ts",
+ "tmp/next-mcp-object-test/dev/types/**/*.ts",
+ "tmp/next-logs-test/types/**/*.ts",
+ "tmp/next-logs-test/dev/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-fpodys/next/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-fpodys/next/dev/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-eCh4ca/next/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-eCh4ca/next/dev/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-C2YiFv/next/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-C2YiFv/next/dev/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-ITx0lt/next/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-ITx0lt/next/dev/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-0OzJOf/next/types/**/*.ts",
+ "tmp/mcp-current-preview-local-review-20261111/portal-real-revoke-proof/owned-revoke-0OzJOf/next/dev/types/**/*.ts",
+ "tmp/next-mcp-routing-resume/types/**/*.ts",
+ "tmp/next-mcp-routing-resume/dev/types/**/*.ts",
+ "tmp/next-wireguard-context-test/types/**/*.ts",
+ "tmp/next-wireguard-context-test/dev/types/**/*.ts",
+ "tmp/next-db-receipt-20261115/types/**/*.ts",
+ "tmp/next-db-receipt-20261115/dev/types/**/*.ts"
],
- "exclude": ["node_modules", "backend", "packages", "tmp", "temp", "test-results", "playwright-report"]
+ "exclude": [
+ "node_modules",
+ "backend",
+ "packages",
+ "tmp",
+ "tmp-*/**",
+ "temp",
+ "test-results",
+ "playwright-report"
+ ]
}