import { useEffect, useRef, useState } from 'react'; import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react'; import { archiveHost, loadProjects } from '../api'; import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types'; import { b2Request, type B2Status, type B2Application } from './api'; import './b2.css'; type Section = 'connection' | 'contours'; export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: { host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void; onChanged: () => Promise; onError: (error: unknown) => void; }) { const project = workspace.project; const [section, setSection] = useState
('contours'); const [status, setStatus] = useState(null); const [pending, setPending] = useState('load'); const [connection, setConnection] = useState(''), [importOpen, setImportOpen] = useState(false); const connectionFile = useRef(null); const [projects, setProjects] = useState([]); const [expanded, setExpanded] = useState([]), [keyRows, setKeyRows] = useState([]); const [creating, setCreating] = useState(''), [name, setName] = useState(''); const [access, setAccess] = useState('read'); const [creationIntent, setCreationIntent] = useState<{ id: string; name: string; access: string } | null>(null); const [newContour, setNewContour] = useState(false), [contourName, setContourName] = useState(''); const [targetProject, setTargetProject] = useState(project.projectRef); const [contourIntent, setContourIntent] = useState<{ id: string; name: string; projectRef: string } | null>(null); const [syncError, setSyncError] = useState(''); const [archiveConfirm, setArchiveConfirm] = useState(false); const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null); const [credentialRows, setCredentialRows] = useState([]); const [confirm, setConfirm] = useState<{ action: string; fields: Record; text: string } | null>(null); const request = (action: string, data: Record = {}, requestId?: string) => b2Request(project.projectRef, host.hostRef, action, data, requestId); const refresh = async () => { const value = await request('status'); setStatus(value); setSyncError(''); return value; }; useEffect(() => { let active = true; Promise.all([request('status'), loadProjects()]).then(([value, available]) => { if (!active) return; setStatus(value); if (!value.connected) { setSection('connection'); setImportOpen(true); } setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef)); }).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); }); return () => { active = false; }; }, [host.hostRef, project.projectRef]); useEffect(() => { if (pending) return; let active = true, timer: number; async function sync() { try { if (document.visibilityState === 'visible') { const value = await request('status'); if (active) { setStatus(value); setSyncError(''); } } } catch { if (active) setSyncError('Не удалось обновить список VPS. Показаны последние полученные сведения.'); } finally { if (active) timer = window.setTimeout(sync, 30000); } } timer = window.setTimeout(sync, 30000); return () => { active = false; window.clearTimeout(timer); }; }, [host.hostRef, project.projectRef, pending]); async function run(action: string, data: Record = {}, requestId?: string) { setPending(action); try { const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string; contourId?: string }>(action, data, requestId); if (result.connection) { const { integration_id: applicationId, client_id: clientId } = result.connection; setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) }); setKeyRows((rows) => [...new Set([...rows, applicationId])]); setCredentialRows((rows) => [...new Set([...rows, clientId])]); } if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null); if (action === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null); if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); } if (action === 'contour-connect') { setNewContour(false); setContourName(''); setContourIntent(null); if (result.contourId) setExpanded(rows => [...new Set([...rows, result.contourId!])]); } setCreating(''); setName(''); setCreationIntent(null); try { await refresh(); await onChanged(); } catch (error) { onError(error); } return true; } catch (error) { const value = await refresh().catch(() => null); const recovered = action === 'application-connect' && requestId ? value?.applications?.find(app => app.key === 'app-' + requestId) : null; if (recovered) { setCreating(''); setName(''); setCreationIntent(null); setKeyRows(rows => [...new Set([...rows, recovered.id])]); onError(new Error('Приложение создано, но ключ не получен. Откройте его ключи и выпустите новый. Секрет повторно не показывается.')); } else onError(error); return false; } finally { setPending(''); } } const busy = Boolean(pending), canManage = status?.authority === 'host'; const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id]; function downloadIssuedKey() { if (!issued) return; const url = URL.createObjectURL(new Blob([issued.value + '\n'], { type: 'application/json' })); const link = document.createElement('a'); link.href = url; link.download = 'arnavi-application-key.json'; document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000); } function applicationRow(app: B2Application) { const legacy = app.key === 'legacy-mission-core'; const open = keyRows.includes(app.id), active = app.credentials.some((item) => item.enabled); return
  • {open && !legacy ? <> {canManage ? <> setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: active }, text: active ? `Перевыпустить ключ «${app.name}»? Прежний ключ перестанет работать.` : `Выдать ключ «${app.name}»?` })}> setConfirm({ action: 'application-delete', fields: { integrationId: app.id }, text: `Удалить «${app.name}» со всеми ключами и связями с контурами на этом VPS? Доступ приложения прекратится. Устройства, данные контуров и другие приложения сохранятся.` })}> : null} : null} setKeyRows(toggle(keyRows, app.id))}> } /> {open ?
    {legacy ? <>
    Тип подключения
    Прямая привязка Mission Core
    ID приложения
    {app.id}

    Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.

    : <>
    Доступ приложения
    {Object.entries(app.grants).map(([contourId, grant]) => `${status?.contours?.find(contour => contour.id === contourId)?.name || contourId}: ${{ read: 'чтение', control: 'чтение и команды', manage: 'управление устройствами' }[grant] || grant}`).join('; ')}
    {app.credentials.map((item) => { const keyOpen = credentialRows.includes(item.client_id); const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null; return
  • {item.enabled ? 'Действует' : 'Отозван'}} actions={ setCredentialRows(toggle(credentialRows, item.client_id))}>} /> {keyOpen ?
    ID для сверки
    {item.client_id}
    VPS
    {status?.endpoint}
    {secret ?
    :

    Секрет скрыт. ID ключа можно сверить с полем client_id в сохранённом файле подключения.

    } {item.enabled && canManage ?
    : null}
    : null}
  • ; })} {!app.credentials.length ?

    Ключи ещё не выданы

    : null} } : null} ; } return <> {section === 'contours' && canManage ? { setNewContour(true); setContourName(''); setTargetProject(project.projectRef); setContourIntent(null); }}> : null} {project.access.capabilities.includes('infrastructure.manage') ? setArchiveConfirm(true)}> : null} { setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); } }}>}>
    {syncError ?

    {syncError}

    : null} {section === 'connection' ? <> {status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}} actions={ setImportOpen(!importOpen)}>} /> {importOpen ?
    { const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return; setPending('file'); try { if (file.size > 16384) throw new Error(); const text = await file.text(); JSON.parse(text); setConnection(text); } catch { onError(new Error('Не удалось прочитать файл доступа.')); } finally { setPending(''); } }} /> setConnection(event.target.value)} rows={4} />
    : null} : null} {section === 'contours' ? <> {newContour ?
    setContourName(event.target.value)} /> 0 && !status?.sharedProjects)} options={[{ value: '', label: 'Выбрать проект Device Core' }, ...available.map(item => ({ value: item.projectRef, label: item.name }))]} onChange={projectRef => { if (projectRef) setConfirm({ action: 'link', fields: { contourId: contour.id, targetProjectRef: projectRef }, text: `Подключить «${projects.find(item => item.projectRef === projectRef)?.name}» к «${contour.name}»? Участники проекта получат доступ к устройствам контура в пределах своих прав проекта.` }); }} /> : null} {links.length > 0 && available.length > 0 && !status?.sharedProjects ?

    Для подключения второго проекта нужна миграция общих контуров на сервере Device Core.

    : null}
    Приложения и ключи
    {apps.map(applicationRow)} {!apps.length && creating !== contour.id ?

    Ключи приложений ещё не выданы

    : null} {creating === contour.id ?
    setName(event.target.value)} />