Add direct B2 device enrollment and consolidate VPS controls
Device Core qualification / qualify (push) Successful in 8m6s
Device Core qualification / qualify (push) Successful in 8m6s
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,51 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readB2Usb } from '../src/b2/usb.mjs';
|
||||
function fixture({ model = 231, silence = false, change = false, incomplete = false } = {}) {
|
||||
let stream, closed = false, identities = 0; const writes = [];
|
||||
const port = {
|
||||
getInfo: () => ({ usbVendorId: 0x2e3c, usbProductId: 0x5740 }),
|
||||
async open(options) { assert.equal(options.flowControl, 'none'); },
|
||||
async close() { closed = true; },
|
||||
readable: new ReadableStream({ start(controller) { stream = controller; } }),
|
||||
writable: new WritableStream({ write(bytes) {
|
||||
const command = new TextDecoder().decode(bytes); writes.push(command);
|
||||
if (silence) return;
|
||||
let response;
|
||||
if (command === '>I 7\r\n') {
|
||||
identities++;
|
||||
response = `>DI=${model};0;6\r\n>DN=300\r\n>MN=${change && identities > 1 ? '4' : '3'}23456789012345\r\n>SID0=0\r\n>SID1=0\r\n`;
|
||||
} else { assert.equal(command, '>D 15;0\r\n'); response = '>SF=synthetic-config\r\n'; }
|
||||
if (incomplete) response = response.slice(0, -2);
|
||||
for (let i = 0; i < response.length; i += 7) stream.enqueue(new TextEncoder().encode(response.slice(i, i + 7)));
|
||||
} }),
|
||||
};
|
||||
return { serial: { async requestPort(options) { assert.deepEqual(options.filters, [{ usbVendorId: 0x2e3c, usbProductId: 0x5740 }]); return port; } }, writes, closed: () => closed, stream: () => stream };
|
||||
}
|
||||
test('read-only USB protocol handles fragmented lines and releases port', async () => {
|
||||
const f = fixture(); const result = await readB2Usb({ serial: f.serial, timeoutMs: 100 });
|
||||
assert.equal(result.settings, 'synthetic-config'); assert.equal(result.before.MN, result.after.MN);
|
||||
assert.deepEqual(f.writes, ['>I 7\r\n', '>D 15;0\r\n', '>I 7\r\n']); assert.ok(f.closed());
|
||||
});
|
||||
test('wrong model stops before requesting configuration', async () => {
|
||||
const f = fixture({ model: 999 });
|
||||
await assert.rejects(readB2Usb({ serial: f.serial, timeoutMs: 50 }), /не распознано/);
|
||||
assert.deepEqual(f.writes, ['>I 7\r\n']); assert.ok(f.closed());
|
||||
});
|
||||
test('identity change cannot produce a registration snapshot', async () => {
|
||||
const f = fixture({ change: true }); await assert.rejects(readB2Usb({ serial: f.serial, timeoutMs: 50 }), /изменилось устройство/); assert.ok(f.closed());
|
||||
});
|
||||
test('incomplete response and silence time out and close the port', async () => {
|
||||
for (const options of [{ silence: true }, { incomplete: true }]) {
|
||||
const f = fixture(options); await assert.rejects(readB2Usb({ serial: f.serial, timeoutMs: 15 }), /не ответил/); assert.ok(f.closed());
|
||||
}
|
||||
});
|
||||
test('closing the form aborts a pending read and releases USB', async () => {
|
||||
const f = fixture({ silence: true }), controller = new AbortController();
|
||||
const promise = readB2Usb({ serial: f.serial, signal: controller.signal });
|
||||
setTimeout(() => controller.abort(), 10); await assert.rejects(promise, { name: 'AbortError' }); assert.ok(f.closed());
|
||||
});
|
||||
test('disconnect does not turn a partial snapshot into success', async () => {
|
||||
const f = fixture({ silence: true }); const promise = readB2Usb({ serial: f.serial });
|
||||
setTimeout(() => f.stream().close(), 10); await assert.rejects(promise, /USB отключён/); assert.ok(f.closed());
|
||||
});
|
||||
@@ -17,11 +17,9 @@ import {
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import { useB2Inventory } from "./b2/useB2Inventory";
|
||||
import { B2AddHost } from "./b2/B2AddHost";
|
||||
import { B2HostSettings } from "./b2/B2HostSettings";
|
||||
|
||||
import {
|
||||
archiveHost,
|
||||
createConfigurationRevision,
|
||||
closeAssetBinding,
|
||||
ensureAsset,
|
||||
@@ -84,8 +82,6 @@ type DialogId =
|
||||
| null;
|
||||
|
||||
export function DeviceControlView({
|
||||
selectedHostRef,
|
||||
onSelectHost,
|
||||
view,
|
||||
workspace,
|
||||
session,
|
||||
@@ -93,8 +89,6 @@ export function DeviceControlView({
|
||||
onPoll,
|
||||
onError,
|
||||
}: {
|
||||
selectedHostRef: string | null;
|
||||
onSelectHost: (hostRef: string | null) => void;
|
||||
view: ControlViewId;
|
||||
workspace: ProjectWorkspace;
|
||||
session: DeviceManagerSession;
|
||||
@@ -181,13 +175,10 @@ export function DeviceControlView({
|
||||
) : null}
|
||||
{view === "hosts" ? (
|
||||
<HostsView
|
||||
selectedHostRef={selectedHostRef}
|
||||
onSelectHost={onSelectHost}
|
||||
workspace={workspace}
|
||||
canManageInfrastructure={capabilities.has("infrastructure.manage")}
|
||||
canManageAssets={capabilities.has("asset.manage")}
|
||||
canManageBindings={capabilities.has("binding.manage")}
|
||||
onCreateHost={() => setDialog("host")}
|
||||
onCreateEndpoint={(hostRef) => { setDialogHostRef(hostRef); setDialog("endpoint"); }}
|
||||
onCreateDeployment={(hostRef) => { setDialogHostRef(hostRef); setDialog("deployment"); }}
|
||||
onCreateService={(hostRef) => { setDialogHostRef(hostRef); setDialog("service-instance"); }}
|
||||
@@ -308,14 +299,6 @@ export function DeviceControlView({
|
||||
onCreated={completed}
|
||||
onError={onError}
|
||||
/>
|
||||
<B2AddHost
|
||||
key={workspace.project.projectRef + ":" + (dialog === "host")}
|
||||
open={dialog === "host"}
|
||||
projectRef={workspace.project.projectRef}
|
||||
onClose={close}
|
||||
onCreated={completed}
|
||||
onError={onError}
|
||||
/>
|
||||
<EndpointDialog
|
||||
key={`EndpointDialog:${dialogHostRef}:${dialog}`}
|
||||
initialHostRef={dialogHostRef}
|
||||
@@ -487,12 +470,10 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
|
||||
}
|
||||
|
||||
function HostsView({
|
||||
selectedHostRef, onSelectHost,
|
||||
workspace,
|
||||
canManageInfrastructure,
|
||||
canManageAssets,
|
||||
canManageBindings,
|
||||
onCreateHost,
|
||||
onCreateEndpoint,
|
||||
onCreateDeployment,
|
||||
onCreateService,
|
||||
@@ -503,13 +484,10 @@ function HostsView({
|
||||
onPoll,
|
||||
onError,
|
||||
}: {
|
||||
selectedHostRef: string | null;
|
||||
onSelectHost: (hostRef: string | null) => void;
|
||||
workspace: ProjectWorkspace;
|
||||
canManageInfrastructure: boolean;
|
||||
canManageAssets: boolean;
|
||||
canManageBindings: boolean;
|
||||
onCreateHost: () => void;
|
||||
onCreateEndpoint: (hostRef: string) => void;
|
||||
onCreateDeployment: (hostRef: string) => void;
|
||||
onCreateService: (hostRef: string) => void;
|
||||
@@ -524,41 +502,14 @@ function HostsView({
|
||||
const [expandedHost, setExpandedHost] = useState<string | null>(null);
|
||||
const [showArchive, setShowArchive] = useState(false);
|
||||
const [showAssets, setShowAssets] = useState(false);
|
||||
const [archiveTarget, setArchiveTarget] = useState<InfrastructureHostView | null>(null);
|
||||
const [archiving, setArchiving] = useState(false);
|
||||
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
|
||||
const topology = workspace.ontology;
|
||||
const hosts = topology.hosts.filter((host) => showArchive ? host.lifecycleState === 'suspended' : !['suspended', 'retired'].includes(host.lifecycleState));
|
||||
const selectedHost = topology.hosts.find((host) => host.hostRef === selectedHostRef);
|
||||
const source = b2.data?.hosts.find((host) => host.hostRef === selectedHostRef);
|
||||
const isB2 = (host: InfrastructureHostView) => Boolean(b2.data?.hosts.some((item) => item.hostRef === host.hostRef)) || host.hostKey.startsWith('b2-');
|
||||
const settings = settingsHost ? <B2HostSettings key={settingsHost.hostRef} host={settingsHost} workspace={workspace} onClose={() => setSettingsHost(null)} onChanged={onPoll} onError={onError} /> : null;
|
||||
if (selectedHost) {
|
||||
if (isB2(selectedHost)) return <div className="b2-settings">
|
||||
{settings}
|
||||
<SettingsCard title={selectedHost.displayName} actions={canManageInfrastructure ? <IconButton label={`Настройки ${selectedHost.displayName}`} onClick={() => setSettingsHost(selectedHost)}><Icon name="settings" /></IconButton> : undefined}>
|
||||
<CanonicalResourceList>
|
||||
<li><CanonicalResourceRow title="API ARNavi" description={source?.endpoint} metadata={source ? `Проверено: ${formatDate(source.checkedAt)}` : undefined} status={<StatusBadge tone={source?.reachable ? 'success' : source ? 'warning' : 'neutral'}>{source?.reachable ? 'Доступен' : source ? 'Нет связи' : 'Проверка…'}</StatusBadge>} /></li>
|
||||
<li><CanonicalResourceRow title="Контуры проекта" status={String(source?.contours ?? '—')} /></li>
|
||||
<li><CanonicalResourceRow title="Трекеры проекта" status={String(source?.devices ?? '—')} /></li>
|
||||
<li><CanonicalResourceRow title="Метрики оборудования" status={<StatusBadge>Не подключены</StatusBadge>} /></li>
|
||||
</CanonicalResourceList>
|
||||
</SettingsCard>
|
||||
{b2.error ? <p role="alert">{b2.error}</p> : null}
|
||||
</div>;
|
||||
return <HostTelemetryWorkspace host={selectedHost} services={topology.serviceInstances.filter((item) => item.hostRef === selectedHost.hostRef)} onPoll={onPoll} onError={onError} />;
|
||||
}
|
||||
return <div className="b2-settings">
|
||||
{settings}
|
||||
<ConfirmationModal open={Boolean(archiveTarget)} title={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить хост?' : 'Перенести хост в архив?'} description={archiveTarget?.displayName} confirmLabel={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => {
|
||||
if (!archiveTarget || archiving) return;
|
||||
setArchiving(true);
|
||||
try { await archiveHost(workspace.project.projectRef, archiveTarget.hostRef, archiveTarget.lifecycleState !== 'suspended'); setArchiveTarget(null); await onPoll(); } catch (reason) { onError(reason); } finally { setArchiving(false); }
|
||||
}} />
|
||||
<div className="b2-actions">
|
||||
{topology.hosts.some((host) => host.lifecycleState === 'suspended') ? <Button variant="ghost" onClick={() => setShowArchive(!showArchive)}>{showArchive ? 'К действующим хостам' : 'Архив'}</Button> : null}
|
||||
{canManageInfrastructure ? <IconButton label="Добавить VPS" onClick={onCreateHost}><Icon name="plus" /></IconButton> : null}
|
||||
</div>
|
||||
{topology.hosts.some((host) => host.lifecycleState === 'suspended') ? <div className="b2-actions"><Button variant="ghost" onClick={() => setShowArchive(!showArchive)}>{showArchive ? 'К действующим хостам' : 'Архив'}</Button></div> : null}
|
||||
{b2.error ? <p role="alert">{b2.error}</p> : null}
|
||||
<CanonicalResourceList>{hosts.map((host) => {
|
||||
const remote = b2.data?.hosts.find((item) => item.hostRef === host.hostRef);
|
||||
@@ -568,18 +519,19 @@ 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}
|
||||
<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>{!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}
|
||||
{expanded ? <div className="b2-disclosure__body">
|
||||
{isB2(host) ? <CanonicalResourceList>
|
||||
<li><CanonicalResourceRow title="API ARNavi" description={remote?.endpoint} metadata={remote ? `Проверено: ${formatDate(remote.checkedAt)}` : undefined} status={<StatusBadge tone={remote?.reachable ? 'success' : remote ? 'warning' : 'neutral'}>{remote?.reachable ? 'Доступен' : remote ? 'Нет связи' : 'Проверка…'}</StatusBadge>} /></li>
|
||||
<li><CanonicalResourceRow title="Контуры проекта" status={String(remote?.contours ?? '—')} /></li>
|
||||
<li><CanonicalResourceRow title="Трекеры проекта" status={String(remote?.devices ?? '—')} /></li>
|
||||
<li><CanonicalResourceRow title="Метрики оборудования" status={<StatusBadge>Не подключены</StatusBadge>} /></li>
|
||||
</CanonicalResourceList> : <>
|
||||
<HostTelemetryWorkspace host={host} services={topology.serviceInstances.filter(item => item.hostRef === host.hostRef)} onPoll={onPoll} onError={onError} />
|
||||
{canManageInfrastructure ? <div className="b2-actions"><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></div> : null}
|
||||
</>}
|
||||
</div> : null}
|
||||
</li>;
|
||||
})}</CanonicalResourceList>
|
||||
{!hosts.length ? <p>{showArchive ? 'Архив пуст' : 'Нет подключённых VPS'}</p> : null}
|
||||
|
||||
@@ -58,6 +58,8 @@ import type {
|
||||
ProjectWorkspace,
|
||||
} from "./types";
|
||||
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
|
||||
import { B2AddDevice } from "./b2/B2AddDevice";
|
||||
import { B2AddHost } from "./b2/B2AddHost";
|
||||
import { useB2Inventory } from "./b2/useB2Inventory";
|
||||
import { capabilityLabel, projectRoleLabel } from "./presentationLabels";
|
||||
import {
|
||||
@@ -193,11 +195,12 @@ export function DeviceManagerApp() {
|
||||
const [activeProjectRef, setActiveProjectRef] = useState("");
|
||||
const projectRefCurrent = useRef(activeProjectRef);
|
||||
projectRefCurrent.current = activeProjectRef;
|
||||
const [selectedHostRef, setSelectedHostRef] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [projectDialogOpen, setProjectDialogOpen] = useState(false);
|
||||
const [collectionDialogOpen, setCollectionDialogOpen] = useState(false);
|
||||
const [addHostOpen, setAddHostOpen] = useState(false);
|
||||
const [addDeviceOpen, setAddDeviceOpen] = useState(false);
|
||||
const [enrollmentDialogOpen, setEnrollmentDialogOpen] = useState(false);
|
||||
const [claimEnrollment, setClaimEnrollment] = useState<EnrollmentView | null>(null);
|
||||
const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);
|
||||
@@ -297,7 +300,6 @@ export function DeviceManagerApp() {
|
||||
setInventoryDetail(null);
|
||||
projectRefCurrent.current = projectRef;
|
||||
setWorkspace(null);
|
||||
setSelectedHostRef(null);
|
||||
setActiveProjectRef(projectRef);
|
||||
};
|
||||
|
||||
@@ -318,7 +320,6 @@ export function DeviceManagerApp() {
|
||||
if (ownerRef === activeOwnerRef) return;
|
||||
setActiveOwnerRef(ownerRef);
|
||||
setInventoryDetail(null);
|
||||
setSelectedHostRef(null);
|
||||
setWorkspace(null);
|
||||
const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef);
|
||||
if (nextProject) {
|
||||
@@ -417,8 +418,8 @@ export function DeviceManagerApp() {
|
||||
{activeSection === "devices" && activeProject ? (
|
||||
<IconButton
|
||||
label="Подключить устройство"
|
||||
disabled={!canEnroll || !workspace?.routes.some((route) => route.lifecycleState === "active")}
|
||||
onClick={() => setEnrollmentDialogOpen(true)}
|
||||
disabled={!canEnroll}
|
||||
onClick={() => setAddDeviceOpen(true)}
|
||||
>
|
||||
<Icon name="plus" size={16} />
|
||||
</IconButton>
|
||||
@@ -494,8 +495,10 @@ export function DeviceManagerApp() {
|
||||
expanded={shell.contentExpanded}
|
||||
onExpandedChange={shell.setContentExpanded}
|
||||
onClose={shell.closeView}
|
||||
utilityActions={[...(activeView === "hosts" && selectedHostRef ? [{
|
||||
label: "Вернуться к VPS и хостам", icon: "chevron-left" as const, onClick: () => setSelectedHostRef(null),
|
||||
utilityActions={[...(activeView === 'inventory' && canEnroll ? [{
|
||||
label: 'Добавить устройство', icon: 'plus' as const, onClick: () => setAddDeviceOpen(true),
|
||||
}] : []), ...(activeView === 'hosts' && capabilities.has('infrastructure.manage') ? [{
|
||||
label: 'Добавить VPS', icon: 'plus' as const, onClick: () => setAddHostOpen(true),
|
||||
}] : []), {
|
||||
label: "Обновить данные",
|
||||
icon: "refresh",
|
||||
@@ -504,8 +507,6 @@ export function DeviceManagerApp() {
|
||||
>
|
||||
<ProjectView
|
||||
key={activeProjectRef}
|
||||
selectedHostRef={selectedHostRef}
|
||||
onSelectHost={setSelectedHostRef}
|
||||
view={activeView}
|
||||
workspace={workspace}
|
||||
canManageCollections={canManageCollections}
|
||||
@@ -557,6 +558,8 @@ export function DeviceManagerApp() {
|
||||
}}
|
||||
onError={(reason) => setError(errorText(reason))}
|
||||
/>
|
||||
{addDeviceOpen && workspace ? <B2AddDevice key={activeProjectRef} workspace={workspace} onClose={() => setAddDeviceOpen(false)} onCreated={async () => { setAddDeviceOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} onLegacy={workspace.routes.some(route => route.lifecycleState === 'active') ? () => { setAddDeviceOpen(false); setEnrollmentDialogOpen(true); } : undefined} /> : null}
|
||||
{addHostOpen && activeProject ? <B2AddHost key={activeProjectRef} open projectRef={activeProjectRef} onClose={() => setAddHostOpen(false)} onCreated={async () => { setAddHostOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} /> : null}
|
||||
<EnrollmentDialog
|
||||
open={enrollmentDialogOpen}
|
||||
workspace={workspace}
|
||||
@@ -782,9 +785,7 @@ function EnvironmentBackdrop({
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: {
|
||||
selectedHostRef: string | null;
|
||||
onSelectHost: (hostRef: string | null) => void;
|
||||
function ProjectView({ view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: {
|
||||
view: ViewId;
|
||||
workspace: ProjectWorkspace | null;
|
||||
canManageCollections: boolean;
|
||||
@@ -803,8 +804,6 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
|
||||
if (!workspace) return <div className="device-manager-panel-empty">Загружаем проект…</div>;
|
||||
if (["catalog", "hosts", "infrastructure", "sessions", "bindings", "commands", "audit", "access", "settings"].includes(view)) {
|
||||
return <DeviceControlView
|
||||
selectedHostRef={selectedHostRef}
|
||||
onSelectHost={onSelectHost}
|
||||
view={view as ControlViewId}
|
||||
workspace={workspace}
|
||||
session={session}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Button, Icon, Select, SettingsCard, StatusBadge, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
|
||||
import type { ProjectWorkspace } from '../types';
|
||||
import { b2Request } from './api';
|
||||
import { readB2Usb, supportsB2Usb, type UsbSnapshot } from './usb.mjs';
|
||||
import './b2.css';
|
||||
|
||||
type Host = { hostRef: string; name: string; reachable: boolean; contours: Array<{ id: string; name: string }> };
|
||||
type Preview = { number: number; identifier: string; firmware: string; configuration: { record_count: number }; parameters: Record<string, number> };
|
||||
export function B2AddDevice({ workspace, onClose, onCreated, onLegacy }: {
|
||||
workspace: ProjectWorkspace; onClose: () => void; onCreated: () => Promise<void>;
|
||||
onError: (error: unknown) => void; onLegacy?: () => void;
|
||||
}) {
|
||||
const projectRef = workspace.project.projectRef;
|
||||
const [hosts, setHosts] = useState<Host[]>([]), [hostRef, setHostRef] = useState(''), [contourId, setContourId] = useState('');
|
||||
const [name, setName] = useState(''), [method, setMethod] = useState(supportsB2Usb() ? 'usb' : 'manual');
|
||||
const [imei, setImei] = useState(''), [number, setNumber] = useState('');
|
||||
const [profile, setProfile] = useState(''), [profiles, setProfiles] = useState<Array<{ id: string; name: string }>>([]);
|
||||
const [snapshot, setSnapshot] = useState<UsbSnapshot | null>(null), [preview, setPreview] = useState<Preview | null>(null);
|
||||
const [loading, setLoading] = useState(true), [catalogReady, setCatalogReady] = useState(false), [retry, setRetry] = useState(0);
|
||||
const [reading, setReading] = useState(false), [pending, setPending] = useState(false), [error, setError] = useState('');
|
||||
const controller = useRef<AbortController | null>(null), mounted = useRef(true);
|
||||
useEffect(() => { mounted.current = true; return () => { mounted.current = false; controller.current?.abort(); }; }, []);
|
||||
useEffect(() => {
|
||||
let active = true; setLoading(true); setError('');
|
||||
b2Request<{ hosts: Host[] }>(projectRef, '', 'enrollment-options').then(result => {
|
||||
if (!active) return; setHosts(result.hosts);
|
||||
const first = result.hosts.find(host => host.reachable && host.contours.length);
|
||||
setHostRef(first?.hostRef || ''); setContourId(first?.contours[0]?.id || '');
|
||||
}).catch(reason => { if (active) setError(reason.message); }).finally(() => { if (active) setLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, [projectRef, retry]);
|
||||
useEffect(() => {
|
||||
let active = true; setProfiles([]); setProfile(''); setCatalogReady(false); setSnapshot(null); setPreview(null);
|
||||
if (hostRef && contourId) b2Request<{ profiles: Array<{ id: string; name: string }> }>(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'catalog' } })
|
||||
.then(result => { if (active) { setProfiles(result.profiles); setCatalogReady(true); } })
|
||||
.catch(reason => { if (active) setError(reason.message); });
|
||||
return () => { active = false; };
|
||||
}, [projectRef, hostRef, contourId, retry]);
|
||||
const busy = pending || reading;
|
||||
const host = hosts.find(item => item.hostRef === hostRef);
|
||||
const valid = catalogReady && Boolean(name.trim()) && (method === 'usb' ? Boolean(snapshot && preview) : /^\d{15}$/.test(imei) && /^\d{1,10}$/.test(number) && Number(number) > 0 && Number(number) <= 4294967295);
|
||||
function close() { if (!pending) { controller.current?.abort(); onClose(); } }
|
||||
async function readUsb() {
|
||||
setError(''); setSnapshot(null); setPreview(null); setReading(true);
|
||||
const abort = new AbortController(); controller.current = abort;
|
||||
try {
|
||||
const observed = await readB2Usb({ signal: abort.signal });
|
||||
if (abort.signal.aborted) return;
|
||||
const result = await b2Request<Preview>(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'inspect', usb: observed } });
|
||||
if (!mounted.current || abort.signal.aborted) return;
|
||||
setSnapshot(observed); setPreview(result); setName(current => current || `ARNavi B2 · ${result.number}`);
|
||||
} catch (reason) { if (mounted.current && !abort.signal.aborted) setError(reason instanceof Error ? reason.message : 'Не удалось прочитать USB.'); }
|
||||
finally { if (mounted.current) setReading(false); }
|
||||
}
|
||||
return <Window open title="Добавить устройство" subtitle={workspace.project.name} size="md" onClose={close} footer={
|
||||
<WindowFooterActions><Button disabled={pending} onClick={close}>Отмена</Button><Button form="b2-add-device" type="submit" disabled={!valid || busy} loading={pending}>Добавить устройство</Button></WindowFooterActions>
|
||||
}>
|
||||
<form id="b2-add-device" className="b2-settings" onSubmit={async event => {
|
||||
event.preventDefault(); if (!valid || busy) return; setPending(true); setError('');
|
||||
try {
|
||||
await b2Request(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'register', name: name.trim(),
|
||||
...(method === 'usb' ? { usb: snapshot } : { imei, number: Number(number) }), ...(profile ? { profile_id: profile } : {}) } });
|
||||
setSnapshot(null); await onCreated();
|
||||
} catch (reason) { setError(reason instanceof Error ? reason.message : 'Не удалось добавить устройство.'); }
|
||||
finally { if (mounted.current) setPending(false); }
|
||||
}}>
|
||||
<Select label="Тип устройства" value="arnavi-b2" disabled={busy} onChange={event => { if (event === 'edge') onLegacy?.(); }} options={[{ value: 'arnavi-b2', label: 'ARNavi B2' }, ...(onLegacy ? [{ value: 'edge', label: 'Устройство через Edge' }] : [])]} />
|
||||
<TextField label="Название" value={name} maxLength={160} required disabled={busy} onChange={event => setName(event.target.value)} />
|
||||
{loading ? <p role="status">Загрузка подключённых VPS…</p> : hosts.some(item => item.reachable && item.contours.length) ? <>
|
||||
<Select label="VPS" value={hostRef} disabled={busy} options={hosts.filter(item => item.reachable && item.contours.length).map(item => ({ value: item.hostRef, label: item.name }))} onChange={event => {
|
||||
setHostRef(event); setContourId(hosts.find(item => item.hostRef === event)?.contours[0]?.id || ''); setError('');
|
||||
}} />
|
||||
{(host?.contours.length || 0) > 1 ? <Select label="Контур проекта" value={contourId} disabled={busy} options={host!.contours.map(item => ({ value: item.id, label: item.name }))} onChange={event => setContourId(event)} /> : null}
|
||||
<Select label="Добавление" value={method} disabled={busy} options={[{ value: 'usb', label: 'Прочитать настройки трекера по USB' }, { value: 'manual', label: 'Ввести IMEI и ID вручную' }]} onChange={event => { setMethod(event); setError(''); }} />
|
||||
<Select label="Профиль настроек" value={profile} disabled={busy || !catalogReady} options={[{ value: '', label: method === 'usb' ? 'Сохранить настройки трекера' : 'Настроить после добавления' }, ...profiles.map(item => ({ value: item.id, label: item.name }))]} onChange={event => setProfile(event)} />
|
||||
{method === 'usb' ? <SettingsCard title="USB на этом компьютере">
|
||||
<div className="b2-settings">
|
||||
<p>{supportsB2Usb() ? 'Подключите один ARNavi B2 и выберите его USB-порт.' : 'Откройте Device Core в Chrome или Edge для чтения USB. Здесь доступен ручной ввод.'}</p>
|
||||
{preview ? <><StatusBadge tone="success">Настройки прочитаны</StatusBadge><p>ARNavi B2 · {preview.number} · IMEI {preview.identifier}<br />Прошивка {preview.firmware} · {preview.configuration.record_count} параметров</p></> : null}
|
||||
<Button disabled={!catalogReady || busy || !supportsB2Usb()} loading={reading} onClick={readUsb}><Icon name="refresh" />{preview ? 'Прочитать повторно' : 'Прочитать настройки по USB'}</Button>
|
||||
</div>
|
||||
</SettingsCard> : <><TextField label="IMEI" value={imei} inputMode="numeric" maxLength={15} required disabled={busy} onChange={event => setImei(event.target.value.trim())} /><TextField label="ID трекера" value={number} inputMode="numeric" maxLength={10} required disabled={busy} onChange={event => setNumber(event.target.value.trim())} /></>}
|
||||
{profile ? <p>Профиль сохранится в Device Core. Отправка настроек — в настройках устройства.</p> : null}
|
||||
</> : <SettingsCard title="Нет VPS для этого проекта"><p>{hosts.some(item => !item.reachable) ? 'Проверьте доступность VPS и связь контура с этим проектом.' : 'Подключите VPS и свяжите контур с этим проектом в разделе «Инфраструктура».'}</p></SettingsCard>}
|
||||
{error ? <p role="alert">{error}</p> : null}
|
||||
{!loading && (!catalogReady || error) ? <Button disabled={busy} onClick={() => setRetry(value => value + 1)}>Обновить подключения</Button> : null}
|
||||
</form>
|
||||
</Window>;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
|
||||
import { loadProjects } from '../api';
|
||||
import { archiveHost, loadProjects } from '../api';
|
||||
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
|
||||
import { b2Request, type B2Status, type B2Application } from './api';
|
||||
import './b2.css';
|
||||
@@ -20,7 +20,7 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
|
||||
const [creating, setCreating] = useState(''), [name, setName] = useState('');
|
||||
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string } | null>(null);
|
||||
const [hiddenHistory, setHiddenHistory] = useState<string[]>([]);
|
||||
const [archiveConfirm, setArchiveConfirm] = useState(false);
|
||||
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);
|
||||
@@ -68,7 +68,6 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
<ResourceRow title={app.name} metadata={legacy ? 'Подключение Mission Core · v1' : active ? 'Ключ выдан' : 'Нет действующего ключа'}
|
||||
actions={<>
|
||||
{open && !legacy ? <>
|
||||
<IconButton label={`История ключей ${app.name}`} aria-pressed={!hiddenHistory.includes(app.id)} onClick={() => setHiddenHistory(toggle(hiddenHistory, app.id))}><Icon name={hiddenHistory.includes(app.id) ? 'eye-off' : 'eye'} /></IconButton>
|
||||
{canManage ? <>
|
||||
<IconButton label={`${active ? 'Перевыпустить' : 'Выдать'} ключ ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: active }, text: active ? `Перевыпустить ключ «${app.name}»? Прежний ключ перестанет работать.` : `Выдать ключ «${app.name}»?` })}><Icon name="plus" /></IconButton>
|
||||
<IconButton label={`Удалить приложение ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'application-delete', fields: { integrationId: app.id }, text: `Удалить «${app.name}» со всеми ключами и связями с контурами на этом VPS? Доступ приложения прекратится. Устройства, данные контуров и другие приложения сохранятся.` })}><Icon name="trash" /></IconButton>
|
||||
@@ -81,7 +80,7 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
<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 || !hiddenHistory.includes(app.id)).map((item) => {
|
||||
<ResourceList>{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 <li key={item.client_id} className="b2-disclosure">
|
||||
@@ -107,9 +106,11 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
|
||||
sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]}
|
||||
activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
|
||||
headerActions={<>
|
||||
{project.access.capabilities.includes('infrastructure.manage') ? <IconButton label={host.lifecycleState === 'suspended' ? 'Восстановить VPS' : 'Перенести VPS в архив'} disabled={busy} onClick={() => setArchiveConfirm(true)}><Icon name={host.lifecycleState === 'suspended' ? 'refresh' : 'trash'} /></IconButton> : null}
|
||||
<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>}>
|
||||
}}><Icon name="refresh" /></IconButton></>}>
|
||||
<div className="b2-settings" aria-busy={busy}>
|
||||
{section === 'connection' ? <>
|
||||
<ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
|
||||
@@ -159,6 +160,10 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
})}</ResourceList> : null}
|
||||
</div>
|
||||
</FeatureSettingsWindow>
|
||||
<ConfirmationModal open={archiveConfirm} title={host.lifecycleState === 'suspended' ? 'Восстановить VPS?' : 'Перенести VPS в архив?'} description={`${host.displayName}. Изменится только запись в этом проекте. Сервер, устройства и подключения других проектов сохранятся.`} confirmLabel={host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => setArchiveConfirm(false)} onConfirm={async () => {
|
||||
if (busy) return; setPending('archive');
|
||||
try { await archiveHost(project.projectRef, host.hostRef, host.lifecycleState !== 'suspended'); setArchiveConfirm(false); await onChanged(); onClose(); } catch (error) { onError(error); } finally { setPending(''); }
|
||||
}} />
|
||||
<ConfirmationModal open={Boolean(confirm)} title={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Ключ приложения'} description={confirm?.text} confirmLabel={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Подтвердить'} cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && !busy && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"version": "0.2.3",
|
||||
"filename": "nodedc-arnavi-vps-0.2.3.pyz",
|
||||
"sha256": "0d52c38d0e8afd7c1d72bb59e01d20328f8ac2cd8bb2abfd50f3d265db4bcaf4",
|
||||
"bytes": 16126822,
|
||||
"version": "0.2.4",
|
||||
"filename": "nodedc-arnavi-vps-0.2.4.pyz",
|
||||
"sha256": "242b6e04f8d38711aa707da67e96f0a2374cbb25b7e79934a58367a34e9a20e6",
|
||||
"bytes": 16129185,
|
||||
"sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git",
|
||||
"sourceCommit": "973e994f02176d438e8ff42f17baccc5fddb6184",
|
||||
"manifestSha256": "b5aa33a08addace744b0ffecc23777fbe56a8d1ea58f6dd59e5161082a6a847a",
|
||||
"sourceCommit": "881f68dbad9f8fdde2f0f4693de549cff45cacfa",
|
||||
"manifestSha256": "f23e6cf7048ce5e8d17720933a13c3bef5ee9b523c194b4f07f874f372a25484",
|
||||
"environment": "ubuntu-24.04-amd64"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export type UsbSnapshot = { before: Record<string, string>; settings: string; after: Record<string, string> };
|
||||
export function supportsB2Usb(): boolean;
|
||||
export function readB2Usb(options?: { signal?: AbortSignal }): Promise<UsbSnapshot>;
|
||||
@@ -0,0 +1,71 @@
|
||||
/** Read-only B2 transport. The VPS validates the vendor CRC and configuration schema. */
|
||||
export function supportsB2Usb(serial = globalThis.navigator?.serial) {
|
||||
return Boolean(serial?.requestPort);
|
||||
}
|
||||
export async function readB2Usb({ serial = globalThis.navigator?.serial, signal, timeoutMs = 10000 } = {}) {
|
||||
if (!supportsB2Usb(serial)) throw new Error('Чтение USB доступно в Chrome или Edge на этом компьютере. Можно добавить устройство по IMEI и ID.');
|
||||
signal?.throwIfAborted();
|
||||
// Keep the browser chooser in the initiating user gesture.
|
||||
const port = await serial.requestPort({ filters: [{ usbVendorId: 0x2e3c, usbProductId: 0x5740 }] });
|
||||
signal?.throwIfAborted();
|
||||
const info = port.getInfo();
|
||||
if (info.usbVendorId !== 0x2e3c || info.usbProductId !== 0x5740) throw new Error('Выберите USB-порт ARNavi B2.');
|
||||
let reader, writer, pump, opened = false, buffer = '', failure, wake;
|
||||
const encoder = new TextEncoder(), decoder = new TextDecoder('ascii');
|
||||
const notify = () => { wake?.(); wake = undefined; };
|
||||
const abort = () => { failure = new DOMException('Чтение отменено', 'AbortError'); notify(); };
|
||||
signal?.addEventListener('abort', abort, { once: true });
|
||||
try {
|
||||
await port.open({ baudRate: 9600, dataBits: 8, stopBits: 1, parity: 'none', flowControl: 'none' });
|
||||
opened = true; signal?.throwIfAborted();
|
||||
reader = port.readable.getReader(); writer = port.writable.getWriter();
|
||||
pump = (async () => {
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) throw new Error('USB отключён до завершения чтения.');
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
if (buffer.length > 262144) throw new Error('Ответ USB превышает допустимый размер.');
|
||||
notify();
|
||||
}
|
||||
} catch (error) { failure = error; notify(); }
|
||||
})();
|
||||
async function command(bytes, required) {
|
||||
if (failure) throw failure;
|
||||
const offset = buffer.length;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
// The transport has no configuration-write or physical-control operation.
|
||||
let writeTimer;
|
||||
try {
|
||||
await Promise.race([writer.write(encoder.encode(bytes)), new Promise((_, reject) => {
|
||||
writeTimer = setTimeout(() => reject(new Error('USB-порт не принял запрос.')), timeoutMs);
|
||||
})]);
|
||||
} finally { clearTimeout(writeTimer); }
|
||||
while (true) {
|
||||
if (failure) throw failure;
|
||||
const fields = Object.fromEntries([...buffer.slice(offset).matchAll(/^(?:> )?>([A-Z][A-Z0-9]*)=([^\r\n]*)\r?\n/gm)].map(m => [m[1], m[2]]));
|
||||
if (required.every(key => Object.hasOwn(fields, key))) return Object.fromEntries(required.map(key => [key, fields[key]]));
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) throw new Error('Трекер не ответил по USB. Проверьте кабель и закройте другие программы, использующие этот порт.');
|
||||
await new Promise(resolve => { const timer = setTimeout(() => { wake = undefined; resolve(); }, remaining); wake = () => { clearTimeout(timer); resolve(); }; });
|
||||
}
|
||||
}
|
||||
const keys = ['DI', 'DN', 'MN', 'SID0', 'SID1'];
|
||||
const before = await command('>I 7\r\n', keys);
|
||||
if (!/^231;[0-9]{1,5};[0-9]{1,5}(;[0-9]{1,5})?$/.test(before.DI) || !/^\d{15}$/.test(before.MN) || !/^\d{1,10}$/.test(before.DN)) throw new Error('Подключённое устройство не распознано как ARNavi B2.');
|
||||
const settings = (await command('>D 15;0\r\n', ['SF'])).SF;
|
||||
const after = await command('>I 7\r\n', keys);
|
||||
if (keys.some(key => before[key] !== after[key])) throw new Error('Во время чтения изменилось устройство. Повторите чтение USB.');
|
||||
return { before, settings, after };
|
||||
} catch (error) {
|
||||
if (error?.name === 'NotFoundError') throw new Error('USB-порт не выбран.');
|
||||
if (error?.name === 'NetworkError') throw new Error('USB-порт недоступен. Закройте конфигуратор и повторите чтение.');
|
||||
throw error;
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', abort);
|
||||
if (reader) { await reader.cancel().catch(() => {}); await pump; reader.releaseLock(); }
|
||||
writer?.releaseLock();
|
||||
if (opened) await port.close().catch(() => {});
|
||||
buffer = '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
# Устройства и VPS: добавление из шапки
|
||||
|
||||
Кнопка в шапке «Устройства» открывает форму на общих компонентах Design Guideline:
|
||||
тип, название, VPS, профиль, USB или ручные IMEI/ID. Эталон композиции — форма
|
||||
добавления независимого устройства в Mission Core. Edge-подключение сохранено
|
||||
отдельным типом там, где у проекта есть активный маршрут.
|
||||
|
||||
Прямое добавление B2 не зависит от Edge. Backend проверяет `device.enroll`,
|
||||
активный хост, связь контура с проектом и идентичность удалённого VPS до передачи
|
||||
запроса. VPS 0.2.4 атомарно сохраняет реестр, профиль и квитанцию; повтор запроса
|
||||
не создаёт дубль. Назначение ранее зарегистрированного устройства не изменяется.
|
||||
|
||||
USB читает операторский браузер через Web Serial, доступный в Chrome/Edge.
|
||||
Пользователь выбирает один порт ARNavi B2. Разрешены только чтения `>I 7` и
|
||||
`>D 15;0`; ответы ограничены по времени и размеру, устройство сверяется до/после,
|
||||
порт закрывается при завершении и отмене. CRC и параметры проверяются VPS тем же
|
||||
кодеком, что использует сервер. Настройки сохраняются, физического применения при
|
||||
добавлении нет. Не поддерживающий Web Serial браузер предлагает ручной ввод.
|
||||
|
||||
«VPS и хосты»: плюс находится в шапке; общие данные/мониторинг раскрываются
|
||||
стрелкой в строке. Архивирование перенесено в круглую корзину настроек VPS,
|
||||
восстановление остаётся доступно в архиве. История ключей раскрывается вместе
|
||||
с приложением, отдельного глазика нет. Жёлтое видео и общие компоненты не менялись.
|
||||
|
||||
Проверки: 298 Node tests, TypeScript; 315 VPS tests (изолированный TCP отдельно
|
||||
вне ограничения loopback песочницы), ruff; 74 теста совместимости Mission Core.
|
||||
Реальная форма Mission Core прочитала B2 по USB: firmware 0.06. Это эталонная
|
||||
проверка; собственный путь Web Serial требует отдельного браузерного подтверждения.
|
||||
@@ -164,10 +164,67 @@ export class B2Infrastructure {
|
||||
// borrow the host administrator credential from another project.
|
||||
return remote.call(`/v2/contours/${contourId}/devices/${deviceId}/settings`, request);
|
||||
}
|
||||
async enrollmentOptions(actor, input) {
|
||||
fields(input, []);
|
||||
const projectId = ref(input.projectRef, 'project');
|
||||
const db = await this.pool.connect();
|
||||
let sources;
|
||||
try {
|
||||
await db.query('begin');
|
||||
await findProjectWithCapability(db, actor, projectId, 'device.enroll');
|
||||
sources = (await db.query(`select s.*, v.host_id, h.display_name,
|
||||
coalesce((select json_agg(l.contour_id order by l.contour_id) from device_b2_contour_links l
|
||||
where l.source_id=s.id and l.project_id=v.project_id), '[]'::json) as contour_ids
|
||||
from device_b2_hosts s join device_b2_host_views v on v.source_id=s.id
|
||||
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
|
||||
where v.project_id=$1 and h.lifecycle_state='active'`, [projectId])).rows;
|
||||
await db.query('commit');
|
||||
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
|
||||
return { hosts: await Promise.all(sources.map(async source => {
|
||||
const host = { hostRef: `host:${source.host_id}`, name: source.display_name };
|
||||
try {
|
||||
const remote = await this.clientFor(source);
|
||||
const identity = await remote.call('/v2/identity');
|
||||
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
|
||||
const contours = (await remote.call('/v2/contours')).items
|
||||
.filter(item => source.contour_ids.includes(item.id) && item.access === 'manage')
|
||||
.map(({ id, name }) => ({ id, name }));
|
||||
return { ...host, reachable: true, contours };
|
||||
} catch { return { ...host, reachable: false, contours: [] }; }
|
||||
})) };
|
||||
}
|
||||
async enrollment(actor, input) {
|
||||
fields(input, ['contourId', 'request']);
|
||||
const projectId = ref(input.projectRef, 'project'), hostId = ref(input.hostRef, 'host');
|
||||
const contourId = opaque(input.contourId), request = input.request;
|
||||
if (!request || typeof request !== 'object' || Array.isArray(request)
|
||||
|| !['catalog', 'inspect', 'register'].includes(request.action)) throw b2Error('b2_request_invalid');
|
||||
const db = await this.pool.connect();
|
||||
let source;
|
||||
try {
|
||||
await db.query('begin');
|
||||
await findProjectWithCapability(db, actor, projectId, 'device.enroll');
|
||||
source = (await db.query(`select s.* from device_b2_hosts s
|
||||
join device_b2_host_views v on v.source_id=s.id
|
||||
join device_b2_contour_links l on l.source_id=s.id and l.project_id=v.project_id
|
||||
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
|
||||
where v.host_id=$1 and v.project_id=$2 and l.contour_id=$3 and h.lifecycle_state='active'`,
|
||||
[hostId, projectId, contourId])).rows[0];
|
||||
if (!source) throw b2Error('b2_access_denied', 403);
|
||||
await db.query('commit');
|
||||
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
|
||||
const remote = await this.clientFor(source);
|
||||
const identity = await remote.call('/v2/identity');
|
||||
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
|
||||
// Only the selected project's linked contour may receive identity/configuration.
|
||||
return remote.call(`/v2/contours/${contourId}/enrollment`, 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);
|
||||
if (input.action === 'enrollment-options') return this.enrollmentOptions(actor, input);
|
||||
if (input.action === 'enrollment') return this.enrollment(actor, input);
|
||||
const projectId = ref(input.projectRef, 'project');
|
||||
const hostId = ref(input.hostRef, 'host');
|
||||
const action = input.action;
|
||||
|
||||
@@ -318,3 +318,45 @@ test('application deletion requires company and credential authority and forward
|
||||
assert.deepEqual(calls, [{ path: '/v2/management/applications/delete', body: { integration_id: input.integrationId } }]);
|
||||
assert.equal(repo.writes.at(-1).values[1], 'b2.application-delete');
|
||||
});
|
||||
|
||||
test('enrollment options reveal only managed contours linked to the current active project', async () => {
|
||||
const own = 'a'.repeat(32), foreign = 'b'.repeat(32); const repo = repository();
|
||||
const db = await repo.pool.connect(), original = db.query; let released = false;
|
||||
db.release = () => { released = true; };
|
||||
db.query = async (sql, values) => {
|
||||
if (sql.includes('from device_b2_hosts')) {
|
||||
assert.match(sql, /l.project_id=v.project_id/); assert.match(sql, /h.lifecycle_state='active'/);
|
||||
assert.deepEqual(values, [projectId]); return { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [own] }] };
|
||||
}
|
||||
return original(sql, values);
|
||||
};
|
||||
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
|
||||
assert.ok(released);
|
||||
return path === '/v2/identity' ? { host_id: pkg.host_id } : { items: [{ id: own, name: 'Own', access: 'manage' }, { id: foreign, name: 'Foreign', access: 'manage' }] };
|
||||
} }) });
|
||||
const result = await service.execute(actor, { projectRef: `project:${projectId}`, action: 'enrollment-options' });
|
||||
assert.deepEqual(result.hosts[0].contours, [{ id: own, name: 'Own' }]); assert.ok(!JSON.stringify(result).includes('Foreign'));
|
||||
});
|
||||
|
||||
test('enrollment validates project capability, active host and contour before forwarding USB', async () => {
|
||||
const own = 'a'.repeat(32), foreign = 'b'.repeat(32); const repo = repository();
|
||||
const db = await repo.pool.connect(), original = db.query; const calls = [];
|
||||
db.query = async (sql, values) => {
|
||||
if (sql.includes('from device_b2_hosts')) {
|
||||
assert.match(sql, /l.project_id=v.project_id/); assert.match(sql, /h.lifecycle_state='active'/);
|
||||
return { rows: values[0] === hostId && values[1] === projectId && values[2] === own ? [source] : [] };
|
||||
}
|
||||
return original(sql, values);
|
||||
};
|
||||
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
|
||||
calls.push(path); return path === '/v2/identity' ? { host_id: pkg.host_id } : { accepted: body.action };
|
||||
} }) });
|
||||
const input = { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'enrollment', contourId: own, request: { action: 'register', name: 'B2', imei: '323456789012345', number: 300 } };
|
||||
await assert.rejects(service.execute(actor, { ...input, contourId: foreign }), /b2_access_denied/);
|
||||
assert.deepEqual(calls, []);
|
||||
assert.deepEqual(await service.execute(actor, input), { accepted: 'register' });
|
||||
assert.deepEqual(calls, ['/v2/identity', `/v2/contours/${own}/enrollment`]);
|
||||
const denied = new B2Infrastructure({ pool: repository({ role: 'viewer' }).pool, secrets: { read: async () => assert.fail('no credentials') } });
|
||||
await assert.rejects(denied.execute({ ...actor, hubRole: 'member' }, input));
|
||||
await assert.rejects(denied.execute({ ...actor, hubRole: 'member' }, { projectRef: input.projectRef, action: 'enrollment-options' }));
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user