feat(mcp): добавить веб-раздел MCP, клиентский API и e2e-тесты

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
DenozordecandClaude Sonnet 5.5 committed 2026-11-15 20:36:14 +07:00
1 parent 18c0a52171
commit 6cb550e179
77 files changed
+4929 -209

No files matched your search

+58 -19
View File
@@ -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<string | null>(null)
const certEpoch = useRef(0)
const certPending = useRef(false)
useEffect(() => () => { certEpoch.current += 1 }, [])
const certFailedAttempts = useRef(new Set<string>())
const certActive = useRef<{ targetKey: string; controller: AbortController } | null>(null)
const [certAttemptFailed, setCertAttemptFailed] = useState(false)
const [certRole, setCertRole] = useState<IpsecCertInfoDto["role"]>("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<IpsecCertBundle>) => {
const loadCert = async (serverId: string, targetKey: string, request: (signal: AbortSignal) => Promise<IpsecCertBundle>) => {
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
/>
<IpsecCertSheet
key={certSession}
open={certOpen}
onOpenChange={(v) => {
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}
/>
+6
View File
@@ -0,0 +1,6 @@
import { Suspense } from "react"
import { McpWorkspace } from "@/components/mcp/mcp-workspace"
export default function McpPage() {
return <Suspense fallback={<p role="status" className="p-6">Загрузка MCP…</p>}><McpWorkspace /></Suspense>
}
+9 -6
View File
@@ -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 }
+4 -2
View File
@@ -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<AppUser[]>(() => 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}
+10 -1
View File
@@ -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;
+8 -3
View File
@@ -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 (
<div className="text-muted-foreground flex min-h-svh items-center justify-center p-6 text-sm">
Проверка сессии…
@@ -16,6 +16,9 @@ import { CableIcon, KeyRoundIcon, LockIcon, NetworkIcon, ShieldIcon } from "luci
const TYPE_VARIANT: Record<InterfaceType, "outline" | "info-light" | "success-light" | "secondary"> = {
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<InterfaceType, "outline" | "info-light" | "success-li
const TYPE_ICON: Record<InterfaceType, { icon: typeof CableIcon; className: string }> = {
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" },
+11 -5
View File
@@ -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 `<image href>` (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)
+86 -10
View File
@@ -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<void>
onReexport?: (passphrase: string, options: IpsecExistingCertExportOptions) => void | Promise<void>
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 (
<>
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent side="right" className="w-full sm:max-w-md flex flex-col gap-0 p-0">
<SheetHeader className="px-6 pt-6 pb-4 border-b shrink-0">
<SheetTitle>Сертификат клиента {bundle ? `«${bundle.user}»` : ""}</SheetTitle>
<SheetTitle>Сертификат {bundle?.user || targetName ? `«${bundle?.user ?? targetName}»` : ""}</SheetTitle>
<SheetDescription>
.p12 для Windows/macOS/iOS · .sswan для strongSwan (Android/iOS)
</SheetDescription>
@@ -73,8 +112,16 @@ function IpsecCertSheet({
<div className="flex-1 min-w-0 overflow-y-auto overflow-x-hidden px-6 py-5 flex flex-col gap-5">
{busy && <p role="status" className="text-sm text-muted-foreground">Загрузка сертификата…</p>}
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{previousAttemptFailed && !busy && (
<p role="alert" className="text-sm text-destructive">Предыдущая попытка завершилась ошибкой; её результат на роутере может быть неизвестен. Проверьте временный файл и состояние экспорта перед новым запросом.</p>
)}
{!bundle ? (
!busy && onReexport ? <Button variant="outline" onClick={() => void onReexport(randomPassphrase())}>Повторить экспорт</Button> : null
!busy && onReexport ? (
<div className="space-y-3">
<p className="text-sm text-muted-foreground">Экспорт .p12 включает закрытый ключ. Подтвердите его получение перед запросом к роутеру.</p>
<Button variant="outline" onClick={openExportConfirmation}>{previousAttemptFailed ? "Подготовить новый запрос" : "Экспортировать .p12"}</Button>
</div>
) : null
) : (
<>
<div className="flex flex-col gap-4">
@@ -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}
>
<RefreshCwIcon className={`size-4 ${busy ? "animate-spin" : ""}`} />
</Button>
@@ -180,6 +224,38 @@ function IpsecCertSheet({
</SheetFooter>
</SheetContent>
</Sheet>
<Dialog open={confirmationOpen && open} onOpenChange={setConfirmationOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Подтвердить экспорт {isCa ? "CA" : "сертификата"}</DialogTitle>
<DialogDescription>Запрос создаст на роутере временный .p12 с закрытым ключом сертификата {targetName ? `«${targetName}»` : ""}, прочитает его и удалит временный файл. Пароль архива будет сгенерирован после подтверждения.</DialogDescription>
</DialogHeader>
<label htmlFor="ipsec-export-private-key" className="flex items-start gap-2 text-sm">
<Checkbox id="ipsec-export-private-key" checked={privateKeyConfirmed} onCheckedChange={setPrivateKeyConfirmed} />
<span>Разрешаю экспорт и получение закрытого ключа выбранного сертификата.</span>
</label>
{isCa && (
<label htmlFor="ipsec-export-ca-key" className="flex items-start gap-2 text-sm">
<Checkbox id="ipsec-export-ca-key" checked={caKeyConfirmed} onCheckedChange={setCaKeyConfirmed} />
<span>Отдельно разрешаю экспорт закрытого ключа центра сертификации CA. Его владелец может подписывать другие сертификаты.</span>
</label>
)}
{previousAttemptFailed && (
<div className="space-y-3">
<p className="text-sm text-destructive">Результат предыдущего запроса может быть неизвестен. Новый запрос не продолжает и не подтверждает предыдущую попытку.</p>
<label htmlFor="ipsec-export-new-attempt" className="flex items-start gap-2 text-sm">
<Checkbox id="ipsec-export-new-attempt" checked={newAttemptConfirmed} onCheckedChange={setNewAttemptConfirmed} />
<span>Я проверил состояние роутера и явно запрашиваю новый экспорт.</span>
</label>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setConfirmationOpen(false)}>Отмена</Button>
<Button disabled={!confirmEnabled} onClick={() => void confirmExport()}>{previousAttemptFailed ? "Отправить новый запрос" : "Подтвердить экспорт"}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
+1 -1
View File
@@ -118,7 +118,7 @@ function CertRow({
</p>
</div>
<div className="flex shrink-0 gap-0.5">
{onExport && cert.role === "client" ? (
{onExport ? (
<Button
type="button"
size="icon"
+3 -2
View File
@@ -22,11 +22,12 @@ export function LogDetailSheet({ entry, base, onClose, onSelect }: { entry: LogE
}
function LogDetail({ entry, base, onSelect }: { entry: LogEntry; base: string; onSelect: (entry: LogEntry) => void }) {
const [context, setContext] = useState<Awaited<ReturnType<typeof getLogContext>> | null>(null), [error, setError] = useState<string | null>(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 <>
<SheetHeader className="gap-3 border-b">
+12 -1
View File
@@ -127,7 +127,18 @@ function LogExplorer({ base, raw, selectedName, liveAvailable }: { base: string;
<Button size="sm" variant="outline" disabled={exporting} onClick={() => void doExport("csv")}><DownloadIcon />CSV</Button><Button size="sm" variant="outline" disabled={exporting} onClick={() => void doExport("json")}>JSON</Button>
</div></div>
{range === "custom" && <div className="flex flex-wrap gap-3">{["from", "to"].map(key => <label key={key} className="flex min-w-0 flex-col gap-1 text-xs">{key === "from" ? "Начало (UTC)" : "Конец (UTC)"}<Input type="datetime-local" aria-label={key === "from" ? "Начало периода UTC" : "Конец периода UTC"} value={params.get(key)?.slice(0, 16) ?? ""} onChange={event => { if (event.target.value) navigate({ [key]: new Date(event.target.value + "Z").toISOString() }) }} /></label>)}</div>}
<div role="status" className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground"><Badge variant={!collectorEnabled ? "secondary" : result.streamError || state?.lastError ? "warning-light" : live && result.stream ? "success-light" : "info-light"}>{collectorEnabled === undefined ? "Проверяем сборщик" : !collectorEnabled ? "Сборщик выключен" : result.streamError ? "Переподключение" : state?.lastError ? "Ошибка сбора" : live && result.stream ? "Live подключён" : "История"}</Badge><span>Последний сбор: {formatLogTime(state?.lastCollectedAt ?? result.summary?.states.map(s => s.lastCollectedAt).filter((s): s is string => !!s).sort().at(-1) ?? null)}</span>{live && <Button size="sm" variant="outline" onClick={() => { if (paused) setPaused(false); else setPaused(true) }}>{paused ? <PlayIcon /> : <PauseIcon />}{paused ? `Новых событий: ${result.pendingCount}` : "Пауза"}</Button>}</div>
<div role="status" className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
{result.streamStopped || result.streamError
? <Badge variant="warning-light">{result.streamStopped ? "Live остановлен" : "Переподключение"}</Badge>
: <Badge variant={!collectorEnabled ? "secondary" : state?.lastError ? "warning-light" : live && result.stream ? "success-light" : "info-light"}>
{collectorEnabled === undefined ? "Проверяем сборщик" : !collectorEnabled ? "Сборщик выключен" : state?.lastError ? "Ошибка сбора" : live && result.stream ? "Live подключён" : "История"}
</Badge>}
<span>Последний сбор: {formatLogTime(state?.lastCollectedAt ?? result.summary?.states.map(s => s.lastCollectedAt).filter((s): s is string => !!s).sort().at(-1) ?? null)}</span>
{live && <Button size="sm" variant="outline" onClick={() => { if (paused) setPaused(false); else setPaused(true) }}>{paused ? <PlayIcon /> : <PauseIcon />}{paused ? `Новых событий: ${result.pendingCount}` : "Пауза"}</Button>}
</div>
{live && collectorEnabled === true && result.streamReceivedAt !== null && <p aria-label="Получение live-логов" className="text-xs text-muted-foreground">
Получено (live-поток): <time dateTime={new Date(result.streamReceivedAt).toISOString()}>{formatLogTime(new Date(result.streamReceivedAt).toISOString())}</time>
</p>}
{collectorEnabled === false && <Alert variant="info"><AlertTitle>История доступна, сбор новых событий выключен</AlertTitle><AlertDescription>Администратор может включить коллектор в разделе <Link className="underline" href="/data-collection#router-logs">«Сбор данных»</Link>.</AlertDescription></Alert>}
{(result.streamError || state?.lastError) && <Alert variant="warning"><AlertTitle>Live требует внимания</AlertTitle><AlertDescription>{state?.lastError ?? result.streamError}</AlertDescription></Alert>}
{state?.gapAt && <Alert variant="warning"><AlertTitle>Возможен разрыв истории</AlertTitle><AlertDescription>Буфер изменился без пересечения с предыдущим снимком: {formatLogTime(state.gapAt)}. Количество недоступных событий неизвестно.</AlertDescription></Alert>}
+42
View File
@@ -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<AbortController | null>(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 <div className="flex flex-col items-start gap-2">
<Button variant="outline" disabled={busy} aria-busy={busy} onClick={() => { void download() }}>{busy ? "Скачивание…" : "Скачать файл"}</Button>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<p role="status" className="text-xs text-muted-foreground">{busy ? "Получаем файл с проверкой доступа…" : saved ? "Файл передан браузеру для сохранения." : error ? "" : "Доступ и срок хранения проверяются при скачивании."}</p>
</div>
}
export function ArtifactDownloads({ api, operation }: { api: McpApi; operation: Record<string, unknown> }) {
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 <div className="flex flex-col gap-3 rounded-md border p-3">
<h3 className="text-sm font-medium">Файлы операции</h3>
{receipts.length ? receipts.map(([id, receipt]) => <ArtifactDownload key={id} api={api} receipt={receipt} />) :
<p role="status" className="text-sm text-muted-foreground">Файл больше недоступен. Проверьте срок хранения и права подключения.</p>}
</div>
}
+156
View File
@@ -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<string, unknown>
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 <label className="flex items-center gap-2 text-sm"><Checkbox checked={checked} onCheckedChange={value => onChange(value === true)} />{label}</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<State | null>(null)
const [bridgeId, setBridgeId] = useState("")
const [draft, setDraft] = useState<BridgeVlanDesired | null>(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 className="flex min-w-0 flex-col gap-1 text-sm">{label}<select className={selectClass} value={keyOf(value)} onChange={event => {
const item = options.find(item => keyOf(item) === event.target.value)
if (item) onChange({ resource: item.resource, id: item.id })
}}>{portOptions.map(item => <option key={keyOf(item)} value={keyOf(item)}>{item.name} · {item.resource} {item.id}</option>)}</select></label>
const membership = (label: string, selected: Reference[], onChange: (value: Reference[]) => void) => <fieldset className="flex flex-col gap-2"><legend className="mb-2 text-sm font-medium">{label}</legend><div className="flex max-h-40 flex-wrap gap-3 overflow-auto">{options.filter(item => memberOptions.includes(item) || selected.some(value => keyOf(value) === keyOf(item))).map(item => <Choice key={keyOf(item)} label={item.name} checked={selected.some(value => keyOf(value) === keyOf(item))} onChange={checked => onChange(checked ? [...selected, { resource: item.resource, id: item.id }] : selected.filter(value => keyOf(value) !== keyOf(item)))} />)}</div></fieldset>
return <section className="flex flex-col gap-4 rounded-xl border p-4" aria-label="Связанная настройка Bridge VLAN" aria-busy={loading || busy}>
<h3 className="font-semibold">Мост, порты и VLAN</h3>
<p className="text-sm text-muted-foreground">Подготовьте единый план VLAN filtering, PVID и участников. Проверяется доступ к управлению устройством. Без независимого канала используется основной адрес с обязательным подтверждением человеком. Подтверждение и применение выполняются отдельно в планах.</p>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<label className="flex min-w-0 flex-1 flex-col gap-1 text-sm">Существующий мост<select className={selectClass} value={bridgeId} disabled={!state || busy} onChange={event => chooseBridge(event.target.value)}><option value="">Выберите мост</option>{state?.bridges.map(row => <option key={text(row, ".id")} value={text(row, ".id")}>{text(row, "name")} · {text(row, ".id")}</option>)}</select></label>
<Button variant="outline" className="self-start" disabled={loading || busy || !connectionId || !serverId} onClick={() => setReload(value => value + 1)}>Перечитать и сбросить черновик</Button>
</div>
{loading && <p role="status" className="text-sm text-muted-foreground">Чтение состояния…</p>}
{draft && state && <fieldset disabled={busy || loading} className="flex min-w-0 flex-col gap-4">
<div className="flex flex-wrap items-end gap-4"><Choice label="VLAN filtering" checked={draft.filtering} onChange={filtering => edit(value => ({ ...value, filtering }))} /><label className="flex flex-col gap-1 text-sm">PVID моста<Input type="number" min={1} max={4094} value={draft.pvid} onChange={event => edit(value => ({ ...value, pvid: Number(event.target.value) }))} /></label></div>
<h4 className="font-medium">Статические порты</h4>
{draft.ports.map((port, index) => <fieldset key={port.id ?? `new-${index}`} className="flex min-w-0 flex-col gap-3 rounded-lg border p-3"><legend className="px-1 text-sm">{port.id ?? "Новый порт"}</legend>
<div className="grid gap-3 sm:grid-cols-3">{interfaceSelect("Интерфейс порта", port.interface, reference => edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, interface: reference } : item) })))}
<label className="flex flex-col gap-1 text-sm">PVID порта<Input type="number" min={1} max={4094} value={port.pvid} onChange={event => edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, pvid: Number(event.target.value) } : item) }))} /></label>
<label className="flex min-w-0 flex-col gap-1 text-sm">Типы кадров<select className={selectClass} value={port.frameTypes} onChange={event => edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, frameTypes: event.target.value as typeof port.frameTypes } : item) }))}><option value="admit-all">Все</option><option value="admit-only-vlan-tagged">Только tagged</option><option value="admit-only-untagged-and-priority-tagged">Untagged и priority tagged</option></select></label></div>
<div className="flex flex-wrap items-center gap-3"><Choice label="Ingress filtering" checked={port.ingressFiltering} onChange={ingressFiltering => edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, ingressFiltering } : item) }))} /><Choice label="Отключён" checked={port.disabled} onChange={disabled => edit(value => ({ ...value, ports: value.ports.map((item, i) => i === index ? { ...item, disabled } : item) }))} /><Button variant="outline" onClick={() => edit(value => ({ ...value, ports: value.ports.filter((_, i) => i !== index), removePortIds: port.id ? [...value.removePortIds, port.id] : value.removePortIds }))}>Удалить порт из плана</Button></div>
</fieldset>)}
<Button variant="outline" className="self-start" disabled={!nextPort} onClick={() => { if (nextPort) edit(value => ({ ...value, ports: [...value.ports, { interface: { resource: nextPort.resource, id: nextPort.id }, pvid: 1, ingressFiltering: true, frameTypes: "admit-all", disabled: false }] })) }}>Добавить порт</Button>
<h4 className="font-medium">Статические участники VLAN</h4>
{draft.vlans.map((vlan, index) => {
const update = (patch: Partial<typeof vlan>) => edit(value => ({ ...value, vlans: value.vlans.map((item, i) => i === index ? { ...item, ...patch } : item) }))
return <fieldset key={vlan.id ?? `new-${index}`} className="flex min-w-0 flex-col gap-3 rounded-lg border p-3"><legend className="px-1 text-sm">{vlan.id ?? "Новая запись VLAN"}</legend>
<label className="flex flex-col gap-1 text-sm">VLAN ID или диапазоны (например, 10,20–30)<Input value={vlan.vlanIds} placeholder="10,20-30" onChange={event => update({ vlanIds: event.target.value })} /></label>
{membership("Tagged, включая CPU-порт моста при необходимости", vlan.tagged, tagged => update({ tagged }))}
{membership("Untagged", vlan.untagged, untagged => update({ untagged }))}
<div className="flex flex-wrap items-center gap-3"><Choice label="Отключена" checked={vlan.disabled} onChange={disabled => update({ disabled })} /><Button variant="outline" onClick={() => edit(value => ({ ...value, vlans: value.vlans.filter((_, i) => i !== index), removeVlanIds: vlan.id ? [...value.removeVlanIds, vlan.id] : value.removeVlanIds }))}>Удалить запись VLAN из плана</Button></div>
</fieldset>
})}
<Button variant="outline" className="self-start" onClick={() => edit(value => ({ ...value, vlans: [...value.vlans, { vlanIds: "", tagged: [], untagged: [], disabled: false }] }))}>Добавить запись VLAN</Button>
{state.ports.filter(row => row.bridge === bridgeName && dynamic(row)).map(row => <p key={`port-${text(row, ".id")}`} className="text-sm text-muted-foreground">Динамический порт {text(row, "interface")} ({text(row, ".id")}) — только чтение</p>)}
{state.vlans.filter(row => row.bridge === bridgeName && dynamic(row)).map(row => <p key={`vlan-${text(row, ".id")}`} className="text-sm text-muted-foreground">Динамический VLAN {text(row, "vlan-ids")} ({text(row, ".id")}) — только чтение</p>)}
{(draft.removePortIds.length > 0 || draft.removeVlanIds.length > 0) && <p className="text-sm">Явное удаление портов: {draft.removePortIds.join(", ") || "нет"}. Записей VLAN: {draft.removeVlanIds.join(", ") || "нет"}. Для отмены удаления перечитайте состояние.</p>}
<Button className="self-start" disabled={busy || loading} onClick={() => { void prepare() }}>{busy ? "Подготовка…" : "Подготовить связанный план VLAN"}</Button>
</fieldset>}
{receipt && <p role="status" className="break-all text-sm">Подготовлен план {receipt}. <Link className="underline" href="/mcp?tab=plans">Открыть планы для проверки и подтверждения</Link></p>}
</section>
}
+102
View File
@@ -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<File | null>(null)
const [archive, setArchive] = useState<Awaited<ReturnType<McpApi["uploadRestoreArchive"]>> | null>(null)
const [operationId, setOperationId] = useState("")
const [result, setResult] = useState<unknown>(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
const [clock, setClock] = useState(0)
const activeRequest = useRef<AbortController | null>(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<typeof setTimeout>
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<unknown>) => {
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 <section className="flex flex-col gap-3 rounded-xl border p-4" aria-labelledby="mcp-database-restore-title">
<h2 id="mcp-database-restore-title" className="font-semibold">Восстановление БД через MCP</h2>
<p className="text-sm text-muted-foreground">Архив PostgreSQL загружает администратор. Модель получает ссылку и SHA-256. Выполнение требует отдельного подтверждения в планах. После восстановления прежний MCP-доступ отзывается, а результат хранится во внешней квитанции.</p>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<label className="flex flex-col gap-1 text-sm">Подключение для восстановления
<select className="h-9 rounded-md border bg-background px-3" value={connectionId} disabled={busy} onChange={event => { setConnectionId(event.target.value); clearResult() }}><option value="">Выберите свой глобальный допуск</option>{connections.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select>
</label>
<label className="flex flex-col gap-1 text-sm">Архив PostgreSQL, до 64 МиБ
<Input type="file" accept=".dump,.backup" disabled={busy} onChange={event => { setFile(event.target.files?.[0] ?? null); setArchive(null); clearResult() }} />
</label>
{file && !validFile && <p className="text-sm text-destructive">Выберите непустой архив размером до 64 МиБ.</p>}
<div className="flex flex-wrap gap-2">
<Button variant="outline" disabled={busy || !validFile} onClick={upload}>Загрузить архив</Button>
<Button disabled={busy || !archive || expired || !connectionId} onClick={prepare}>Подготовить план восстановления БД</Button>
</div>
{archive && <p className="break-all text-xs text-muted-foreground">SHA-256: {archive.sha256} · Допуск до {new Date(archive.expiresAt).toLocaleString()}</p>}
{expired && <p role="status" className="text-sm text-muted-foreground">Срок архива истёк. Загрузите архив снова для нового плана.</p>}
<label className="flex flex-col gap-1 text-sm">ID операции восстановления БД<Input value={operationId} disabled={busy} aria-invalid={!!receiptId && !validReceiptId} onChange={event => { setOperationId(event.target.value); clearResult() }} /></label>
<Button className="self-start" variant="outline" disabled={busy || !validReceiptId} onClick={() => { void run(signal => api.restoreReceipt(receiptId, signal)) }}>Прочитать внешнюю квитанцию</Button>
{result !== null && <pre role="status" className="max-h-60 overflow-auto whitespace-pre-wrap break-all text-xs">{JSON.stringify(result, null, 2)}</pre>}
</section>
}
+802
View File
@@ -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<string, unknown>
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 <div className="flex flex-col gap-1"><Badge variant={label === "Активен" ? "success-light" : "warning-light"}>{label}</Badge><span className="text-xs text-muted-foreground">{reason}</span></div>
}
function useQuery<T>(load: (signal: AbortSignal) => Promise<T>, 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 <Frame dense><FrameHeader className="flex-row flex-wrap items-center justify-between gap-3"><div><FrameTitle>{title}</FrameTitle>{description && <FrameDescription>{description}</FrameDescription>}</div>{actions}</FrameHeader><FramePanel className="flex min-w-0 flex-col gap-4 p-4">{children}</FramePanel></Frame>
}
function ErrorMessage({ message }: { message: string }) { return message ? <p role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{message}</p> : null }
function Field({ label, children }: { label: string; children: ReactNode }) { return <label className="flex min-w-0 flex-col gap-1.5 text-sm"><span>{label}</span>{children}</label> }
function Choice({ label, checked, onChange }: { label: string; checked: boolean; onChange: (value: boolean) => void }) { return <label className="flex items-center gap-2 text-sm"><Checkbox checked={checked} onCheckedChange={checked => onChange(!!checked)} />{label}</label> }
function NativeSelect({ label, value, onChange, children }: { label: string; value: string; onChange: (value: string) => void; children: ReactNode }) {
return <Field label={label}><select aria-label={label} className="h-9 min-w-0 rounded-md border border-input bg-background px-2 text-sm" value={value} onChange={event => onChange(event.target.value)}>{children}</select></Field>
}
function Grid({ items, columns, loading, total, onSelect }: { items: RecordRow[]; columns: ColumnDef<DataGridFeatures, RecordRow>[]; 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 <DataGrid table={table} recordCount={total ?? items.length} isLoading={loading} onRowClick={onSelect} i18n={{ labels: DATA_GRID_LABELS_RU }} emptyMessage="Записей пока нет" tableLayout={{ dense: true, width: "fixed" }}><DataGridContainer><DataGridScrollArea className="max-h-[32rem]"><DataGridTable /></DataGridScrollArea></DataGridContainer></DataGrid>
}
type DeviceResource = Awaited<ReturnType<McpApi["deviceCatalog"]>>["resources"][number]
function DeviceManagement({ api }: { api: McpApi }) {
const connections = useQuery(useCallback(signal => api.connections(signal), [api]))
const [connectionId, setConnectionId] = useState("")
return <Panel title="Интерфейсы и адреса" description="Чтение и подготовка изменений от имени выбранного подключения. Подтверждение и применение — на вкладке «Планы и операции»."><ErrorMessage message={connections.error} /><NativeSelect label="Подключение для управления интерфейсами" value={connectionId} onChange={setConnectionId}><option value="">Выберите подключение</option>{connections.data?.connections.filter(connection => connection.ownerId === getClaims()?.sub && connection.policy.status === "active").map(connection => <option key={connection.id} value={connection.id}>{connection.name}</option>)}</NativeSelect>{connectionId && <DeviceCatalog key={connectionId} api={api} connectionId={connectionId} />}</Panel>
}
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 <><ErrorMessage message={catalog.error} /><div className="grid gap-3 sm:grid-cols-2"><NativeSelect label="Сервер интерфейсов" value={serverId} onChange={setServerId}><option value="">Выберите сервер</option>{catalog.data?.servers.map(server => <option key={server.id} value={String(server.id)} disabled={!server.enabled}>{server.name} · {server.host}</option>)}</NativeSelect><NativeSelect label="Тип объектов устройства" value={resourceId} onChange={setResourceId}><option value="">Выберите тип</option>{catalog.data?.resources.filter(resource => resource.read).map(resource => <option key={resource.id} value={resource.id}>{resource.title}</option>)}</NativeSelect></div>{catalog.data && !catalog.data.resources.some(resource => resource.read) && <p className="text-sm text-muted-foreground">Подключению не выданы инструменты чтения интерфейсов.</p>}{resourceId === "bridge" && serverId && catalog.data?.servers.some(server => String(server.id) === serverId && server.enabled) && <BridgeVlanWorkflow key={`vlan:${connectionId}:${serverId}`} api={api} connectionId={connectionId} serverId={serverId} />}{resource && serverId && catalog.data?.servers.some(server => String(server.id) === serverId && server.enabled) && <DeviceEditor key={`${serverId}:${resourceId}`} api={api} connectionId={connectionId} serverId={serverId} resource={resource} />}</>
}
function DeviceEditor({ api, connectionId, serverId, resource }: { api: McpApi; connectionId: string; serverId: string; resource: DeviceResource }) {
const [offset, setOffset] = useState(0), [editing, setEditing] = useState<RecordRow | "new" | null>(null), [draft, setDraft] = useState<Record<string, unknown>>({})
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 <><ErrorMessage message={rows.error || error} />{receipt && <p role="status" className="text-sm">{receipt}</p>}<div className="flex flex-wrap items-center justify-between gap-2"><p className="text-sm text-muted-foreground">Объектов: {rows.data?.total ?? "…"}. Выберите строку для просмотра и подготовки изменения.</p>{resource.create && <Button variant="outline" disabled={busy} onClick={() => open("new")}><PlusIcon />Создать объект</Button>}</div><Grid items={rows.data?.items ?? []} loading={!rows.data && !rows.error} total={rows.data?.total} columns={[{ id: "nativeId", header: "ID", cell: ({ row }) => 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) }} /><div className="flex gap-2"><Button variant="outline" disabled={busy || offset === 0} onClick={() => { setOffset(Math.max(0, offset - 100)); setEditing(null) }}>Предыдущие объекты</Button><Button variant="outline" disabled={busy || rows.data?.nextOffset == null} onClick={() => { if (rows.data?.nextOffset != null) setOffset(rows.data.nextOffset); setEditing(null) }}>Следующие объекты</Button></div>{editing && <div className="flex flex-col gap-4 rounded-md border p-4"><p className="font-medium">{editing === "new" ? "Новый объект" : `Объект ${String(current?.[".id"])}`}</p>{current && <details><summary className="cursor-pointer text-sm">Текущие свойства</summary><pre className="max-h-60 overflow-auto whitespace-pre-wrap break-all text-xs">{pretty(current)}</pre></details>}{protectedRow ? <p className="text-sm">Системный или динамический объект доступен для чтения.</p> : <><p className="text-xs text-muted-foreground">В план попадут только заполненные изменения. Пустой выбор оставляет свойство без изменения; при создании действует настройка устройства.</p><div className="grid gap-3 sm:grid-cols-2">{editableFields.map(field => <Field key={field.key} label={`${field.key}${editing === "new" && field.requiredOnCreate ? " *" : ""}`}>{field.type === "boolean" || field.options ? <select aria-label={field.key} className="h-9 min-w-0 rounded-md border border-input bg-background px-2 text-sm" value={String(draft[field.key] ?? "")} disabled={busy || editing !== "new" && !resource.update} onChange={event => change(field.key, event.target.value === "" ? undefined : field.type === "boolean" ? event.target.value === "true" : event.target.value)}><option value="">{ethernetDisabledUnknown && field.key === "disabled" ? "Текущее значение неизвестно" : current ? `Сейчас: ${String(current[field.key])}` : "По умолчанию устройства"}</option>{(field.options ?? ["true", "false"]).map(value => <option key={value} value={value}>{value}</option>)}</select> : <Input aria-label={field.key} type={field.type === "number" ? "number" : "text"} min={field.min} max={field.max} maxLength={field.maxLength} disabled={busy || editing !== "new" && !resource.update} placeholder={current ? String(current[field.key] ?? "") : ""} value={String(draft[field.key] ?? "")} onChange={event => change(field.key, field.type === "number" ? event.target.value === "" ? undefined : Number(event.target.value) : event.target.value)} />}</Field>)}</div>
{ethernetDisabledUnknown && draft.disabled !== undefined && <p className="text-sm text-muted-foreground">Исходное состояние неизвестно. Для этого изменения обратный план недоступен.</p>}
</>}<div className="flex flex-wrap gap-2">{!protectedRow && (editing === "new" ? resource.create : resource.update) && <Button disabled={busy || !Object.keys(draft).length} onClick={() => { void prepare(editing === "new" ? "create" : "update") }}>Подготовить план изменения</Button>}{current && !protectedRow && resource.delete && <Button variant="destructive" disabled={busy} onClick={() => { void prepare("delete") }}>Подготовить план удаления</Button>}<Button variant="outline" disabled={busy} onClick={() => setEditing(null)}>Закрыть объект</Button></div></div>}</>
}
function TokenDialog({ token, close, connectionName }: { token: string; close: () => void; connectionName?: string }) {
return <Dialog open={!!token} onOpenChange={open => { if (!open) close() }}><DialogContent className="sm:max-w-xl"><DialogHeader><DialogTitle>Доступ создан</DialogTitle><DialogDescription>{connectionName && `Подключение «${connectionName}». `}Сохраните токен в настройках AI-клиента. Повторно посмотреть его нельзя.</DialogDescription></DialogHeader><Input aria-label="Одноразовый токен MCP" readOnly type="password" value={token} /><Button onClick={() => { void navigator.clipboard.writeText(token).then(() => toast.success("Токен скопирован"), () => toast.error("Не удалось скопировать токен")) }}><CopyIcon />Копировать</Button><Button variant="outline" onClick={close}>Закрыть и скрыть токен</Button></DialogContent></Dialog>
}
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<McpConnection["policy"]["mode"]>(editing?.policy.mode ?? "observer")
const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState<string[]>(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 <Dialog open onOpenChange={open => { if (!open && !busy) close() }}><DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl"><DialogHeader><DialogTitle>{editing ? "Изменить разрешения" : "Новое подключение"}</DialogTitle><DialogDescription>Шаг {step} из 4 · доступ ограничивается правами текущего владельца.</DialogDescription></DialogHeader><ErrorMessage message={error} />
{step === 1 && <><Field label="Название"><Input value={name} onChange={event => setName(event.target.value)} placeholder="Агент диагностики" /></Field><Field label="Срок действия (UTC)"><Input type="datetime-local" value={expires} onChange={event => setExpires(event.target.value)} /></Field><NativeSelect label="Режим управления" value={mode} onChange={value => setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => <option key={value} value={value}>{title}</option>)}</NativeSelect></>}
{step === 2 && <><Field label="ID разрешённых серверов через запятую"><Input value={serverText} onChange={event => setServerText(event.target.value)} placeholder="1, 2" /></Field><Choice label="Разрешить выбранные глобальные операции" checked={global} onChange={setGlobal} /><div className="grid max-h-80 gap-2 overflow-y-auto sm:grid-cols-2">{eligible.map(operation => <Choice key={operation.id} label={operation.title} checked={selected.includes(operation.id)} onChange={() => toggle(operation.id)} />)}</div><p className="text-xs text-muted-foreground">Новые инструменты не добавляются в доступ автоматически. Для применения планов выберите также инструменты просмотра и применения.</p></>}
{step === 3 && <><div className="grid gap-3 sm:grid-cols-2">{Object.entries(limits).map(([key, value]) => <Field key={key} label={({ callsPerMinute: "Вызовов в минуту", concurrentReads: "Одновременных чтений", mutationsPerHour: "Изменений в час", serversPerPlan: "Серверов на план", objectsPerPlan: "Объектов на план" } as Record<string, string>)[key]}><Input type="number" min={1} value={value} onChange={event => setLimits(current => ({ ...current, [key]: Number(event.target.value) }))} /></Field>)}</div><NativeSelect label="Опасные действия" value={danger} onChange={value => setDanger(value as typeof danger)}><option value="approval">Всегда подтверждать</option><option value="explicit-allow">Автономно для явно выбранных действий</option></NativeSelect>{danger === "explicit-allow" && eligible.filter(operation => operation.risk === "dangerous" && selected.includes(operation.id)).map(operation => <Choice key={operation.id} label={operation.title} checked={dangerIds.includes(operation.id)} onChange={checked => setDangerIds(ids => checked ? [...ids, operation.id] : ids.filter(id => id !== operation.id))} />)}</>}
{step === 4 && <div className="space-y-3 text-sm"><p><strong>{name || "Без названия"}</strong> · {modeLabels[mode]}</p><p>Серверы: {serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.</p><p>Защита объектов продолжает действовать независимо от автономных разрешений.</p><p>После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».</p></div>}
<div className="flex flex-wrap justify-between gap-2"><Button variant="outline" disabled={busy} onClick={() => step > 1 ? setStep(step - 1) : close()}>{step > 1 ? "Назад" : "Отмена"}</Button>{step < 4 ? <Button onClick={() => setStep(step + 1)}>Далее</Button> : <Button disabled={busy} onClick={() => { void save() }}>{busy ? "Сохранение…" : "Сохранить доступ"}</Button>}</div>
</DialogContent></Dialog>
}
function Connections({ api, operations }: { api: McpApi; operations: McpOperationDescriptor[] }) {
const query = useQuery(useCallback(signal => api.connections(signal), [api]))
const [editing, setEditing] = useState<McpConnection | "new" | null>(null), [token, setToken] = useState("")
const admin = can("mm:mcp:admin")
const refresh = query.refresh
const act = useCallback(async (work: () => Promise<unknown>) => { try { await work(); refresh() } catch (error) { toast.error(errorText(error)) } }, [refresh])
const columns = useMemo<ColumnDef<DataGridFeatures, RecordRow>[]>(() => [
{ 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 <div className="flex flex-col items-start gap-1"><span>{connection.name}</span><div className="flex flex-wrap gap-x-2 text-xs">
{admin && <Link className="underline underline-offset-2" href={`/mcp?tab=permissions&connection=${connection.id}`}>Проверить права</Link>}
<Link className="underline underline-offset-2" href={`/mcp?${journal}`}>Журнал подключения</Link>
</div></div>
} },
{ id: "mode", header: "Режим", cell: ({ row }) => modeLabels[(row.original.policy as McpConnection["policy"]).mode] },
{ id: "status", header: "Состояние доступа", size: 260, cell: ({ row }) => <ConnectionAccessStatus connection={row.original as unknown as McpConnection} /> },
{ 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 <div className="flex flex-col gap-1"><span className="text-xs">{date(connection.ownerValidUntil)}</span>{connection.ownerId === getClaims()?.sub && <Button size="sm" variant="outline" disabled={!connection.generationValid || connection.policy.status === "revoked"} onClick={() => { void act(() => api.revalidate(connection.id)) }}>Обновить мои права</Button>}</div> } },
{ id: "actions", header: "Действия", size: 350, cell: ({ row }) => { const connection = row.original as unknown as McpConnection; return admin && <div className="flex flex-wrap gap-1"><Button size="sm" variant="outline" onClick={() => setEditing(connection)}>Разрешения</Button><Button size="sm" variant="outline" disabled={connection.policy.status === "revoked"} onClick={() => { void act(() => api.status(connection.id, connection.policy.status === "active" ? "paused" : "active")) }}>{connection.policy.status === "active" ? "Пауза" : "Включить"}</Button><Button size="sm" variant="outline" disabled={connection.policy.status === "revoked"} onClick={() => { if (window.confirm("Отозвать доступ подключения и все его токены?")) void act(() => api.status(connection.id, "revoked")) }}>Отозвать</Button><Button size="sm" variant="ghost" disabled={connection.policy.status === "revoked"} onClick={() => { if (window.confirm("Заменить токен? Старый токен перестанет работать.")) void act(async () => setToken((await api.rotate(connection.id)).token)) }}>Новый токен</Button></div> } },
], [api, admin, act])
return <><Panel title="Подключения" description="Токены, сроки и разрешения AI-клиентов" actions={admin && <Button onClick={() => setEditing("new")}><PlusIcon />Выдать доступ</Button>}><ErrorMessage message={query.error} /><Grid items={(query.data?.connections ?? []) as unknown as RecordRow[]} columns={columns} loading={!query.data && !query.error} /><p className="text-sm text-muted-foreground">HTTP endpoint: адрес backend + /mcp. Для stdio используйте MCP_URL и MCP_TOKEN с командой npm --prefix backend run mcp:stdio.</p></Panel>{editing && <ConnectionForm api={api} operations={operations} editing={editing === "new" ? undefined : editing} close={() => setEditing(null)} created={value => { setEditing(null); if (value) setToken(value); query.refresh() }} />}<TokenDialog token={token} close={() => 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<McpApi["grant"]>[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 <Panel title="Проверка подключения и временные допуски" description="Допуск с отдельным токеном может только сузить основной доступ и действует не более 24 часов">
<ErrorMessage message={connections.error} />
<NativeSelect label="Подключение для проверки" value={selected} onChange={setSelected}>
<option value="">Выберите подключение</option>
{connections.data?.connections.map(connection => <option key={connection.id} value={connection.id}>{connection.name}</option>)}
</NativeSelect>
{connection && <ConnectionAccessTools key={connection.id} api={api} connection={connection} issue={issue} grantBusy={grantBusy} />}
{issued && <TokenDialog token={issued.token} connectionName={issued.connectionName} close={() => { setIssued(null); releaseGrant() }} />}
</Panel>
}
function ConnectionAccessTools({ api, connection, issue, grantBusy }: {
api: McpApi
connection: McpConnection
issue: (grant: Parameters<McpApi["grant"]>[1]) => Promise<void>
grantBusy: boolean
}) {
const [result, setResult] = useState<Awaited<ReturnType<McpApi["check"]>> | null>(null)
const [operations, setOperations] = useState<string[]>([]), [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 <>
<ErrorMessage message={grants.error} />
<p className="text-sm text-muted-foreground">Права владельца подтверждены до {date(connection.ownerValidUntil)}. Для продления войдите с актуальными правами портала; старые планы и допуски контроллера потребуется подготовить заново.</p>
<Button variant="outline" className="self-start" disabled={connection.ownerId !== getClaims()?.sub} onClick={() => { void api.revalidate(connectionId).then(() => { grants.refresh(); toast.success("Права владельца обновлены") }, error => toast.error(errorText(error))) }}>Подтвердить текущие права владельца</Button>
<Button variant="outline" className="self-start" onClick={() => { void check() }}>Проверить готовность доступа</Button>
{result !== null && <>
{result.protocolProbe?.capabilitiesRead && <p role="status" className="text-sm text-muted-foreground">
{({ passed: "Проверочное чтение возможностей прошло.", failed: "Проверочное чтение возможностей завершилось ошибкой.", skipped: "Проверочное чтение возможностей пропущено." })[result.protocolProbe.capabilitiesRead]}
</p>}
<pre className="overflow-auto rounded bg-muted p-3 text-xs">{pretty(result)}</pre>
</>}
<div className="grid gap-3 sm:grid-cols-2">
<Field label={`Серверы допуска (доступны: ${connection.policy.scope.serverIds.join(", ")})`}><Input value={serverText} onChange={event => setServerText(event.target.value)} placeholder="ID через запятую" /></Field>
<Field label="Срок допуска, минут"><Input type="number" min={1} max={1440} value={minutes} onChange={event => setMinutes(Number(event.target.value))} /></Field>
</div>
{connection.policy.scope.allowGlobal && <Choice label="Разрешить глобальные действия в допуске" checked={global} onChange={setGlobal} />}
<div className="grid max-h-60 gap-2 overflow-y-auto sm:grid-cols-2">{connection.policy.scope.operationIds.map(id => <Choice key={id} label={id} checked={operations.includes(id)} onChange={checked => setOperations(values => checked ? [...values, id] : values.filter(value => value !== id))} />)}</div>
<Button className="self-start" disabled={grantBusy || !operations.length || connection.policy.status !== "active"} onClick={create}>Выдать временный допуск</Button>
{grants.data?.grants.map(grant => <div key={grant.id} className="flex flex-wrap items-center justify-between gap-2 rounded border p-3 text-sm">
<span>До {date(grant.grant.expiresAt)} · {grant.revoked_at ? "отозван" : "выдан"}</span>
<Button size="sm" variant="outline" disabled={!!grant.revoked_at} onClick={() => { void api.revokeGrant(grant.id).then(grants.refresh, error => toast.error(errorText(error))) }}>Отозвать допуск</Button>
</div>)}
</>
}
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<string[]>(original?.excludedCandidateIds ?? [])
const [sla, setSla] = useState({ ping: original?.maxPingMs?.toString() ?? "", loss: original?.maxLossPct?.toString() ?? "", speed: original?.minBandwidthMbps?.toString() ?? "" })
const [candidates, setCandidates] = useState<CandidateForm[]>(() => 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 <Dialog open onOpenChange={open => { if (!open && !busy) close() }}><DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-4xl"><DialogHeader><DialogTitle>{editing ? "Изменить профиль Route AI" : "Новый профиль Route AI"}</DialogTitle><DialogDescription>Проверьте пути и допуск. Сохранение создаёт план для отдельного подтверждения и применения.</DialogDescription></DialogHeader><ErrorMessage message={error || connections.error} />{plan ? <><p>Создан план {plan}. Откройте «Планы и операции», проверьте изменения, подтвердите и примените план.</p><Button onClick={close}>Закрыть</Button></> : <><div className="grid gap-3 sm:grid-cols-2"><NativeSelect label="Подключение контроллера" value={connectionId} onChange={setConnectionId}><option value="">Выберите подключение владельца</option>{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 => <option key={connection.id} value={connection.id}>{connection.name}</option>)}</NativeSelect><Field label="Название профиля"><Input value={name} onChange={event => setName(event.target.value)} /></Field><Field label="ID домашнего сервера"><Input type="number" min={1} value={serverId} onChange={event => setServerId(event.target.value)} /></Field><Field label="Community"><Input value={community} onChange={event => setCommunity(event.target.value)} placeholder="65000:10" /></Field><NativeSelect label="Семейство адресов" value={family} onChange={value => setFamily(value as typeof family)}><option value="ipv4">IPv4</option><option value="ipv6">IPv6</option></NativeSelect><Field label="Таблица маршрутизации"><Input value={table} onChange={event => setTable(event.target.value)} /></Field><Field label="VRF диагностических проб"><Input value={probeVrf} onChange={event => setProbeVrf(event.target.value)} /></Field></div>
<p className="text-sm text-muted-foreground">Таблица определяет установку маршрутов. VRF диагностических проб определяет контекст измерений и задаётся отдельно от транспортной VRF BGP.</p>
<Choice label="Привязать профиль к конкретному BGP-подключению RouterOS" checked={bindBgp} onChange={setBindBgp} />
{bindBgp ? <fieldset className="rounded-lg border p-3"><legend className="px-1 text-sm font-medium">Контекст BGP</legend><div className="grid gap-3 sm:grid-cols-2">{([{ key: "connectionId", title: "ID BGP-подключения RouterOS" }, { key: "instance", title: "Экземпляр BGP" }, { key: "inputChain", title: "Входящая цепочка BGP" }, { key: "vrf", title: "Транспортная VRF BGP" }] as const).map(field => <Field key={field.key} label={field.title}><Input value={bgp[field.key]} placeholder={field.key === "connectionId" ? "*A" : undefined} onChange={event => setBgp(values => ({ ...values, [field.key]: event.target.value }))} /></Field>)}</div><p className="mt-2 text-sm text-muted-foreground">Заполните все поля. Снятие привязки явно удалит контекст BGP из плана профиля.</p></fieldset> : <p className="text-sm text-muted-foreground">Подключение BGP будет определено по наблюдаемой конфигурации; неоднозначная привязка блокирует переключение.</p>}
{controllerReason && <p role="status" className="text-sm text-muted-foreground">{controllerReason} Профиль можно сохранить с выключенным контроллером для анализа и подготовки предложений.</p>}
{candidates.map((candidate, index) => <fieldset key={candidate.id} className="rounded-lg border p-3"><legend className="px-1 text-sm font-medium">Путь {index + 1} · {candidate.id}</legend><div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{([{ 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 => <Field key={field.key} label={field.title}><Input value={candidate[field.key] ?? ""} onChange={event => setCandidates(values => values.map(value => value.id === candidate.id ? { ...value, [field.key]: event.target.value } : value))} /></Field>)}<NativeSelect label="Тип шлюза" value={candidate.gatewayRef.resource} onChange={resource => setCandidates(values => values.map(value => value.id === candidate.id ? { ...value, gatewayRef: { ...value.gatewayRef, resource: resource as typeof value.gatewayRef.resource } } : value))}><option value="gre">GRE</option><option value="ipv4_route">Рекурсивный IPv4</option><option value="ipv6_route">Рекурсивный IPv6</option></NativeSelect><Field label="ID шлюза на устройстве"><Input value={candidate.gatewayRef.id} onChange={event => setCandidates(values => values.map(value => value.id === candidate.id ? { ...value, gatewayRef: { ...value.gatewayRef, id: event.target.value } } : value))} /></Field></div><div className="mt-3 flex flex-wrap items-center gap-3"><Choice label="Исключить путь" checked={excluded.includes(candidate.id)} onChange={checked => setExcluded(values => checked ? [...values, candidate.id] : values.filter(value => value !== candidate.id))} /><Button size="sm" variant="ghost" disabled={candidates.length === 1} onClick={() => { setCandidates(values => values.filter(value => value.id !== candidate.id)); setExcluded(values => values.filter(value => value !== candidate.id)); if (pin === candidate.id) setPin("") }}>Удалить путь</Button></div></fieldset>)}
<CandidateProbeEditor candidates={candidates} update={(id, controlProbe) => setCandidates(values => values.map(candidate => candidate.id === id ? { ...candidate, controlProbe } : candidate))} /><Button variant="outline" className="self-start" disabled={candidates.length >= 100} onClick={() => setCandidates(values => [...values, { ...values[0], id: crypto.randomUUID(), gateway: "", gatewayRef: { ...values[0].gatewayRef, id: "" } }])}>Добавить путь</Button><div className="grid gap-3 sm:grid-cols-3">{Object.entries(weights).map(([key, value]) => <Field key={key} label={`Вес ${key}, %`}><Input type="number" min={0} max={100} value={value} onChange={event => setWeights(values => ({ ...values, [key]: Number(event.target.value) }))} /></Field>)}{([{ key: "ping", title: "Максимум RTT, мс" }, { key: "loss", title: "Максимум потерь, %" }, { key: "speed", title: "Минимум скорости, Mbps" }] as const).map(field => <Field key={field.key} label={field.title}><Input type="number" min={0} value={sla[field.key]} placeholder="Без ограничения" onChange={event => setSla(values => ({ ...values, [field.key]: event.target.value }))} /></Field>)}<Field label="Порог улучшения, баллы"><Input type="number" min={0} max={100} value={threshold} onChange={event => setThreshold(Number(event.target.value))} /></Field><Field label="Пауза между переключениями, сек"><Input type="number" min={60} value={cooldown} onChange={event => setCooldown(Number(event.target.value))} /></Field><NativeSelect label="Закреплённый путь" value={pin} onChange={setPin}><option value="">Автоматический выбор</option>{candidates.map((candidate, index) => <option key={candidate.id} value={candidate.id}>Путь {index + 1}</option>)}</NativeSelect></div><Choice label="Разрешить заранее зарезервированное восстановление" checked={autoRecovery} onChange={setAutoRecovery} /><Choice label="Разрешить работу контроллера после применения плана" checked={enabled} onChange={setEnabled} /><Field label="Допуск действует до (UTC, максимум 24 часа)"><Input type="datetime-local" value={expires} onChange={event => setExpires(event.target.value)} /></Field><Button disabled={busy || !connectionId || (!!controllerReason && enabled)} onClick={() => { void save() }}>{busy ? "Подготовка…" : "Подготовить план профиля"}</Button></>}</DialogContent></Dialog>
}
type CandidateForm = Omit<RouteAiProfile["candidates"][number], "jumpHostId" | "exitNodeId"> & { jumpHostId: string; exitNodeId: string }
function CandidateProbeEditor({ candidates, update }: { candidates: CandidateForm[]; update: (id: string, probe: CandidateForm["controlProbe"]) => void }) {
return <div className="grid gap-3">{candidates.map((candidate, index) => <fieldset key={candidate.id} className="flex flex-col gap-3 rounded-md border p-3"><legend className="px-1 text-sm">Контрольная проверка пути {index + 1}</legend><Choice label={`Включить контроль пути ${index + 1}`} checked={!!candidate.controlProbe} onChange={checked => 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 && <><Field label={`Контрольный интерфейс ExitNode пути ${index + 1}`}><Input value={candidate.controlProbe.targetInterface} onChange={event => update(candidate.id, { ...candidate.controlProbe!, targetInterface: event.target.value })} /></Field><Field label={`Исходный IP контрольной пробы пути ${index + 1}`}><Input value={candidate.controlProbe.sourceAddress ?? ""} placeholder="Автоматический выбор RouterOS" onChange={event => update(candidate.id, { ...candidate.controlProbe!, sourceAddress: event.target.value || undefined })} /></Field><Field label={`Конкретный IP ExitNode пути ${index + 1}`}><Input value={candidate.controlProbe.targetAddress ?? ""} placeholder="Для интерфейса с несколькими адресами" onChange={event => update(candidate.id, { ...candidate.controlProbe!, targetAddress: event.target.value || undefined })} /></Field>{candidate.controlProbe.expectedHops.map((hop, hopIndex) => <div key={hopIndex} className="grid gap-3 sm:grid-cols-2"><Field label={`Сервер hop ${hopIndex + 1} пути ${index + 1}`}><Input type="number" min={1} value={hop.serverId || ""} onChange={event => update(candidate.id, { ...candidate.controlProbe!, expectedHops: candidate.controlProbe!.expectedHops.map((item, current) => current === hopIndex ? { ...item, serverId: Number(event.target.value) } : item) })} /></Field><Field label={`IP hop ${hopIndex + 1} пути ${index + 1}`}><Input value={hop.address ?? ""} placeholder="Для интерфейса с несколькими адресами" onChange={event => update(candidate.id, { ...candidate.controlProbe!, expectedHops: candidate.controlProbe!.expectedHops.map((item, current) => current === hopIndex ? { ...item, address: event.target.value || undefined } : item) })} /></Field><Field label={`Интерфейс hop ${hopIndex + 1} пути ${index + 1}`}><Input value={hop.interface} onChange={event => update(candidate.id, { ...candidate.controlProbe!, expectedHops: candidate.controlProbe!.expectedHops.map((item, current) => current === hopIndex ? { ...item, interface: event.target.value } : item) })} /></Field></div>)}<p className="text-xs text-muted-foreground">Проверяются зарегистрированные адреса, порядок hops и достижение ExitNode. Это наблюдение контрольных пакетов; оно не доказывает путь всего пользовательского трафика.</p></>}</fieldset>)}</div>
}
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 <Panel title="Контрольная проверка пути" description="Ограниченные ping и traceroute; неизвестный результат не считается отказом пути.">
<ErrorMessage message={profiles.error || (currentFeedback && "error" in currentFeedback ? currentFeedback.error : "")} />
<div className="grid gap-3 sm:grid-cols-2">
<NativeSelect label="Профиль для проверки пути" value={profileId} onChange={value => { invalidate(); setProfileId(value); setCandidateId("") }}><option value="">Выберите профиль</option>{profiles.data?.profiles.map(profile => <option key={String(profile.id)} value={String(profile.id)}>{String((profile.config as RecordRow)?.name ?? profile.id)}</option>)}</NativeSelect>
<NativeSelect label="Проверяемый путь" value={candidateId} onChange={value => { invalidate(); setCandidateId(value) }}><option value="">Выберите путь</option>{candidates.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.id}</option>)}</NativeSelect>
<NativeSelect label="Назначение проверки" value={proofPurpose} onChange={value => { invalidate(); setProofPurpose(value as typeof proofPurpose) }}><option value="community">Путь Community</option><option value="control-path">Самостоятельный контрольный путь</option></NativeSelect>
</div>
<p className="text-sm text-muted-foreground">{proofPurpose === "control-path" ? "Проверяется только контрольный путь. Результат не разрешает переключение Community и не подтверждает обратный путь." : "Проверка учитывает Community, таблицу маршрутизации и BGP. Применение изменений требует отдельного плана; обратный путь проверяется отдельно."}</p>
<Button disabled={busy || !canCheck} onClick={() => { void check() }}>Проверить контрольный путь</Button>
{currentFeedback && "result" in currentFeedback && <pre role="status" className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">{pretty(currentFeedback.result)}</pre>}
</Panel>
}
function RoutingProfiles({ api }: { api: McpApi }) {
const query = useQuery(useCallback(signal => api.profiles(signal), [api])), [selected, setSelected] = useState<RecordRow | null>(null)
const [editing, setEditing] = useState<RecordRow | "new" | null>(null)
const columns = useMemo<ColumnDef<DataGridFeatures, RecordRow>[]>(() => [
{ 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 }) => <Badge variant={row.original.enabled ? "success-light" : "warning-light"}>{row.original.enabled ? "включён" : "пауза"}</Badge> },
{ 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") && <Button size="sm" variant="outline" disabled={!row.original.enabled} onClick={() => { void api.pauseProfile(String(row.original.id)).then(query.refresh, error => toast.error(errorText(error))) }}>Остановить</Button> },
], [api, query.refresh])
return <><Panel title="Постоянный контроллер Route AI" description="Профили, временные допуски и решения маршрутизации" actions={can("mm:mcp:admin") && can("mm:network:write") && <Button onClick={() => setEditing("new")}>Создать профиль</Button>}><ErrorMessage message={query.error} /><Grid items={query.data?.profiles ?? []} columns={columns} loading={!query.data && !query.error} onSelect={setSelected} /><p className="text-sm text-muted-foreground">Контроллер учитывает свежесть измерений, закрепления, SLA, гистерезис, cooldown и бюджет переключений. Неизвестный фактический путь не считается подтверждённым.</p><Dialog open={!!selected} onOpenChange={open => { if (!open) setSelected(null) }}><DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl"><DialogHeader><DialogTitle>Профиль Route AI</DialogTitle><DialogDescription>Сохранённые параметры и последнее решение контроллера</DialogDescription></DialogHeader><pre className="overflow-auto whitespace-pre-wrap break-all text-xs">{pretty(selected)}</pre>{can("mm:mcp:admin") && can("mm:network:write") && <Button onClick={() => { setEditing(selected); setSelected(null) }}>Изменить профиль</Button>}</DialogContent></Dialog></Panel>{editing && <RoutingProfileForm api={api} editing={editing === "new" ? undefined : editing} close={() => { setEditing(null); query.refresh() }} />}</>
}
function Overview({ api }: { api: McpApi }) {
const query = useQuery(useCallback(signal => api.overview(signal), [api]))
return <Panel title="Управление AI-доступом" description={query.data ? "Последнее обновление: " + date(query.data.observedAt) : "Загрузка состояния"} actions={can("mm:mcp:pause") && <Button variant="outline" onClick={() => { if (window.confirm("Остановить новые обращения MCP и все профили Route AI? Начатые записи будут завершены или сверены.")) void api.stopAutomation().then(query.refresh, error => toast.error(errorText(error))) }}><StopCircleIcon />Остановить автоматические изменения</Button>}><ErrorMessage message={query.error} /><div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">{Object.entries({ connections: "Подключения", calls: "Вызовы за 24 часа", errors: "Ошибки и отказы", approvals: "Ожидают подтверждения", running: "Выполняются" }).map(([key, title]) => <div key={key} className="rounded-lg border p-4"><p className="text-sm text-muted-foreground">{title}</p><p className="mt-2 text-2xl font-semibold tabular-nums">{query.data ? query.data[key as "calls"] : "—"}</p></div>)}</div><Badge variant={query.data?.enabled ? "success-light" : "warning-light"}>{query.data?.enabled ? "MCP включён" : "MCP выключен"}</Badge><p className="text-sm text-muted-foreground">Выключатель прекращает новые вызовы. Выключатель также останавливает новые решения Route AI. Отдельный профиль можно остановить на вкладке Route AI.</p><PollStorageCapacity capacity={query.error ? {status:"unavailable"} : query.data?.pollStorageCapacity} loading={!query.data && !query.error} refresh={query.refresh} /></Panel>
}
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<RecordRow | null>(null)
const [startedOperation, setStartedOperation] = useState<string | null>(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<ColumnDef<DataGridFeatures, RecordRow>[]>(() => [
{ 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 }) => <Badge variant={["completed", "applied"].includes(String(row.original.status ?? row.original.state)) ? "success-light" : "info-light"}>{String(row.original.status ?? row.original.state ?? "событие")}</Badge> },
{ accessorKey: "connection_id", header: "Подключение", size: 250, cell: ({ row }) => <span className="font-mono text-xs">{String(row.original.connection_id ?? row.original.connectionId ?? "—")}</span> },
{ accessorKey: "error_code", header: "Причина", cell: ({ row }) => String(row.original.error_code ?? row.original.verification ?? "—") },
{ id: "details", header: "", cell: ({ row }) => <Button size="sm" variant="ghost" onClick={() => selectRecord(row.original)}>Открыть</Button> },
], [selectRecord])
const pendingPlanRequests = useRef(new Set<string>())
const [pendingPlans, setPendingPlans] = useState<ReadonlySet<string>>(() => 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<typeof setTimeout>
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 (
<Panel title={kind === "requests" ? "Обращения" : kind === "plans" ? "Планы изменений" : kind === "operations" ? "Выполнение операций" : kind === "drift" ? "Расхождения конфигурации" : "Административный аудит"} description="Чтение, отказы и изменения доступны для расследования">
<ErrorMessage message={query.error} />
{startedOperation && <Link className={navigationClass} href={`/mcp?${operationLink}`}>Открыть выполнение операции</Link>}
{journalConnection && <Link className={navigationClass} href={`/mcp?${new URLSearchParams({ tab: "plans", "plans.connectionId": journalConnection, "operations.connectionId": journalConnection })}`}>Планы и операции подключения</Link>}
{journalConnection && can("mm:mcp:admin") && <Link className={navigationClass} href={`/mcp?${new URLSearchParams({ tab: "settings", "audit.connectionId": journalConnection })}#mcp-audit`}>Административный аудит подключения</Link>}
<p className="text-xs text-muted-foreground">Последнее успешное обновление: {date(query.updatedAt)}{query.error && query.data ? " · показаны ранее полученные данные" : ""}</p>
<RecordFilters fields={fields} value={filterValue} update={setFilter} />
<div className="flex flex-wrap gap-2">
{fields.includes("tool") && <Input className="max-w-sm" aria-label="Имя инструмента" placeholder="Имя инструмента" value={filterValue("tool")} onChange={event => setFilter("tool", event.target.value)} />}
{fields.includes("status") && <Input className="max-w-xs" aria-label="Фильтр состояния" placeholder="Состояние" value={filterValue("status")} onChange={event => setFilter("status", event.target.value)} />}
<Button variant="outline" onClick={query.refresh}><RefreshCwIcon />Обновить</Button>
</div>
<Grid items={query.data?.items ?? []} columns={columns} total={query.data?.total} loading={!query.data && !query.error} onSelect={selectRecord} />
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">Найдено: {query.data?.total ?? "—"}</span>
<div className="flex gap-2">
<Button variant="outline" disabled={!cursor} onClick={() => setFilter("cursor", "")}>В начало</Button>
<Button variant="outline" disabled={!query.data?.nextCursor} onClick={() => setFilter("cursor", query.data?.nextCursor ?? "")}>Далее</Button>
</div>
</div>
<Dialog open={!!selected || !!operationId} onOpenChange={open => { if (!open) closeDetails() }}>
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-3xl">
<DialogHeader>
<DialogTitle>Детали {kind === "plans" ? "плана" : kind === "operations" ? "операции" : "обращения"}</DialogTitle>
<DialogDescription>{kind === "plans" ? "Подтверждение относится к показанному плану." : "Данные журнала с маскировкой секретных полей."}</DialogDescription>
</DialogHeader>
{operationId ? <OperationMonitor key={operationId} api={api} id={operationId} /> : kind === "plans" && selected ? <PlanReview plan={selected} /> : <pre className="max-h-[55dvh] overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted p-3 text-xs">{pretty(selected)}</pre>}
{planExpired && <p role="status" className="text-sm text-muted-foreground">Срок плана истёк. Подготовьте новый план.</p>}
{planChanged && !planExpired && <p role="status" className="text-sm text-muted-foreground">Текущая версия плана недоступна или изменилась. Откройте план заново.</p>}
{kind === "plans" && ["approved", "draft"].includes(String(selected?.state)) && can("mm:mcp:admin") && <Button disabled={planActionDisabled} onClick={() => { void submitPlan("apply") }}>Применить план</Button>}
{kind === "plans" && selected?.state === "awaiting-approval" && can("mm:mcp:approve") && <div className="flex gap-2"><Button disabled={planActionDisabled} onClick={() => { void submitPlan("approve") }}>Подтвердить план</Button><Button variant="outline" disabled={planActionDisabled} onClick={() => { void submitPlan("reject") }}>Отклонить</Button></div>}
</DialogContent>
</Dialog>
</Panel>
)
}
const operationStates: Record<string, string> = {
pending: "Ожидает выполнения", running: "Выполняется", applied: "Применена", failed: "Ошибка выполнения",
blocked: "Заблокирована", cancelled: "Отменена", partial: "Выполнена частично", unknown: "Исход не подтверждён",
}
const stepStates: Record<string, string> = { 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 <>
<ErrorMessage message={query.error} />
<div className="flex flex-wrap items-center gap-2">
<span className="break-all font-mono text-xs">{id}</span>
<Button variant="outline" size="sm" onClick={query.refresh}>Обновить выполнение</Button>
</div>
<p aria-live="polite" className="text-sm">
{operation ? operationStates[state] ?? state : query.data ? "Операция отсутствует в доступном журнале" : query.error ? "Состояние недоступно" : "Получаем состояние операции…"}
{query.error && operation && " · последнее полученное состояние"}
</p>
{operation && <>
{(state === "partial" || state === "unknown") && <div className="flex flex-wrap items-center gap-2 text-sm">
<p className="text-muted-foreground">Перед обратным изменением сверьте фактическое состояние. Повтор может повторно изменить конфигурацию.</p>
{can("mm:mcp:admin") && <Link className={buttonVariants({ variant: "outline", size: "sm" })} href={`/mcp?${recoveryLink}#mcp-recovery`}>Перейти к сверке</Link>}
</div>}
{steps.length > 0 && <section aria-label="Шаги выполнения" className="rounded-md border p-3 text-sm">
<h3 className="font-medium">Шаги выполнения</h3>
<ol className="mt-2 list-inside list-decimal space-y-1">
{steps.map(step => <li key={String(step.step_index)}>{stepStates[String(step.state)] ?? String(step.state)}{step.server_id != null && ` · сервер ${step.server_id}`}{step.finished_at != null && ` · ${date(step.finished_at)}`}</li>)}
</ol>
{operation.stepsTruncated === true && <p className="mt-2 text-muted-foreground">Показаны первые 100 шагов.</p>}
</section>}
<pre className="max-h-[45dvh] overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted p-3 text-xs">{pretty(operation)}</pre>
{!query.error && <ArtifactDownloads api={api} operation={operation} />}
</>}
</>
}
function RecordFilters({ fields, value, update }: { fields: readonly string[]; value: (field: string) => string; update: (field: string, value: string) => void }) {
return (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{fields.includes("connectionId") && <Field label="Фильтр подключения MCP"><Input value={value("connectionId")} placeholder="UUID подключения" onChange={event => update("connectionId", event.target.value)} /></Field>}
{fields.includes("serverId") && <Field label="Фильтр ID сервера"><Input type="number" min={1} value={value("serverId")} onChange={event => update("serverId", event.target.value)} /></Field>}
{fields.includes("userId") && <Field label="Фильтр пользователя"><Input value={value("userId")} onChange={event => update("userId", event.target.value)} /></Field>}
{["from", "to"].map(field => <Field key={field} label={field === "from" ? "Обращения с (UTC)" : "Обращения до (UTC)"}><Input type="datetime-local" value={value(field).slice(0, 16)} onChange={event => update(field, event.target.value ? new Date(event.target.value + "Z").toISOString() : "")} /></Field>)}
</div>
)
}
function ConnectionPolicySimulation({ api, connection, operations }: {
api: McpApi
connection: McpConnection
operations: McpOperationDescriptor[]
}) {
const [operationId, setOperationId] = useState(""), [serverText, setServerText] = useState("")
const [result, setResult] = useState<McpPolicyDecision | null>(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 <>
<div className="grid gap-3 md:grid-cols-2">
<NativeSelect label="Операция" value={operationId} onChange={value => { invalidate(); setOperationId(value); setServerText("") }}>
<option value="">Выберите действие</option>
{available.map(operation => <option key={operation.id} value={operation.id}>{operation.title} · {operation.id}</option>)}
</NativeSelect>
{operation?.scope === "servers" && <Field label="ID серверов"><Input value={serverText} onChange={event => { invalidate(); setServerText(event.target.value) }} /></Field>}
</div>
{operation && <p className="text-sm text-muted-foreground">{{ connection: "Область операции — подключение", global: "Область операции — всё приложение", servers: "Область операции — выбранные серверы" }[operation.scope]}</p>}
<Button className="self-start" disabled={!target.success || !can("mm:mcp:admin")} onClick={() => { void preview() }}><ShieldIcon />Проверить</Button>
{result && <PolicyPreviewDecision result={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 <div className="flex flex-col gap-4">
<Panel title="Проверка разрешений" description="Симуляция текущей политики подключения без выполнения операции. Защиту конкретного объекта можно проверить отдельно.">
<ErrorMessage message={connections.error || protections.error} />
<NativeSelect label="Подключение" value={selected?.id ?? ""} onChange={value => {
const url = new URL(window.location.href)
if (value) url.searchParams.set("connection", value)
else url.searchParams.delete("connection")
window.history.replaceState(null, "", url.pathname + url.search)
}}>
<option value="">Выберите подключение</option>
{connections.data?.connections.map(connection => <option key={connection.id} value={connection.id}>{connection.name}</option>)}
</NativeSelect>
{connectionId && connections.data && !selected && <p className="text-sm text-muted-foreground">Подключение отсутствует в доступном списке.</p>}
{selected && <div className="flex flex-wrap items-center gap-3"><ConnectionAccessStatus connection={selected} /><Link className={buttonVariants({ variant: "outline" })} href={`/mcp?${new URLSearchParams({ tab: "requests", "requests.connectionId": selected.id })}`}>Открыть обращения подключения</Link></div>}
{selected && admin && <ConnectionPolicySimulation key={`simulation:${selected.id}:${selected.policy.version}`} api={api} connection={selected} operations={operations} />}
{selected && admin && selected.ownerId === getClaims()?.sub && <ObjectPermissionPreview key={`object:${selected.id}:${selected.policy.version}`} api={api} connection={selected} operations={operations} editable={!protections.error && !!protections.data} onProtected={protections.refresh} />}
{!admin && <p className="text-sm text-muted-foreground">Симуляция политики и управление защитой доступны администратору MCP.</p>}
</Panel>
<Panel title="Защищённые объекты" description="Защита сохраняется и при автономном доступе">
<div className="flex flex-col gap-2">{protectionItems.map(item => <div key={item.id} className="flex flex-wrap items-center justify-between gap-2 rounded border p-3 text-sm"><span>{item.object_ref.kind} · {item.object_ref.id}{item.object_ref.serverId != null && ` · сервер ${item.object_ref.serverId}`} · {item.object_ref.protection === "deny" ? "Запрет изменений" : "Подтверждение человеком"}<span className="ml-2 text-muted-foreground">{item.reason}</span></span>{admin && <Button variant="outline" size="sm" onClick={() => { if (window.confirm("Удалить защиту объекта?")) void api.removeProtection(item.id).then(protections.refresh, error => toast.error(errorText(error))) }}>Удалить защиту</Button>}</div>)}</div>
{admin && <>
<div className="grid gap-3 md:grid-cols-4">
<Field label="Тип объекта"><Input value={kind} onChange={event => setKind(event.target.value)} /></Field>
<Field label="Стабильный ID"><Input value={objectId} onChange={event => setObjectId(event.target.value)} /></Field>
{kind !== "server" && <Field label="ID сервера защищаемого объекта"><Input value={protectionServerText} onChange={event => setProtectionServerText(event.target.value)} /></Field>}
<NativeSelect label="Защита" value={protection} onChange={setProtection}><option value="human-approval-required">Подтверждение человеком</option><option value="deny">Запрет изменений</option></NativeSelect>
<Field label="Причина"><Input value={reason} onChange={event => setReason(event.target.value)} /></Field>
</div>
<Button className="self-start" disabled={!objectId || kind !== "server" && !validProtectionServer} onClick={addProtection}>Добавить защиту</Button>
</>}
</Panel>
</div>
}
function OperationRecovery({ api, operationId }: { api: McpApi; operationId: string }) {
const [id, setId] = useState(operationId), [result, setResult] = useState<unknown>(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 <section id="mcp-recovery">
<Panel title="Сверка и восстановление" description="Сверка читает состояние устройства. Восстановление создаёт отдельный план и проверяет отсутствие внешних изменений.">
<ErrorMessage message={error} />
<Field label="ID исходной операции"><Input value={id} disabled={busy} aria-invalid={!!target && !validId} onChange={event => { setId(event.target.value); setResult(null); setError("") }} /></Field>
{target && !validId && <p className="text-sm text-destructive">Укажите UUID операции из журнала.</p>}
<div className="flex flex-wrap gap-2">
<Button variant="outline" disabled={busy || !validId} onClick={() => { void run(false) }}>Сверить состояние операции</Button>
<Button disabled={busy || !validId} onClick={() => { void run(true) }}>Подготовить обратный план</Button>
</div>
{result !== null && <pre role="status" className="max-h-60 overflow-auto whitespace-pre-wrap break-all text-xs">{pretty(result)}</pre>}
</Panel>
</section>
}
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 <Panel title="Независимый канал управления" description="Другой IP того же RouterOS. Backend проверяет стабильный ID и доступность; независимость сетевого пути подтверждает администратор."><ErrorMessage message={channels.error || error} /><Grid items={channels.data?.channels ?? []} columns={[{ accessorKey: "server_id", header: "Сервер" }, { accessorKey: "verified_at", header: "Проверен", cell: ({ row }) => 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 ? "Отозван" : <Button size="sm" variant="outline" onClick={() => { void api.revokeManagement(String(row.original.id)).then(channels.refresh, failure => toast.error(errorText(failure))) }}>Отозвать канал</Button> }]} />{can("mm:network:admin") && <><div className="grid gap-3 sm:grid-cols-2"><Field label="ID сервера независимого канала"><Input type="number" min={1} value={serverId} onChange={event => setServerId(event.target.value)} /></Field><Field label="IP независимого управления"><Input value={host} onChange={event => setHost(event.target.value)} /></Field><Field label="Порт независимого управления"><Input type="number" min={1} max={65535} value={port} onChange={event => setPort(Number(event.target.value))} /></Field><Choice label="HTTPS с проверкой сертификата" checked={ssl} onChange={setSsl} /><Field label="Пользователь независимого канала"><Input autoComplete="off" value={username} onChange={event => setUsername(event.target.value)} /></Field><Field label="Пароль независимого канала"><Input type="password" autoComplete="new-password" value={password} onChange={event => setPassword(event.target.value)} /></Field><Field label="Допуск независимого канала до (UTC)"><Input type="datetime-local" value={expiry} onChange={event => setExpiry(event.target.value)} /></Field><Field label="Подтверждение независимости пути"><Textarea value={attestation} onChange={event => setAttestation(event.target.value)} placeholder="Опишите отдельный путь, интерфейс/VRF и почему изменение основного пути его не затронет" /></Field></div><Button disabled={busy || !serverId || !host || !username || !password || attestation.trim().length < 30} onClick={() => { void register() }}>Проверить и зарегистрировать канал</Button></>}</Panel>
}
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 <div className="flex flex-col gap-4"><Panel title="Настройки MCP" description="По умолчанию внешний доступ выключен"><ErrorMessage message={query.error} />{query.data && <><Choice label="Разрешить обращения MCP" checked={query.data.enabled} onChange={enabled => { void save({ enabled }) }} /><div className="grid gap-3 sm:grid-cols-2"><Field label="Хранение обращений, дней"><Input type="number" min={1} max={365} defaultValue={query.data.requestsRetentionDays} onBlur={event => { const value = Number(event.target.value); if (value !== query.data?.requestsRetentionDays && window.confirm("Изменить срок хранения обращений? Старые записи будут удаляться по новому сроку.")) void save({ requestsRetentionDays: value }) }} /></Field><Field label="Хранение аудита, дней"><Input type="number" min={30} max={3650} defaultValue={query.data.auditRetentionDays} onBlur={event => { const value = Number(event.target.value); if (value !== query.data?.auditRetentionDays && window.confirm("Изменить срок хранения аудита?")) void save({ auditRetentionDays: value }) }} /></Field></div></>}</Panel><Panel title="OAuth-клиенты" description="Зарегистрируйте точный redirect URI внешнего AI-клиента"><ErrorMessage message={clients.error} />{clients.data?.clients.map(client => <div key={client.id} className="rounded border p-3 text-sm"><p className="font-medium">{client.name} · {client.enabled ? "разрешён" : "отключён"}</p><p className="break-all font-mono text-xs">client_id: {client.id}</p><p className="break-all text-muted-foreground">{client.redirect_uris.join(", ")}</p>{client.enabled && <Button size="sm" variant="outline" onClick={() => { if (window.confirm("Отключить OAuth-клиент и отозвать его токены?")) void api.disableClient(client.id).then(clients.refresh, error => toast.error(errorText(error))) }}>Отключить и отозвать токены</Button>}</div>)}<Field label="Название клиента"><Input value={name} onChange={event => setName(event.target.value)} /></Field><Field label="Redirect URI, по одному на строку"><Textarea value={redirect} onChange={event => setRedirect(event.target.value)} /></Field><Button className="self-start" disabled={!name || !redirect} onClick={() => { void api.createClient(name, redirect.split("\n").map(value => value.trim()).filter(Boolean)).then(() => { setName(""); setRedirect(""); clients.refresh() }, error => toast.error(errorText(error))) }}>Зарегистрировать клиент</Button></Panel><section id="mcp-audit"><Records api={api} kind="audit" /></section></div>
}
function RestCoverage({ api }: { api: McpApi }) {
const query = useQuery(useCallback(signal => api.coverage(signal), [api])), routes = query.data?.routes ?? []
return <Panel title="Покрытие REST через MCP" description="Сервисные сценарии проверяются отдельно от количества инструментов. Новые endpoints отслеживает автоматическая проверка реестра."><ErrorMessage message={query.error} /><div className="flex flex-wrap gap-2"><Badge variant="success-light">Сценариев с MCP: {routes.filter(route => route.status === "mediated").length}</Badge><Badge variant="info-light">Транспорт и управление доступом: {routes.filter(route => route.status === "excluded").length}</Badge><Badge variant="warning-light">Ожидают реализации: {routes.filter(route => route.status === "pending").length}</Badge></div><Grid items={routes.filter(route => route.status === "pending")} columns={[{ accessorKey: "method", header: "Метод", size: 90 }, { accessorKey: "path", header: "Незавершённый сценарий", size: 310 }, { accessorKey: "reason", header: "Что осталось", size: 400 }]} loading={!query.data && !query.error} /></Panel>
}
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 <Panel title="Разрешение OAuth-доступа" description="Выберите подключение с нужными ограничениями; клиент получит только его доступ">
<ErrorMessage message={sessionChanged ? "Сессия портала изменилась. Обновите страницу и снова проверьте запрос OAuth." : request.error || connections.error} />
{currentRequest && <><p>{currentRequest.name} запрашивает доступ к MikrotikManager.</p><p className="break-all text-sm text-muted-foreground">Возврат: {currentRequest.redirect_uri}</p></>}
<NativeSelect label="Подключение" value={sessionChanged ? "" : selected} onChange={setSelected}>
<option value="">Выберите ограниченный доступ</option>
{!sessionChanged && eligible.map(connection => <option key={connection.id} value={connection.id}>{connection.name} · {modeLabels[connection.policy.mode]}</option>)}
</NativeSelect>
<div className="flex gap-2">
<Button disabled={!canApprove || busy} onClick={() => { void confirm(true) }}>Разрешить</Button>
<Button variant="outline" disabled={!canDeny || busy} onClick={() => { void confirm(false) }}>Отклонить</Button>
</div>
</Panel>
}
export function McpWorkspace() {
const { backendUrl, mode } = useDataSource()
return <McpWorkspaceContent key={JSON.stringify([backendUrl, mode])} backendUrl={backendUrl} live={mode === "live"} />
}
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<McpOperationDescriptor[]>([]), [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 <><PageHeader crumbs={[{ label: "MCP" }]} /><main className="flex min-w-0 flex-1 flex-col gap-5 p-4 md:p-6"><div className="flex items-center gap-3"><BotIcon className="size-7 text-muted-foreground" /><div><h1 className="text-xl font-semibold">MCP</h1><p className="text-sm text-muted-foreground">Доступ нейросетей, разрешения и контроль изменений</p></div></div>{!live ? <Panel title="Подключите backend"><p>Для выдачи реального AI-доступа выберите режим «Живые» и настройте авторизацию портала.</p></Panel> : <><ErrorMessage message={error} />{oauthRequestId && <Consent key={oauthRequestId} api={api} id={oauthRequestId} />}<Tabs value={tab} onValueChange={changeTab}><div className="overflow-x-auto pb-1"><TabsList variant="line">{Object.entries(tabs).filter(([key]) => key !== "settings" || can("mm:mcp:admin")).map(([key, title]) => <TabsTrigger key={key} value={key}>{title}</TabsTrigger>)}</TabsList></div><TabsContent value="overview"><Overview api={api} /></TabsContent><TabsContent value="connections"><div className="flex flex-col gap-4"><Connections api={api} operations={operations} />{can("mm:mcp:admin") && <AccessTools api={api} />}</div></TabsContent><TabsContent value="permissions"><Permissions api={api} operations={operations} /></TabsContent><TabsContent value="devices"><DeviceManagement api={api} /></TabsContent><TabsContent value="routing"><div className="flex flex-col gap-4"><RoutingProfiles api={api} /><RoutePathVerification api={api} /></div></TabsContent><TabsContent value="requests"><Records api={api} kind="requests" /></TabsContent><TabsContent value="plans"><div className="flex flex-col gap-4"><Records api={api} kind="plans" /><Records api={api} kind="operations" />{admin && <OperationRecovery key={recoveryId} api={api} operationId={recoveryId} />}<Records api={api} kind="drift" /></div></TabsContent>{can("mm:mcp:admin") && <TabsContent value="settings"><div className="flex flex-col gap-4"><Settings api={api} /><RestCoverage api={api} /><ManagementChannels api={api} />{can("mm:settings:admin") && <DatabaseRestore api={api} />}</div></TabsContent>}</Tabs></>}</main></>
}
@@ -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<ReturnType<McpApi["deviceCatalog"]>>
type Rows = Awaited<ReturnType<McpApi["deviceRows"]>>
export function ObjectPermissionPreview({ api, connection, operations, editable, onProtected }: {
api: McpApi; connection: McpConnection; operations: McpOperationDescriptor[]; editable: boolean; onProtected: () => void
}) {
const [catalog, setCatalog] = useState<Catalog | null>(null), [rows, setRows] = useState<Rows | null>(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<McpPolicyDecision | null>(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 <section aria-label="Проверка объекта устройства" className="flex min-w-0 flex-col gap-4 rounded-md border p-4">
<p className="font-medium">Объект устройства</p>
<p className="text-sm text-muted-foreground">Выберите объект по данным своего подключения. Проверка гипотетическая: она учитывает выбранный объект и сохранённые защиты. Реальный план дополнительно проверяет зависимости. Выбор объекта не ограничивает токен или временный допуск этим объектом.</p>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<div className="grid gap-3 sm:grid-cols-2">
<label className="flex min-w-0 flex-col gap-1.5 text-sm">Сервер проверяемого объекта<select aria-label="Сервер проверяемого объекта" className={selectClass} disabled={busy || !catalog} value={server} onChange={event => changeServer(event.target.value)}><option value="">Выберите сервер</option>{catalog?.servers.map(value => <option key={value.id} value={value.id}>{value.name} · {value.id}</option>)}</select></label>
<label className="flex min-w-0 flex-col gap-1.5 text-sm">Тип проверяемого объекта<select aria-label="Тип проверяемого объекта" className={selectClass} disabled={busy || !catalog} value={resource} onChange={event => changeResource(event.target.value)}><option value="">Выберите тип</option>{catalog?.resources.filter(value => value.read).map(value => <option key={value.id} value={value.id}>{value.title}</option>)}</select></label>
<label className="flex min-w-0 flex-col gap-1.5 text-sm">Стабильный ID объекта<select aria-label="Стабильный ID объекта" className={selectClass} disabled={busy || !rows} value={nativeId} onChange={event => { setNativeId(event.target.value); setResult(null); setReceipt("") }}><option value="">{rows && !availableRows.length ? "Нет объектов на странице" : "Выберите объект"}</option>{availableRows.map(row => <option key={String(row[".id"])} value={String(row[".id"])}>{String(row.name ?? row.address ?? row.interface ?? resource)} · {String(row[".id"])}</option>)}</select></label>
<label className="flex min-w-0 flex-col gap-1.5 text-sm">Операция над объектом<select aria-label="Операция над объектом" className={selectClass} disabled={busy} value={operation} onChange={event => { setOperation(event.target.value); setResult(null) }}><option value="">Выберите действие</option>{operations.filter(value => value.scope === "servers" && connection.policy.scope.operationIds.includes(value.id)).map(value => <option key={value.id}>{value.id}</option>)}</select></label>
</div>
<div className="flex flex-wrap gap-2"><Button variant="outline" disabled={busy || offset === 0} onClick={() => { reset(); setOffset(value => Math.max(0, value - 100)) }}>Предыдущая страница объектов</Button><Button variant="outline" disabled={busy || rows?.nextOffset == null} onClick={() => { const next = rows?.nextOffset; if (next != null) { reset(); setOffset(next) } }}>Следующая страница объектов</Button><Button disabled={!editable || busy || !ready || !operation} onClick={() => { void act(false) }}>Проверить выбранный объект</Button></div>
{result && <PolicyPreviewDecision result={result} />}
{editable && <><label className="flex flex-col gap-1.5 text-sm">Защита выбранного объекта<select aria-label="Защита выбранного объекта" className={selectClass} disabled={busy} value={protection} onChange={event => setProtection(event.target.value)}><option value="human-approval-required">Подтверждение человеком</option><option value="deny">Запрет изменений</option></select></label><label className="flex flex-col gap-1.5 text-sm">Причина защиты объекта<Input value={reason} disabled={busy} onChange={event => setReason(event.target.value)} /></label><Button className="self-start" disabled={busy || !ready} onClick={() => { void act(true) }}>Защитить выбранный объект</Button></>}
{receipt && <p role="status" className="text-sm">{receipt}</p>}
</section>
}
export function PolicyPreviewDecision({ result }: { result: McpPolicyDecision }) {
return <div role="status" className="flex flex-col gap-3 rounded-md border p-3 text-sm">
<Badge variant={result.decision === "allowed" ? "success-light" : result.decision === "denied" ? "destructive-light" : "warning-light"}>{result.decision === "allowed" ? "Разрешено" : result.decision === "denied" ? "Запрещено" : "Нужно подтверждение"}</Badge>
{result.reasons.length > 0 && <ul className="list-inside list-disc space-y-1">{result.reasons.map((item, index) => <li key={`${item.code}:${index}`}>{item.message} <span className="text-xs text-muted-foreground">({item.code})</span></li>)}</ul>}
<p className="text-xs text-muted-foreground">Лимиты подключения: {result.limits.callsPerMinute} вызовов/мин · {result.limits.concurrentReads} параллельных чтения · {result.limits.mutationsPerHour} изменений/ч · до {result.limits.serversPerPlan} серверов и {result.limits.objectsPerPlan} объектов в плане.</p>
</div>
}
+18
View File
@@ -0,0 +1,18 @@
import { Badge } from "@/components/reui/badge"
const object = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}
const list = (value: unknown): unknown[] => Array.isArray(value) ? value : []
const json = (value: unknown) => JSON.stringify(value, null, 2)
export function PlanReview({ plan }: { plan: Record<string, unknown> }) {
const changes = object(plan.changes), target = object(changes.target)
const objects = list(changes.objects), steps = list(changes.steps), recovery = object(changes.recovery)
return <div className="flex min-w-0 flex-col gap-4">
<div className="flex flex-wrap gap-2"><Badge variant="info-light">{String(plan.operationId ?? "Операция")}</Badge><Badge variant="warning-light">{String(plan.state ?? "Неизвестно")}</Badge><Badge variant="invert-light">Шагов: {steps.length}</Badge></div>
<dl className="grid gap-2 text-sm sm:grid-cols-2"><div><dt className="text-muted-foreground">Область</dt><dd>{target.scope === "servers" ? "Серверы: " + list(target.serverIds).join(", ") : target.scope === "global" ? "Всё приложение" : "Подключение"}</dd></div><div><dt className="text-muted-foreground">Срок плана</dt><dd>{plan.expiresAt ? new Date(String(plan.expiresAt)).toLocaleString("ru-RU") : "Не указан"}</dd></div></dl>
{!!list(changes.warnings).length && <div className="rounded-md border border-warning/30 p-3 text-sm"><p className="mb-2 font-medium">Условия и последствия</p><ul className="list-disc space-y-1 pl-5">{list(changes.warnings).map((warning, index) => <li key={index}>{String(warning)}</li>)}</ul></div>}
{!!objects.length && <div><h3 className="mb-2 text-sm font-medium">Объекты и защищённые зависимости</h3><div className="flex flex-wrap gap-2">{objects.map((value, index) => { const item = object(value); return <Badge key={index} variant="invert-light">{item.serverId ? `Сервер ${item.serverId} · ` : ""}{String(item.kind)} · {String(item.id)}</Badge> })}</div></div>}
<div className="grid min-w-0 gap-3 md:grid-cols-2"><div className="min-w-0"><h3 className="mb-2 text-sm font-medium">Исходное состояние</h3><pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted p-3 text-xs">{json(changes.before ?? changes.snapshots ?? null)}</pre></div><div className="min-w-0"><h3 className="mb-2 text-sm font-medium">Запланированные шаги</h3><ol className="flex flex-col gap-2">{steps.map((value, index) => { const step = object(value); return <li key={index} className="min-w-0 rounded-md border p-3"><p className="mb-2 text-sm font-medium">{index + 1}. {step.kind === "ros" ? String(object(step.step).action) + " · " + String(object(step.step).resource) : String(step.service)}</p><pre className="max-h-52 overflow-auto whitespace-pre-wrap break-all text-xs">{json(step.kind === "ros" ? step.step : step.input)}</pre></li> })}</ol></div></div>
{!!Object.keys(recovery).length && <p className="rounded-md border p-3 text-sm">Зарезервировано восстановление до {new Date(String(recovery.validUntil)).toLocaleString("ru-RU")}. Оно выполняется только при подтверждённой исходной записи, неуспешной проверке и действующем допуске; неопределённую запись исполнитель не повторяет.</p>}
<details><summary className="cursor-pointer text-sm text-muted-foreground">Полные данные плана</summary><pre className="mt-2 max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">{json(plan)}</pre></details>
</div>
}
+25
View File
@@ -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 <section aria-label="Журнал полных опросов" className="flex flex-col gap-3 rounded-lg border p-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="font-medium">Журнал полных опросов</h3>
<div className="flex items-center gap-2"><Badge variant={!observed?"info-light":full?"warning-light":"success-light"}>{loading?"Загрузка":!observed?"Нет данных":full?"Квота заполнена":"Квота не заполнена"}</Badge><Button size="sm" variant="outline" onClick={refresh}>Обновить статус</Button></div>
</div>
{observed?<>
<dl className="grid gap-3 text-sm sm:grid-cols-2">
<div><dt className="text-muted-foreground">Ваши полные журналы</dt><dd className="font-medium tabular-nums">{observed.owner.used} / {observed.owner.limit}<span className="ml-2 font-normal text-muted-foreground">Осталось: {observed.owner.remaining}</span></dd></div>
<div><dt className="text-muted-foreground">Полные журналы приложения</dt><dd className="font-medium tabular-nums">{observed.global.usage?<>{observed.global.usage.used} / {observed.global.usage.limit}<span className="ml-2 font-normal text-muted-foreground">Осталось: {observed.global.usage.remaining}</span></>:globalFull?"Заполнена":"Не заполнена"}</dd></div>
</dl>
{full&&<p role="alert" className="text-sm">{ownerFull&&globalFull?"Личная и общая квоты журнала заполнены.":ownerFull?"Личная квота журнала заполнена.":"Общая квота журнала заполнена."} Новый полный опрос не получит место. После безопасного архивирования или очистки по сроку хранения место может освободиться. Неизвестный результат сохраняет резерв; повторные попытки его не освобождают.</p>}
<p className="text-sm text-muted-foreground">Счётчик учитывает резерв под выполнение и журналы, ожидающие архивирования. Архив сохраняет все исходные записи и продолжает занимать место. Поэтому остаток зависит и от объёма сохранённой истории.</p>
<p className="text-sm text-muted-foreground">Срок хранения новых записей: {observed.retentionDays} дн. Существующие записи могут храниться дольше. Архивирование сохраняет исходный срок; очистка учитывает завершение операции, истечение допуска и защитный интервал.</p>
<p className="text-xs text-muted-foreground">Состояние показано на момент обновления. Окончательный допуск проверяется при запуске.</p>
</>:<p role="status" className="text-sm text-muted-foreground">{loading?"Проверяем заполнение журнала…":"Заполнение журнала сейчас недоступно. Свободное место не подтверждено; обновите статус позже."}</p>}
</section>
}
@@ -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&&current())checkpoint(source,false)
+20 -11
View File
@@ -61,6 +61,9 @@ import {
const IFACE_TILE: Record<InterfaceType, { icon: typeof CableIcon; className: string }> = {
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<HTMLDivElement>(null)
useEffect(() => { if (saveError) saveErrorRef.current?.scrollIntoView({ block: "nearest" }) }, [saveError])
const isCreate = user === null
const [sheetStep, setSheetStep] = useState(1)
const [form, setForm] = useState<AppUserForm>(() => (user ? toForm(user) : emptyForm(servers)))
const [form, setForm] = useState<AppUserForm>(() => {
if (user) return toForm(user)
const initial = emptyForm(servers)
return canManagePermissions ? initial : { ...initial, sections: [], servers: [] }
})
const [errors, setErrors] = useState<Partial<Record<keyof AppUserForm, string>>>({})
const [catalogServerId, setCatalogServerId] = useState(servers[0]?.id ?? "")
const [selectedPicks, setSelectedPicks] = useState<CatalogPick[]>([])
@@ -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 && <span id="user-email-error" className="sr-only">{errors.email}</span>}
</FormField>
<FormField label="Роль" required>
<SegmentedControl
<FormField label="Роль" required={canManagePermissions}>
{canManagePermissions ? <SegmentedControl
className="w-full flex-col items-stretch sm:flex-row [&>button]:whitespace-nowrap [&>button]:min-h-9"
value={form.role}
onChange={setRole}
@@ -382,7 +391,7 @@ function UserSheet({
{ value: "operator", label: ROLE_LABEL.operator },
{ value: "admin", label: ROLE_LABEL.admin },
]}
/>
/> : <p className="text-sm">{ROLE_LABEL[form.role]}</p>}
</FormField>
<div className="flex items-center justify-between">
<span className="text-sm font-medium">Активный профиль</span>
@@ -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 (
<div key={section} className="flex flex-wrap items-center justify-between gap-2 py-2.5 hover:bg-muted/20 transition-colors">
<span className="text-sm">{section}</span>
<PermPills label={section} value={level} onChange={(v) => setSectionPerm(section, v)} disabled={isAdmin} />
<PermPills label={section} value={level} onChange={(v) => setSectionPerm(section, v)} disabled={permissionsReadOnly} />
</div>
)
})}
@@ -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({
<p className="text-[11px] font-mono text-muted-foreground truncate" title={srv.host}>{srv.host} · {srv.site}</p>
</div>
</div>
<PermPills label={srv.name} value={level} onChange={(v) => setServerPerm(srv.id, v)} disabled={isAdmin} />
<PermPills label={srv.name} value={level} onChange={(v) => setServerPerm(srv.id, v)} disabled={permissionsReadOnly} />
</div>
)
})}
+41 -5
View File
@@ -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<void> {
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<Response> {
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
}
+31 -23
View File
@@ -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<LogEntry[]>([]), [page, setPage] = useState<LogPage | null>(null)
const [summary, setSummary] = useState<LogSummary | null>(null), [stream, setStream] = useState<LogStream | null>(null)
const [entries, setEntries] = useState<LogEntry[]>([])
const [page, setPage] = useState<{ data: LogPage; query: string; signal: AbortSignal } | null>(null)
const [summary, setSummary] = useState<LogSummary | null>(null)
const [stream, setStream] = useState<{ batch: LogStream; receivedAt: number } | null>(null)
const [loading, setLoading] = useState(enabled), [fetchingMore, setFetchingMore] = useState(false)
const [error, setError] = useState<string | null>(null), [summaryError, setSummaryError] = useState<string | null>(null), [streamError, setStreamError] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null), [summaryError, setSummaryError] = useState<string | null>(null)
const [streamFailure, setStreamFailure] = useState<{ message: string | null; stopped: boolean } | null>(null)
const [revision, setRevision] = useState(0), [pendingCount, setPendingCount] = useState(0)
const pending = useRef<LogEntry[]>([]), pausedRef = useRef(paused), initialCursor = useRef<string | null>(null)
const lifetime = useRef<AbortController | null>(null), moreBusy = useRef(false)
const moreBusy = useRef<AbortSignal | null>(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<void>(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 }
}
+14
View File
@@ -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")
+2 -1
View File
@@ -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"
}
+1 -1
View File
@@ -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"
+1
View File
@@ -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","релиз"] },
+2 -2
View File
@@ -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<void>,
@@ -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]
+3 -2
View File
@@ -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
}
+4 -1
View File
@@ -77,13 +77,16 @@ export interface UserServerOption {
export const IFACE_TYPE_LABEL: Record<InterfaceType, string> = {
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<Role, string> = {
admin: "Администратор",
+3
View File
@@ -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/)
+1 -1
View File
@@ -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"]),
+255
View File
@@ -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",
+4 -1
View File
@@ -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",
+2
View File
@@ -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,
+16
View File
@@ -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" },
},
})
+24
View File
@@ -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',
},
},
})
+9
View File
@@ -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" } },
})
+11 -5
View File
@@ -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<T>(
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)
}
+105
View File
@@ -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<Response>((_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 }
})
+25 -3
View File
@@ -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<typeof existingCertExportOptionsSchema>
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<IpsecCertBundle> {
const intent = existingCertExportIntent(passphrase, options)
const response = await requestJson<unknown>(
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<IpsecCertBundle> {
const intent = existingCertExportIntent(passphrase, options)
const response = await requestJson<unknown>(
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)
}
+6 -3
View File
@@ -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<LogEntry, "id" | "serverId">, 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<typeof logSettingsPatchSchema>, signal?: AbortSignal) {
+78
View File
@@ -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) }
}
})
+97
View File
@@ -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<ReturnType<typeof humanArtifactReceipt>>, 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 "Не удалось скачать файл. Проверьте соединение и повторите попытку."
}
+17
View File
@@ -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)
})
+65
View File
@@ -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 <T>(path: string, schema: z.ZodType<T>, signal?: AbortSignal): Promise<T> => schema.parse(await requestJson(base, "/api/mcp" + path, { signal }))
const send = async <T>(path: string, body: unknown, schema: z.ZodType<T>, method = "POST", signal?: AbortSignal): Promise<T> => 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<string, unknown>) => 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<typeof mcpApi>
+2 -1
View File
@@ -12,7 +12,8 @@ import { requestJson as httpRequestJson } from "@/shared/api/http-client"
function requestJson<T>(baseUrl: string, path: string, init?: RequestInit): Promise<T> {
return httpRequestJson<T>(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),
})
}
+1 -1
View File
@@ -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<typeof receiptSchema>
const warningSchema=receiptSchema.omit({ok:true})
export type SystemDatabaseWarnings=z.output<typeof warningSchema>
+2 -1
View File
@@ -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<AppUser> {
export async function createAppUser(baseUrl: string, data: z.input<typeof appUserCreateSchema>, init?: RequestInit): Promise<AppUser> {
const payload = await requestJson<unknown>(baseUrl, "/api/users", {
...init,
method: "POST",
+2 -2
View File
@@ -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")
+177
View File
@@ -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<void>) {
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<string, unknown>)["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<void>(resolve => { release = resolve })
const requested = new Promise<void>(resolve => { started = resolve })
const settled = new Promise<void>(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)
})
@@ -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" })
})
}
@@ -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
}
+2 -2
View File
@@ -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")
+3 -4
View File
@@ -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()
+8
View File
@@ -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'); }",
}
+14
View File
@@ -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(?:[/?#]|$)/)
}
+2 -2
View File
@@ -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")
+114 -57
View File
@@ -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<string, unknown>, certs: ReturnType<typeof certificate>[], post: (route: Route) => Promise<void>) {
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<void>(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<void>(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()
})
+2 -2
View File
@@ -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")
+114 -5
View File
@@ -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<string | null> = []
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<void>(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)
})
+392
View File
@@ -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<string, unknown> }[] = []
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<void>(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<void>(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<void>(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<void> | 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: '<h1>Portal sign-in</h1>' })
})
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<void>(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()
}
})
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -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()
@@ -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([])
})
+2 -3
View File
@@ -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")
+2 -1
View File
@@ -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()
+2 -1
View File
@@ -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()
+2 -2
View File
@@ -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()
+10 -3
View File
@@ -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)
})
+35 -4
View File
@@ -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<string, unknown>, 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<string, unknown>, release: () => {}, liveCalls: 0 }
const gate = new Promise<void>(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'
+27
View File
@@ -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<string, unknown> | 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:""})})
+2 -2
View File
@@ -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")
+2 -1
View File
@@ -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()
+54
View File
@@ -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)
})
+15
View File
@@ -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<void>(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}])
})
+43 -4
View File
@@ -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"
]
}