fix(mcp): упростить выбор разрешений и ускорить сборку фронтенда
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 12m30s
Docker images / frontend-image (push) Successful in 4m16s
Docker images / updater-image (push) Successful in 2m38s
Docker images / netflow-agent-image (push) Successful in 38s
Docker images / backend-image (push) Successful in 4m5s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 12m30s
Docker images / frontend-image (push) Successful in 4m16s
Docker images / updater-image (push) Successful in 2m38s
Docker images / netflow-agent-image (push) Successful in 38s
Docker images / backend-image (push) Successful in 4m5s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
This commit is contained in:
1 parent
cad54635a8
commit
f27fd035bc
4 files changed
+110
-3
No files matched your search
@@ -31,6 +31,11 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } f
|
||||
|
||||
const errorText = (error: unknown) => error instanceof Error ? error.message : "Не удалось выполнить запрос"
|
||||
const modeLabels = { observer: "Наблюдатель", approval: "С подтверждением", autonomous: "Автономный" }
|
||||
const operationSectionLabels: Record<string, string> = {
|
||||
backups: "Резервные копии", certificates: "Сертификаты", filters: "Фильтры маршрутизации", firewall: "Межсетевой экран",
|
||||
ipsec: "IPsec", logs: "Журналы", mcp: "Управление MCP", network: "Сеть и маршрутизация", "recursive-routes": "Рекурсивные маршруты",
|
||||
servers: "Серверы", settings: "Настройки", traffic: "Трафик", uptime: "Доступность", users: "Пользователи", wireguard: "WireGuard",
|
||||
}
|
||||
const tabs = { overview: "Обзор", connections: "Подключения", permissions: "Разрешения", devices: "Интерфейсы", requests: "Обращения", plans: "Планы и операции", routing: "Route AI", settings: "Настройки" }
|
||||
type Tab = keyof typeof tabs
|
||||
type RecordRow = Record<string, unknown>
|
||||
@@ -162,7 +167,19 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
||||
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 selectedIds = new Set(selected)
|
||||
const bySection = new Map<string, McpOperationDescriptor[]>()
|
||||
for (const operation of eligible) {
|
||||
const group = bySection.get(operation.section)
|
||||
if (group) group.push(operation)
|
||||
else bySection.set(operation.section, [operation])
|
||||
}
|
||||
const groups = [...bySection]
|
||||
.sort(([left], [right]) => (operationSectionLabels[left] ?? left).localeCompare(operationSectionLabels[right] ?? right, "ru"))
|
||||
const selectOperations = (operations: McpOperationDescriptor[], checked: boolean) => {
|
||||
const groupIds = new Set(operations.map(operation => operation.id))
|
||||
setSelected(ids => checked ? [...new Set([...ids, ...groupIds])] : ids.filter(id => !groupIds.has(id)))
|
||||
}
|
||||
const save = async () => {
|
||||
setBusy(true); setError("")
|
||||
try {
|
||||
@@ -173,7 +190,32 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp
|
||||
}
|
||||
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 === 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="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" disabled={!eligible.length} onClick={() => setSelected(eligible.map(operation => operation.id))}>Выбрать все операции</Button>
|
||||
<Button variant="ghost" size="sm" disabled={!selected.length} onClick={() => setSelected([])}>Снять все</Button>
|
||||
<span className="text-sm text-muted-foreground" role="status">Выбрано {selected.length}</span>
|
||||
</div>
|
||||
<div className="max-h-80 space-y-2 overflow-y-auto">
|
||||
{groups.map(([section, items]) => {
|
||||
const title = operationSectionLabels[section] ?? section
|
||||
const count = items.filter(operation => selectedIds.has(operation.id)).length
|
||||
return <div key={section} className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-3 rounded-md border p-3">
|
||||
<Checkbox aria-label={`Все операции группы «${title}»`} className="mt-0.5" checked={count === items.length} indeterminate={count > 0 && count < items.length} onCheckedChange={checked => selectOperations(items, checked)} />
|
||||
<details>
|
||||
<summary className="cursor-pointer text-sm font-medium">{title} <span className="ms-1 font-normal text-muted-foreground">{count} / {items.length}</span></summary>
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
||||
{items.map(operation => <Choice key={operation.id} label={operation.title} checked={selectedIds.has(operation.id)} onChange={checked => selectOperations([operation], checked)} />)}
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
})}
|
||||
{!eligible.length && <p className="text-sm text-muted-foreground">Нет доступных операций.</p>}
|
||||
</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>
|
||||
|
||||
Reference in new issue
Block a user