Complete ARNavi VPS onboarding and contextual key controls
Device Core qualification / qualify (push) Successful in 6m45s

This commit is contained in:
DCCONSTRUCTIONS
2026-09-30 23:57:17 +03:00
parent 19aa5e2796
commit 53dbd7483e
11 changed files with 312 additions and 64 deletions
+9 -36
View File
@@ -17,6 +17,7 @@ import {
} from "@nodedc/ui-react";
import { useB2Inventory } from "./b2/useB2Inventory";
import { B2AddHost } from "./b2/B2AddHost";
import { B2HostSettings } from "./b2/B2HostSettings";
import {
@@ -30,7 +31,6 @@ import {
ensureEdge,
ensureInfrastructureDeployment,
ensureInfrastructureEndpoint,
ensureInfrastructureHost,
ensureInfrastructureServiceInstance,
ensureRoute,
registerAdapterVersion,
@@ -308,7 +308,8 @@ export function DeviceControlView({
onCreated={completed}
onError={onError}
/>
<HostDialog
<B2AddHost
key={workspace.project.projectRef + ":" + (dialog === "host")}
open={dialog === "host"}
projectRef={workspace.project.projectRef}
onClose={close}
@@ -316,7 +317,7 @@ export function DeviceControlView({
onError={onError}
/>
<EndpointDialog
key={`${dialogHostRef}:${dialog}`}
key={`EndpointDialog:${dialogHostRef}:${dialog}`}
initialHostRef={dialogHostRef}
open={dialog === "endpoint"}
workspace={workspace}
@@ -325,7 +326,7 @@ export function DeviceControlView({
onError={onError}
/>
<DeploymentDialog
key={`${dialogHostRef}:${dialog}`}
key={`DeploymentDialog:${dialogHostRef}:${dialog}`}
initialHostRef={dialogHostRef}
open={dialog === "deployment"}
workspace={workspace}
@@ -334,7 +335,7 @@ export function DeviceControlView({
onError={onError}
/>
<ServiceInstanceDialog
key={`${dialogHostRef}:${dialog}`}
key={`ServiceInstanceDialog:${dialogHostRef}:${dialog}`}
initialHostRef={dialogHostRef}
open={dialog === "service-instance"}
workspace={workspace}
@@ -567,16 +568,17 @@ function HostsView({
status={<StatusBadge tone={remote ? remote.reachable ? 'success' : 'warning' : freshnessTone(host.telemetry.freshness)}>{remote ? remote.reachable ? 'Подключён' : 'Нет связи' : host.lifecycleState === 'suspended' ? 'В архиве' : freshnessLabel(host.telemetry.freshness)}</StatusBadge>}
actions={<>
{canManageInfrastructure && (isB2(host) || (!host.managementCredentialConfigured && !topology.serviceInstances.some((item) => item.hostRef === host.hostRef))) ? <IconButton label={`Настройки ${host.displayName}`} onClick={() => setSettingsHost(host)}><Icon name="settings" /></IconButton> : null}
<Button size="compact" onClick={() => onSelectHost(host.hostRef)}>Мониторинг</Button>
<IconButton label={`Мониторинг ${host.displayName}`} onClick={() => onSelectHost(host.hostRef)}><Icon name="activity" /></IconButton>
<IconButton label={`Сведения ${host.displayName}`} aria-expanded={expanded} onClick={() => setExpandedHost(expanded ? null : host.hostRef)}><Icon name={expanded ? "chevron-up" : "chevron-down"} /></IconButton>
</>} />
{expanded ? <SettingsCard title="Сведения о хосте">
<CanonicalResourceList>
{isB2(host) ? <li><CanonicalResourceRow title="ARNavi VPS" description={remote?.endpoint} metadata="Адрес получен из ключа сервера" /></li> : null}
{topology.endpoints.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.endpointRef}><CanonicalResourceRow title="Адрес подключения" description={item.endpointUri} /></li>)}
{topology.deployments.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.deploymentRef}><CanonicalResourceRow title={item.displayName} metadata="Развёртывание" /></li>)}
{topology.serviceInstances.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.serviceInstanceRef}><CanonicalResourceRow title={item.displayName} metadata="Сервис" /></li>)}
</CanonicalResourceList>
{canManageInfrastructure ? <div className="b2-actions"><Button disabled={archiving} onClick={() => setArchiveTarget(host)}>{host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button><Button onClick={() => onCreateEndpoint(host.hostRef)}>Адрес</Button><Button onClick={() => onCreateDeployment(host.hostRef)}>Развёртывание</Button><Button onClick={() => onCreateService(host.hostRef)} disabled={!topology.deployments.length}>Сервис</Button></div> : null}
{canManageInfrastructure ? <div className="b2-actions"><Button disabled={archiving} onClick={() => setArchiveTarget(host)}>{host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button>{!isB2(host) ? <><Button onClick={() => onCreateEndpoint(host.hostRef)}>Адрес</Button><Button onClick={() => onCreateDeployment(host.hostRef)}>Развёртывание</Button><Button onClick={() => onCreateService(host.hostRef)} disabled={!topology.deployments.some((item) => item.hostRef === host.hostRef)}>Сервис</Button></> : null}</div> : null}
</SettingsCard> : null}
</li>;
})}</CanonicalResourceList>
@@ -1340,35 +1342,6 @@ function AssetBindingDialog({ workspace, ...props }: DialogBaseProps & { workspa
</FormWindow>;
}
function HostDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: string }) {
const [advanced, setAdvanced] = useState(false);
const [hostKey, setHostKey] = useState("");
const [displayName, setDisplayName] = useState("");
const [providerRef, setProviderRef] = useState("");
const [externalRef, setExternalRef] = useState("");
const [credentialRef, setCredentialRef] = useState("");
return <FormWindow {...props} id="host-form" title="Новый VPS" submit={async () => {
await ensureInfrastructureHost({
projectRef,
hostKey,
displayName,
providerRef: providerRef || null,
externalRef: externalRef || null,
managementCredentialRef: credentialRef || null,
lifecycleState: "active",
});
}}>
<KeyField label="Код VPS" value={hostKey} onChange={setHostKey} />
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
<Button variant="ghost" aria-expanded={advanced} onClick={() => setAdvanced(!advanced)}>Дополнительно</Button>
{advanced ? <>
<TextField label="Провайдер" value={providerRef} onChange={(event) => setProviderRef(event.target.value)} placeholder="provider:beget" />
<TextField label="Идентификатор у провайдера" value={externalRef} onChange={(event) => setExternalRef(event.target.value)} placeholder="provider-resource:vps-123" />
<TextField label="Ссылка на серверный ключ" value={credentialRef} onChange={(event) => setCredentialRef(event.target.value)} placeholder="secret-ref:device-core/host-key" description="Ссылка secret-ref из хранилища сервера." />
</> : null}
</FormWindow>;
}
function EndpointDialog({ workspace, initialHostRef, ...props }: DialogBaseProps & { workspace: ProjectWorkspace; initialHostRef: string | null }) {
const hosts = workspace.ontology.hosts.filter((host) => host.lifecycleState === "active");
const [hostRef, setHostRef] = useState(initialHostRef || hosts[0]?.hostRef || "");
+57
View File
@@ -0,0 +1,57 @@
import { useRef, useState } from 'react';
import { Button, Icon, Select, SettingsCard, TextAreaField, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
import { b2Request } from './api';
import release from './installer-release.json';
import './b2.css';
const installCommand = `sudo python3 ${release.filename} --device-core`;
const keyCommand = 'sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection';
export function B2AddHost({ open, projectRef, onClose, onCreated, onError }: {
open: boolean; projectRef: string; onClose: () => void; onCreated: () => Promise<void>; onError: (error: unknown) => void;
}) {
const [name, setName] = useState('ARNavi VPS'), [connection, setConnection] = useState('');
const [pending, setPending] = useState(false);
const fileInput = useRef<HTMLInputElement>(null);
return <Window open={open} title="Добавить VPS" size="lg" onClose={onClose} footer={
<WindowFooterActions><Button onClick={onClose}>Отмена</Button><Button type="submit" form="b2-add-vps" loading={pending} disabled={pending || !name.trim() || !connection.trim()}>Подключить VPS</Button></WindowFooterActions>
}>
<form id="b2-add-vps" className="b2-settings" onSubmit={async (event) => {
event.preventDefault(); if (pending) return;
setPending(true);
try {
await b2Request(projectRef, '', 'register-host', { name: name.trim(), connection });
setConnection(''); await onCreated();
} catch (error) { onError(error); } finally { setPending(false); }
}}>
<Select label="Поддерживаемый VPS" value="arnavi" onChange={() => undefined} options={[{ value: 'arnavi', label: 'ARNavi VPS' }]} />
<div className="b2-onboarding-grid">
<SettingsCard title="1. Установить сервер" description={`ARNavi VPS ${release.version} · Ubuntu Server 24.04 LTS · x86-64`}>
<div className="b2-settings">
<div className="b2-actions"><Button onClick={() => {
const link = document.createElement('a'); link.href = `/installers/${release.filename}`; link.download = release.filename;
document.body.append(link); link.click(); link.remove();
}}><Icon name="download" />Скачать установщик</Button></div>
<p>Перенесите файл на новый VPS. В его терминале выполните команду и укажите публичный IP или домен.</p>
<TextAreaField label="Установка на VPS" rows={2} readOnly value={installCommand} />
<p>Порты сервера: 19443/TCP для API и 9922/TCP для трекеров. Ключ администратора Device Core создаётся при первой установке.</p>
<TextAreaField label="Получить ключ подключения на VPS" rows={2} readOnly value={keyCommand} />
<p>Скопируйте полученный JSON в блок подключения или загрузите сохранённый файл.</p>
<p className="b2-key-id">SHA-256 установщика: {release.sha256}</p>
</div>
</SettingsCard>
<SettingsCard title="2. Подключить сервер">
<div className="b2-settings">
<TextField label="Название VPS" value={name} maxLength={160} disabled={pending} required onChange={(event) => setName(event.target.value)} />
<Button disabled={pending} onClick={() => fileInput.current?.click()}><Icon name="upload" />Загрузить ключ сервера</Button>
<input ref={fileInput} type="file" hidden accept=".json,application/json" aria-label="Файл ключа сервера" onChange={async (event) => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return;
try { if (file.size > 16384) throw new Error('Файл ключа слишком большой.'); const text = await file.text(); JSON.parse(text); setConnection(text); }
catch { onError(new Error('Не удалось прочитать JSON ключа сервера.')); }
}} />
<TextAreaField label="Ключ администратора VPS · JSON" value={connection} disabled={pending} rows={4} autoComplete="off" spellCheck={false} maxLength={16384} required onChange={(event) => setConnection(event.target.value)} />
</div>
</SettingsCard>
</div>
</form>
</Window>;
}
+38 -18
View File
@@ -21,7 +21,8 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
const [creating, setCreating] = useState(''), [name, setName] = useState('');
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string } | null>(null);
const [history, setHistory] = useState<string[]>([]);
const [issued, setIssued] = useState<{ application: string; value: string } | null>(null);
const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null);
const [credentialRows, setCredentialRows] = useState<string[]>([]);
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
const request = <T,>(action: string, data: Record<string, unknown> = {}, requestId?: string) => b2Request<T>(project.projectRef, host.hostRef, action, data, requestId);
const refresh = () => request<B2Status>('status').then(setStatus);
@@ -37,8 +38,14 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) {
setPending(action);
try {
const result = await request<{ connection?: unknown; id?: string }>(action, data, requestId);
if (result.connection) setIssued({ application: String(data.name || name || 'Приложение'), value: JSON.stringify(result.connection, null, 2) });
const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: 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 === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); }
setCreating(''); setName(''); setCreationIntent(null);
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
@@ -57,17 +64,34 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
const legacy = app.key === 'legacy-mission-core';
const open = keyRows.includes(app.id), active = app.credentials.some((item) => item.enabled);
return <li key={app.id} className="b2-disclosure">
<ResourceRow title={app.name} metadata={legacy ? 'Mission Core · совместимое подключение' : active ? 'Ключ выдан' : 'Нет действующего ключа'}
actions={!legacy ? <IconButton label={`Ключи ${app.name}`} aria-expanded={open} aria-controls={`keys-${app.id}`} onClick={() => setKeyRows(toggle(keyRows, app.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton> : undefined} />
{open && !legacy ? <div id={`keys-${app.id}`} className="b2-disclosure__body">
<ResourceList>{app.credentials.filter((item) => item.enabled || history.includes(app.id)).map((item) => <li key={item.client_id}><ResourceRow
title={<code className="b2-key-id">{item.client_id}</code>} metadata="ID ключа"
status={<StatusBadge>{item.enabled ? 'Действует' : 'Отозван'}</StatusBadge>}
actions={item.enabled && canManage ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: item.client_id }, text: `Отозвать ключ «${app.name}»?` })}>Отозвать</Button> : undefined} /></li>)}</ResourceList>
<div className="b2-actions">
{app.credentials.some((item) => !item.enabled) ? <Button variant="ghost" onClick={() => setHistory(toggle(history, app.id))}>{history.includes(app.id) ? 'Скрыть историю' : 'История ключей'}</Button> : null}
{canManage ? <Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: active }, text: active ? `Перевыпустить ключ «${app.name}»? Прежний ключ перестанет работать.` : `Выдать ключ «${app.name}»?` })}>{active ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button> : null}
</div>
<ResourceRow title={app.name} metadata={legacy ? 'Подключение Mission Core · v1' : active ? 'Ключ выдан' : 'Нет действующего ключа'}
actions={<IconButton label={`Ключи ${app.name}`} aria-expanded={open} aria-controls={`keys-${app.id}`} onClick={() => setKeyRows(toggle(keyRows, app.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>} />
{open ? <div id={`keys-${app.id}`} className="b2-disclosure__body">
{legacy ? <>
<dl className="b2-tracker-facts"><dt>Тип подключения</dt><dd>Прямая привязка Mission Core</dd><dt>ID приложения</dt><dd>{app.id}</dd></dl>
<p>Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.</p>
</> : <>
<ResourceList>{app.credentials.filter((item) => item.enabled || history.includes(app.id)).map((item) => {
const keyOpen = credentialRows.includes(item.client_id);
const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null;
return <li key={item.client_id} className="b2-disclosure">
<ResourceRow title={`Ключ · …${item.client_id.slice(-8)}`} status={<StatusBadge tone={item.enabled ? 'success' : 'neutral'}>{item.enabled ? 'Действует' : 'Отозван'}</StatusBadge>}
actions={<IconButton label={`Сведения ключа ${item.client_id}`} aria-expanded={keyOpen} aria-controls={`credential-${item.client_id}`} onClick={() => setCredentialRows(toggle(credentialRows, item.client_id))}><Icon name={keyOpen ? 'chevron-up' : 'chevron-down'} /></IconButton>} />
{keyOpen ? <div id={`credential-${item.client_id}`} className="b2-disclosure__body">
<dl className="b2-tracker-facts"><dt>ID для сверки</dt><dd><code className="b2-key-id">{item.client_id}</code></dd><dt>VPS</dt><dd>{status?.endpoint}</dd></dl>
{secret ? <SettingsCard title="Ключ подключения приложения" description="Импортируйте файл в приложение с поддержкой ARNavi API v2. Секрет показывается один раз."><div className="b2-settings">
<TextAreaField label="Файл подключения" value={secret.value} readOnly rows={4} />
<div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(secret.value).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued(null)}>Скрыть секрет</Button></div>
</div></SettingsCard> : <p>Секрет скрыт. ID ключа можно сверить с полем client_id в сохранённом файле подключения.</p>}
{item.enabled && canManage ? <div className="b2-actions"><Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: item.client_id }, text: `Отозвать ключ «${app.name}»?` })}>Отозвать ключ</Button></div> : null}
</div> : null}
</li>;
})}</ResourceList>
<div className="b2-actions">
{app.credentials.some((item) => !item.enabled) ? <Button variant="ghost" onClick={() => setHistory(toggle(history, app.id))}>{history.includes(app.id) ? 'Скрыть историю' : 'История ключей'}</Button> : null}
{canManage ? <Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: active }, text: active ? `Перевыпустить ключ «${app.name}»? Прежний ключ перестанет работать.` : `Выдать ключ «${app.name}»?` })}>{active ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button> : null}
</div>
</>}
</div> : null}
</li>;
}
@@ -80,10 +104,6 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
}}><Icon name="refresh" /></IconButton>}>
<div className="b2-settings" aria-busy={busy}>
{issued ? <SettingsCard title={`Ключ · ${issued.application}`} description="Сохраните ключ — повторный просмотр недоступен."><div className="b2-settings">
<TextAreaField label="Ключ подключения приложения" value={issued.value} readOnly rows={4} />
<div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(issued.value).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued(null)}>Скрыть</Button></div>
</div></SettingsCard> : null}
{section === 'connection' ? <>
<ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>}
+2
View File
@@ -12,6 +12,8 @@ const messages: Record<string, string> = {
b2_request_invalid: 'Проверьте параметры: VPS отклонил запрос.',
b2_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.',
b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.',
b2_host_management_required: 'Нужен ключ администратора VPS из установщика. Ключ приложения подходит только для доступа к его контуру.',
b2_host_identity_mismatch: 'Сервер не совпадает с идентификатором в файле подключения.',
b2_host_not_connected: 'Сначала подключите VPS.',
b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.',
b2_key_rejected: 'VPS не принял ключ подключения.',
+4
View File
@@ -11,3 +11,7 @@
.b2-tracker-facts { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr); gap: .65rem 1rem; margin: 0; font-size: var(--nodedc-font-size-sm); }
.b2-tracker-facts dt { color: var(--nodedc-text-muted); }
.b2-tracker-facts dd { margin: 0; overflow-wrap: anywhere; }
.b2-onboarding-grid { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr); gap: var(--nodedc-space-4); align-items: start; }
.b2-onboarding-grid > * { min-width: 0; }
@media (max-width: 760px) { .b2-onboarding-grid { grid-template-columns: minmax(0, 1fr); } }
@@ -0,0 +1,10 @@
{
"version": "0.2.2",
"filename": "nodedc-arnavi-vps-0.2.2.pyz",
"sha256": "de509d4029a0276d42937a5e5f0aacaf7e0851826ad935c0b6679a9212dec2de",
"bytes": 16126396,
"sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git",
"sourceCommit": "c67afcd6a1328f00bef4f86f1b1baea2cf277f45",
"manifestSha256": "dd819af361dee4df4b13e769c3b7a9a7f542f07de30364a6a110b9e6dc8c9108",
"environment": "ubuntu-24.04-amd64"
}