Complete ARNavi VPS onboarding and contextual key controls
Device Core qualification / qualify (push) Successful in 6m45s
Device Core qualification / qualify (push) Successful in 6m45s
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,17 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
test('downloadable VPS installer matches its immutable release metadata and deploy size limit', async () => {
|
||||
const metadata = JSON.parse(await readFile(new URL('../src/b2/installer-release.json', import.meta.url), 'utf8'));
|
||||
assert.match(metadata.filename, /^nodedc-arnavi-vps-\d+\.\d+\.\d+\.pyz$/);
|
||||
assert.equal(metadata.environment, 'ubuntu-24.04-amd64');
|
||||
assert.match(metadata.sourceCommit, /^[a-f0-9]{40}$/);
|
||||
assert.equal(metadata.sourceRepository, 'https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git');
|
||||
const file = await readFile(new URL('../public/installers/' + metadata.filename, import.meta.url));
|
||||
assert.equal(file.length, metadata.bytes);
|
||||
assert.ok(file.length < 16 * 1024 * 1024);
|
||||
assert.equal(createHash('sha256').update(file).digest('hex'), metadata.sha256);
|
||||
assert.equal(file.subarray(0, 2).toString(), 'PK');
|
||||
});
|
||||
@@ -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 || "");
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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>}
|
||||
|
||||
@@ -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 не принял ключ подключения.',
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
# ARNavi VPS: установка и подключение из Device Core
|
||||
|
||||
## Пользовательский путь
|
||||
|
||||
«Инфраструктура → VPS и хосты → +» открывает один диалог с выбором
|
||||
поддерживаемого продукта и двумя блоками. Сейчас поддерживается ARNavi VPS.
|
||||
|
||||
1. Скачать установщик 0.2.2, перенести на новый Ubuntu Server 24.04 LTS x86-64.
|
||||
2. В терминале **этого VPS** выполнить
|
||||
`sudo python3 nodedc-arnavi-vps-0.2.2.pyz --device-core`.
|
||||
Установщик запрашивает публичный IP/домен. Требуются 19443/TCP для API и
|
||||
9922/TCP для трекеров на VPS; это не порты Synology.
|
||||
3. В том же терминале выполнить
|
||||
`sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection`.
|
||||
Это чтение уже созданного закрытого JSON подключения, а не выпуск ещё одного ключа.
|
||||
4. Вставить JSON или загрузить его файлом во второй блок Device Core,
|
||||
указать название и нажать «Подключить VPS».
|
||||
|
||||
Сервер проверяет полномочия пользователя, TLS fingerprint, identity VPS и
|
||||
доступ администратора **до** создания записи. Ключ отдельного приложения
|
||||
не подходит для регистрации VPS. Повторное подключение того же сервера в
|
||||
том же проекте использует существующую запись. Секрет сохраняется только
|
||||
в закрытом хранилище Core, не в журнале аудита.
|
||||
|
||||
Установщик в режиме `--device-core` создаёт администратора без фиктивного
|
||||
Mission Core и без заранее выдуманных контуров. Контуры связываются с уже
|
||||
существующими проектами Device Core через настройки VPS. Существующий VPS
|
||||
с прямой привязкой Mission Core этот режим менять отказывается: для него
|
||||
нужен ранее экспортированный ключ администратора, не повторная установка.
|
||||
|
||||
## Ключи приложений
|
||||
|
||||
Настройки VPS → Контуры → нужный проект → Приложения и ключи.
|
||||
Выпущенный JSON появляется внутри соответствующей строки ключа. Его нужно
|
||||
импортировать в приложение, реализующее ARNavi API v2; он содержит endpoint,
|
||||
TLS fingerprint и OAuth client credentials. Создание ключа само по себе не
|
||||
подключает и не запускает другое приложение. Для отдельного приложения
|
||||
создаётся отдельная интеграция в том же контуре.
|
||||
|
||||
Полный секрет доступен один раз. После скрытия/закрытия остаётся `client_id`
|
||||
для сверки с сохранённым JSON, состояние и отзыв. Перевыпуск явно предупреждает
|
||||
об отключении предыдущего ключа. Отозванные ключи доступны в истории.
|
||||
Строка прямой привязки Mission Core v1 раскрывает её тип и ID; это не OAuth
|
||||
credential и кнопка отзыва ключа v2 не должна притворяться её отключением.
|
||||
|
||||
## Инфраструктурный реестр
|
||||
|
||||
Для подключённого ARNavi VPS строка содержит настройки, круглую кнопку
|
||||
мониторинга и раскрытие сведений. «В архив» обратимо скрывает локальную запись,
|
||||
не удаляет VPS. Ручные действия «Адрес», «Развёртывание», «Сервис» оставлены
|
||||
для общего инфраструктурного реестра, но не предлагаются в обычном ARNavi
|
||||
сценарии. Они регистрируют метаданные, не устанавливают ПО: сервис требует
|
||||
записи развёртывания именно выбранного хоста.
|
||||
|
||||
## Происхождение скачиваемого файла
|
||||
|
||||
Исходный сервер остаётся в отдельном репозитории
|
||||
`SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS`, commit
|
||||
`c67afcd6a1328f00bef4f86f1b1baea2cf277f45`. Device Core раздаёт только
|
||||
неизменяемый официальный установщик из `public/installers`.
|
||||
Метаданные в `src/b2/installer-release.json`; тест проверяет размер и SHA-256.
|
||||
|
||||
Сборка: `scripts/build_vps_host.py` отдельного VPS-репозитория с закреплённым
|
||||
Hydra 26.2.0 archive. Две сборки дали одинаковый SHA-256:
|
||||
`de509d4029a0276d42937a5e5f0aacaf7e0851826ad935c0b6679a9212dec2de`.
|
||||
Размер 16126396 байт, ниже лимита одного файла канонического deploy artifact.
|
||||
Для обновления скачать/собрать новый проверенный релиз в VPS-репозитории,
|
||||
опубликовать его commit, заменить asset и metadata вместе и пройти CI.
|
||||
Нельзя редактировать содержимое PYZ в Device Core или переписывать старый релиз.
|
||||
|
||||
303 серверных теста покрывают пустое состояние, отдельный bootstrap,
|
||||
изоляцию контуров, отказ смены режима и прежнюю привязку. Полная установка
|
||||
0.2.2 на чистую Ubuntu в этой задаче **не выполнялась**. Действующий VPS
|
||||
остаётся на 0.2.1. Прохождение тестов не является актом приёмки новой машины.
|
||||
@@ -32,6 +32,66 @@ export class B2Infrastructure {
|
||||
this.clients.set(source.secret_ref, client);
|
||||
return client;
|
||||
}
|
||||
async verifyConnection(input) {
|
||||
let value;
|
||||
try { value = typeof input === 'string' ? JSON.parse(input) : input; }
|
||||
catch { throw b2Error('b2_connection_invalid'); }
|
||||
const pkg = connectionPackage(value);
|
||||
const remote = this.clientFactory(pkg);
|
||||
const identity = await remote.call('/v2/identity');
|
||||
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
|
||||
const status = await remote.call(pkg.authority === 'host' ? '/v2/management' : '/v2/contours');
|
||||
if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
|
||||
return pkg;
|
||||
}
|
||||
async saveSource(db, project, pkg) {
|
||||
const secret = await this.secrets.save(pkg);
|
||||
const saved = (await db.query(`insert into device_b2_hosts
|
||||
(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
|
||||
values($1,$2,$3,$4,$5,$6,$7,$8)
|
||||
on conflict(owner_scope_id,remote_host_id) do update set
|
||||
secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now()
|
||||
where device_b2_hosts.integration_id=excluded.integration_id
|
||||
and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint
|
||||
and device_b2_hosts.authority=excluded.authority returning id`,
|
||||
[randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0];
|
||||
if (!saved) throw b2Error('b2_connection_identity_conflict', 409);
|
||||
return saved;
|
||||
}
|
||||
async registerHost(actor, input, requestId) {
|
||||
fields(input, ['connection', 'name']);
|
||||
const projectId = ref(input.projectRef, 'project');
|
||||
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
|
||||
const db = await this.pool.connect();
|
||||
try {
|
||||
await db.query('begin');
|
||||
const project = await findProjectWithCapability(db, actor, projectId, 'infrastructure.manage');
|
||||
assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
|
||||
await findProjectWithCapability(db, actor, projectId, 'credential.manage');
|
||||
// A rejected key never leaves an empty host in the user's registry.
|
||||
const pkg = await this.verifyConnection(input.connection);
|
||||
if (pkg.authority !== 'host') throw b2Error('b2_host_management_required', 403);
|
||||
await db.query('select pg_advisory_xact_lock(hashtextextended($1,0))', [project.owner_scope_id + ':' + pkg.host_id]);
|
||||
const saved = await this.saveSource(db, project, pkg);
|
||||
const existing = (await db.query(`select h.host_key from device_b2_host_views v
|
||||
join device_infrastructure_hosts h on h.id=v.host_id
|
||||
where v.source_id=$1 and v.project_id=$2`, [saved.id, projectId])).rows[0];
|
||||
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
|
||||
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
|
||||
projectRef: input.projectRef, hostKey: existing?.host_key || `b2-${saved.id}`,
|
||||
displayName: input.name.trim(), providerRef: null, externalRef: pkg.host_id,
|
||||
managementCredentialRef: null, lifecycleState: 'active',
|
||||
}) });
|
||||
const hostRef = registered.host.hostRef;
|
||||
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
|
||||
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [ref(hostRef, 'host'), projectId, project.owner_scope_id, saved.id]);
|
||||
await db.query(`insert into device_audit_events(id,event_type,actor_ref,payload,project_id)
|
||||
values($1,$2,$3,$4::jsonb,$5)`, [randomUUID(), 'b2.register-host', actor.userRef,
|
||||
JSON.stringify({ projectRef: input.projectRef, hostRef, requestId }), projectId]);
|
||||
await db.query('commit');
|
||||
return { connected: true, hostRef, endpoint: pkg.endpoint, authority: pkg.authority };
|
||||
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
|
||||
}
|
||||
async inventory(actor, input) {
|
||||
fields(input, []);
|
||||
const projectId = ref(input.projectRef, 'project');
|
||||
@@ -105,6 +165,7 @@ export class B2Infrastructure {
|
||||
return remote.call(`/v2/contours/${contourId}/devices/${deviceId}/settings`, request);
|
||||
}
|
||||
async execute(actor, input, requestId) {
|
||||
if (input.action === 'register-host') return this.registerHost(actor, input, requestId);
|
||||
if (input.action === 'inventory') return this.inventory(actor, input);
|
||||
if (input.action === 'tracker') return this.tracker(actor, input);
|
||||
const projectId = ref(input.projectRef, 'project');
|
||||
@@ -138,16 +199,7 @@ export class B2Infrastructure {
|
||||
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
|
||||
const status = pkg.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
|
||||
if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
|
||||
const secret = await this.secrets.save(pkg);
|
||||
const saved = (await db.query(`insert into device_b2_hosts
|
||||
(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
|
||||
values($1,$2,$3,$4,$5,$6,$7,$8)
|
||||
on conflict(owner_scope_id,remote_host_id) do update set
|
||||
secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now()
|
||||
where device_b2_hosts.integration_id=excluded.integration_id
|
||||
and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint
|
||||
and device_b2_hosts.authority=excluded.authority returning id`,
|
||||
[randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0];
|
||||
const saved = await this.saveSource(db, project, pkg);
|
||||
if (!saved) throw b2Error('b2_connection_identity_conflict', 409);
|
||||
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
|
||||
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [hostId, projectId, project.owner_scope_id, saved.id]);
|
||||
|
||||
@@ -264,3 +264,42 @@ test('tracker settings keep project and contour authority across remote calls',
|
||||
await assert.rejects(service.execute(actor,input), /b2_access_denied/);
|
||||
assert.equal(calls.length,2);
|
||||
});
|
||||
|
||||
test('VPS onboarding rejects invalid or application-only credentials without creating a host', async () => {
|
||||
for (const input of ['bad-json', JSON.stringify({ ...pkg, authority: 'contours' }), JSON.stringify(pkg)]) {
|
||||
const repo = repository(); let secrets = 0;
|
||||
const service = new B2Infrastructure({ pool: repo.pool,
|
||||
secrets: { save: async () => { secrets += 1; return 'private-ref'; } },
|
||||
clientFactory: () => ({ call: async (path) => path === '/v2/identity' ? { host_id: input === JSON.stringify(pkg) ? 'foreign-host' : pkg.host_id } : { items: [] } }) });
|
||||
await assert.rejects(service.execute(actor, { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: input }, 'a'.repeat(32)));
|
||||
assert.equal(secrets, 0); assert.deepEqual(repo.writes, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('VPS onboarding reuses the project host and audits no credential material', async () => {
|
||||
const queries = []; let existing = false;
|
||||
const base = repository(); const db = await base.pool.connect(); const original = db.query.bind(db);
|
||||
db.query = async (sql, values) => {
|
||||
queries.push({ sql, values });
|
||||
if (sql.includes('pg_advisory_xact_lock')) return { rows: [] };
|
||||
if (sql.startsWith('insert into device_b2_hosts')) return { rows: [{ id: source.id }] };
|
||||
if (sql.startsWith('select h.host_key')) return { rows: existing ? [{ host_key: 'b2-existing-project-view' }] : [] };
|
||||
if (sql.startsWith('insert into device_infrastructure_hosts')) return { rows: [{ id: hostId, host_key: values[3],
|
||||
display_name: values[4], project_id: projectId, owner_scope_id: ownerId, lifecycle_state: 'active', created: !existing }] };
|
||||
if (sql.startsWith('insert into device_b2_host_views')) { existing = true; return { rows: [] }; }
|
||||
return original(sql, values);
|
||||
};
|
||||
const service = new B2Infrastructure({ pool: base.pool, secrets: { save: async () => 'private-ref' },
|
||||
clientFactory: () => ({ call: async () => ({ host_id: pkg.host_id }) }) });
|
||||
const input = { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: JSON.stringify(pkg) };
|
||||
const first = await service.execute(actor, input, 'a'.repeat(32));
|
||||
const second = await service.execute(actor, input, 'b'.repeat(32));
|
||||
assert.equal(first.hostRef, second.hostRef);
|
||||
assert.equal(queries.filter((q) => q.sql === 'commit').length, 2);
|
||||
const hosts = queries.filter((q) => q.sql.startsWith('insert into device_infrastructure_hosts'));
|
||||
assert.equal(hosts[0].values[3], `b2-${source.id}`);
|
||||
assert.equal(hosts[1].values[3], 'b2-existing-project-view');
|
||||
const audit = queries.filter((q) => q.sql.includes('insert into device_audit_events'));
|
||||
assert.ok(audit.length > 0);
|
||||
assert.ok(!JSON.stringify(audit).includes(pkg.client_secret));
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user