Manage shared ARNavi VPS contours and application keys from infrastructure
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge,
|
||||
TextField, TextAreaField, WindowFooterActions, ConfirmationModal } from '@nodedc/ui-react';
|
||||
import { loadProjects } from '../api';
|
||||
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
|
||||
import { b2Request, type B2Status } from './api';
|
||||
import './b2.css';
|
||||
|
||||
type Section = 'connection' | 'contours' | 'applications';
|
||||
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
|
||||
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
|
||||
onChanged: () => Promise<void>; onError: (error: unknown) => void;
|
||||
}) {
|
||||
const project = workspace.project;
|
||||
const [section, setSection] = useState<Section>('connection');
|
||||
const [status, setStatus] = useState<B2Status | null>(null);
|
||||
const [pending, setPending] = useState('');
|
||||
const [connection, setConnection] = useState('');
|
||||
const [key, setKey] = useState(''); const [name, setName] = useState('');
|
||||
const [contour, setContour] = useState('');
|
||||
const [targetProject, setTargetProject] = useState(project.projectRef);
|
||||
const [projects, setProjects] = useState<ProjectSummary[]>([]);
|
||||
const [issued, setIssued] = useState('');
|
||||
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
|
||||
const request = <T,>(action: string, data: Record<string, unknown> = {}) => b2Request<T>(project.projectRef, host.hostRef, action, data);
|
||||
const refresh = () => request<B2Status>('status').then(setStatus);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setPending('load');
|
||||
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
|
||||
if (!active) return;
|
||||
setStatus(value);
|
||||
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]);
|
||||
async function run(action: string, data: Record<string, unknown> = {}) {
|
||||
setPending(action);
|
||||
try {
|
||||
const result = await request<{ connection?: unknown }>(action, data);
|
||||
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2));
|
||||
if (action === 'connect') setConnection('');
|
||||
await refresh(); await onChanged();
|
||||
} catch (error) { onError(error); } finally { setPending(''); }
|
||||
}
|
||||
const contours = status?.contours || [];
|
||||
const canManage = status?.authority === 'host';
|
||||
const busy = Boolean(pending);
|
||||
return <>
|
||||
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
|
||||
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
|
||||
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' },
|
||||
{ id: 'contours', label: 'Контуры и проекты', icon: 'layers', disabled: !status?.connected },
|
||||
{ id: 'applications', label: 'Приложения и ключи', icon: 'key', disabled: !status?.connected }]}
|
||||
activeSection={section} onSectionChange={(value) => { setSection(value); setKey(''); setName(''); }} onClose={onClose}
|
||||
footer={<WindowFooterActions><Button onClick={onClose}>Закрыть</Button>
|
||||
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
|
||||
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
|
||||
}}><Icon name="refresh" /></IconButton></WindowFooterActions>}>
|
||||
<div className="b2-settings">
|
||||
{section === 'connection' ? <>
|
||||
<SettingsCard title="ARNavi VPS" description="Одно подключение сервера для проектов компании. Устройства разделяются контурами.">
|
||||
<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Проверяем подключение' : status ? 'Не подключён' : 'Состояние не получено'}</StatusBadge>
|
||||
{status?.endpoint ? <p>{status.endpoint}</p> : null}
|
||||
</SettingsCard>
|
||||
<SettingsCard title={status?.connected ? 'Заменить ключ подключения' : 'Подключить сервер'} description="Вставьте ключ, выданный на VPS. После подключения он хранится только на сервере Device Core.">
|
||||
<div className="b2-settings">
|
||||
<TextAreaField label="Ключ подключения" value={connection} autoComplete="off" spellCheck={false}
|
||||
onChange={(event) => setConnection(event.target.value)} rows={5} />
|
||||
<Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>Подключить</Button>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</> : null}
|
||||
{section === 'contours' ? <>
|
||||
<SettingsCard title="Контуры на VPS" description="Связь с проектом определяет, где появятся устройства. Один контур можно подключить к нескольким приложениям.">
|
||||
<div className="b2-settings">
|
||||
{contours.map((item) => {
|
||||
const link = status?.links?.find((value) => value.contourId === item.id);
|
||||
return <div className="b2-resource" key={item.id}><div><strong>{item.name}</strong><small>{item.key}</small></div>
|
||||
<StatusBadge tone={link ? 'success' : 'neutral'}>{link ? projects.find((p) => p.projectRef === link.projectRef)?.name || 'Связан с проектом' : 'Не связан'}</StatusBadge></div>;
|
||||
})}
|
||||
{!contours.length ? <p>На VPS пока нет контуров.</p> : null}
|
||||
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
|
||||
<Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((item) => ({ value: item.projectRef, label: item.name }))} />
|
||||
<Button loading={pending === 'link'} disabled={busy || !contour || !targetProject} onClick={() => void run('link', { contourId: contour, targetProjectRef: targetProject })}>Связать с проектом</Button>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
{canManage ? <SettingsCard title="Новый контур" description="Контур создаётся на VPS и получает собственный реестр устройств.">
|
||||
<div className="b2-settings"><TextField label="Название" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<TextField label="Код контура" value={key} placeholder="robot2b" onChange={(e) => setKey(e.target.value)} />
|
||||
<Button loading={pending === 'contour-create'} disabled={busy || !/^[a-z][a-z0-9-]{0,63}$/.test(key) || !name.trim()}
|
||||
onClick={() => void run('contour-create', { key, name })}>Создать контур</Button></div>
|
||||
</SettingsCard> : null}
|
||||
</> : null}
|
||||
{section === 'applications' ? <>
|
||||
{issued ? <SettingsCard title="Новый ключ приложения" description="Скопируйте ключ и передайте в подключаемое приложение. Позже его можно перевыпустить без потери устройств.">
|
||||
<div className="b2-settings"><TextAreaField label="Ключ" value={issued} readOnly rows={6} />
|
||||
<Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать ключ</Button>
|
||||
<Button onClick={() => setIssued('')}>Скрыть</Button></div>
|
||||
</SettingsCard> : null}
|
||||
{(status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core').map((app) => <SettingsCard key={app.id} title={app.name}
|
||||
description={Object.keys(app.grants).map((id) => contours.find((item) => item.id === id)?.name || id).join(', ')}>
|
||||
<div className="b2-settings">
|
||||
{app.credentials.map((credential) => <div className="b2-resource" key={credential.client_id}>
|
||||
<div><small>{credential.client_id}</small><StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge></div>
|
||||
{credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${app.name}»? Подключённый клиент потеряет доступ.` })}>Отозвать</Button> : null}
|
||||
</div>)}
|
||||
<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: true }, text: `Выдать новый ключ для «${app.name}»? Предыдущие ключи этого приложения перестанут работать. Устройства и история сохранятся.` })}>{app.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>
|
||||
</div>
|
||||
</SettingsCard>)}
|
||||
{canManage ? <SettingsCard title="Подключить новое приложение" description="Для каждого приложения создайте отдельный ключ. Несколько приложений могут работать с одним контуром независимо.">
|
||||
<div className="b2-settings"><TextField label="Название приложения" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<TextField label="Код приложения" value={key} placeholder="robot2b-client" onChange={(e) => setKey(e.target.value)} />
|
||||
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
|
||||
<Button loading={pending === 'application-create'} disabled={busy || !contour || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)}
|
||||
onClick={() => void run('application-create', { key, name, contourId: contour })}>Создать приложение</Button></div>
|
||||
</SettingsCard> : <SettingsCard title="Доступ к контуру" description="Управление ключами доступно через управляющее подключение VPS." />}
|
||||
</> : null}
|
||||
</div>
|
||||
</FeatureSettingsWindow>
|
||||
<ConfirmationModal open={Boolean(confirm)} title="Изменить доступ приложения" description={confirm?.text}
|
||||
confirmLabel="Продолжить" cancelLabel="Отмена" onClose={() => setConfirm(null)}
|
||||
onConfirm={async () => { if (confirm) await run(confirm.action, confirm.fields); setConfirm(null); }} />
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
export type B2Contour = { id: string; key: string; name: string; access?: string };
|
||||
export type B2Application = { id: string; key: string; name: string; authority: 'host' | 'contours';
|
||||
grants: Record<string, string>; credentials: Array<{ client_id: string; enabled: boolean }> };
|
||||
export type B2Status = { connected: boolean; endpoint?: string; authority?: 'host' | 'contours';
|
||||
contours?: B2Contour[]; applications?: B2Application[];
|
||||
links?: Array<{ contourId: string; projectRef: string }> };
|
||||
export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string };
|
||||
const messages: Record<string, string> = {
|
||||
b2_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.',
|
||||
b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.',
|
||||
b2_host_not_connected: 'Сначала подключите VPS.',
|
||||
b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.',
|
||||
b2_key_rejected: 'VPS не принял ключ подключения.',
|
||||
b2_conflict: 'На VPS уже есть запись с такими данными. Обновите список и проверьте результат.',
|
||||
b2_contour_already_linked: 'Этот контур уже связан с другим проектом.',
|
||||
b2_connection_identity_conflict: 'Этот хост уже подключён другим приложением или ключом сервера.',
|
||||
b2_certificate_mismatch: 'Сертификат VPS не соответствует ключу подключения.',
|
||||
b2_private_storage_unavailable: 'Закрытое хранилище ключей ещё не настроено на Device Core.',
|
||||
b2_connection_invalid: 'Не удалось прочитать ключ подключения ARNavi VPS.',
|
||||
b2_company_mismatch: 'Выберите проект той же компании.',
|
||||
device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.',
|
||||
};
|
||||
export async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}): Promise<T> {
|
||||
const response = await fetch('/api/device-manager/b2/infrastructure', {
|
||||
method: 'POST', credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID().replaceAll('-', '') },
|
||||
body: JSON.stringify({ projectRef, hostRef, action, ...fields }),
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
if (!response.ok || body?.ok !== true) throw new Error(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.');
|
||||
return body.result as T;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
.b2-settings { display: grid; gap: var(--nodedc-space-md, 16px); }
|
||||
.b2-settings p { margin: 0; font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
|
||||
.b2-resource { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-sm, 8px); flex-wrap: wrap; }
|
||||
.b2-resource > div { display: grid; gap: 4px; min-width: 0; }
|
||||
.b2-resource strong { font-size: var(--nodedc-font-size-sm); }
|
||||
.b2-resource small { font-size: var(--nodedc-font-size-xs); overflow-wrap: anywhere; color: var(--nodedc-text-secondary); }
|
||||
Reference in New Issue
Block a user