72 lines
9.2 KiB
TypeScript
72 lines
9.2 KiB
TypeScript
"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>
|
|
}
|