Restructure ARNavi contour UX and expose project-scoped VPS inventory
Device Core qualification / qualify (push) Successful in 7m42s
Device Core qualification / qualify (push) Successful in 7m42s
This commit is contained in:
@@ -84,7 +84,7 @@ test("Device Core overview follows the Mission Core landing-stage geometry", asy
|
||||
assert.ok(!client.includes('<GlassSurface className="device-manager-home"'));
|
||||
});
|
||||
|
||||
test("VPS inventory and monitoring follow the Mission Core system workspace geometry", async () => {
|
||||
test("host hardware monitoring retains the established geometry", async () => {
|
||||
const client = await readFile(
|
||||
new URL("../src/DeviceControlViews.tsx", import.meta.url),
|
||||
"utf8",
|
||||
@@ -99,21 +99,7 @@ test("VPS inventory and monitoring follow the Mission Core system workspace geom
|
||||
);
|
||||
|
||||
for (const expected of [
|
||||
'className="infrastructure-system-workspace"',
|
||||
'className="infrastructure-system-workspace host-monitoring-workspace"',
|
||||
'className="infrastructure-overview-block"',
|
||||
'className="infrastructure-section infrastructure-hosts-block"',
|
||||
'className="infrastructure-host-list"',
|
||||
'className="infrastructure-host-card__summary"',
|
||||
'className="infrastructure-host-card__freshness"',
|
||||
'className="infrastructure-host-card__toggle"',
|
||||
'className="infrastructure-host-card__details"',
|
||||
'className="infrastructure-host-relations"',
|
||||
'aria-expanded={expanded}',
|
||||
'const [expandedHostRefs, setExpandedHostRefs] = useState<Set<string>>',
|
||||
'topology.endpoints.filter((item) => item.hostRef === host.hostRef)',
|
||||
'topology.deployments.filter((item) => item.hostRef === host.hostRef)',
|
||||
'topology.serviceInstances.filter((item) => item.hostRef === host.hostRef)',
|
||||
'className="host-monitoring-series-grid"',
|
||||
'className="host-monitoring-hardware"',
|
||||
'className="host-monitoring-hardware-facts"',
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from "react";
|
||||
import {
|
||||
Button,
|
||||
ConfirmationModal,
|
||||
ResourceList as CanonicalResourceList,
|
||||
ResourceRow as CanonicalResourceRow,
|
||||
GlassSurface,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -13,9 +16,11 @@ import {
|
||||
WindowFooterActions,
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import { useB2Inventory } from "./b2/useB2Inventory";
|
||||
import { B2HostSettings } from "./b2/B2HostSettings";
|
||||
|
||||
import {
|
||||
archiveHost,
|
||||
createConfigurationRevision,
|
||||
closeAssetBinding,
|
||||
ensureAsset,
|
||||
@@ -79,6 +84,8 @@ type DialogId =
|
||||
| null;
|
||||
|
||||
export function DeviceControlView({
|
||||
selectedHostRef,
|
||||
onSelectHost,
|
||||
view,
|
||||
workspace,
|
||||
session,
|
||||
@@ -86,6 +93,8 @@ export function DeviceControlView({
|
||||
onPoll,
|
||||
onError,
|
||||
}: {
|
||||
selectedHostRef: string | null;
|
||||
onSelectHost: (hostRef: string | null) => void;
|
||||
view: ControlViewId;
|
||||
workspace: ProjectWorkspace;
|
||||
session: DeviceManagerSession;
|
||||
@@ -94,6 +103,7 @@ export function DeviceControlView({
|
||||
onError: (reason: unknown) => void;
|
||||
}) {
|
||||
const [dialog, setDialog] = useState<DialogId>(null);
|
||||
const [dialogHostRef, setDialogHostRef] = useState<string | null>(null);
|
||||
const capabilities = new Set(workspace.project.access.capabilities);
|
||||
const platformOwner = session.actor.hubRole === "owner";
|
||||
const close = () => setDialog(null);
|
||||
@@ -171,14 +181,16 @@ 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={() => setDialog("endpoint")}
|
||||
onCreateDeployment={() => setDialog("deployment")}
|
||||
onCreateService={() => setDialog("service-instance")}
|
||||
onCreateEndpoint={(hostRef) => { setDialogHostRef(hostRef); setDialog("endpoint"); }}
|
||||
onCreateDeployment={(hostRef) => { setDialogHostRef(hostRef); setDialog("deployment"); }}
|
||||
onCreateService={(hostRef) => { setDialogHostRef(hostRef); setDialog("service-instance"); }}
|
||||
onRecordHealth={() => setDialog("health-observation")}
|
||||
onCreateAsset={() => setDialog("asset")}
|
||||
onCreateAssetBinding={() => setDialog("asset-binding")}
|
||||
@@ -304,6 +316,8 @@ export function DeviceControlView({
|
||||
onError={onError}
|
||||
/>
|
||||
<EndpointDialog
|
||||
key={`${dialogHostRef}:${dialog}`}
|
||||
initialHostRef={dialogHostRef}
|
||||
open={dialog === "endpoint"}
|
||||
workspace={workspace}
|
||||
onClose={close}
|
||||
@@ -311,6 +325,8 @@ export function DeviceControlView({
|
||||
onError={onError}
|
||||
/>
|
||||
<DeploymentDialog
|
||||
key={`${dialogHostRef}:${dialog}`}
|
||||
initialHostRef={dialogHostRef}
|
||||
open={dialog === "deployment"}
|
||||
workspace={workspace}
|
||||
onClose={close}
|
||||
@@ -318,6 +334,8 @@ export function DeviceControlView({
|
||||
onError={onError}
|
||||
/>
|
||||
<ServiceInstanceDialog
|
||||
key={`${dialogHostRef}:${dialog}`}
|
||||
initialHostRef={dialogHostRef}
|
||||
open={dialog === "service-instance"}
|
||||
workspace={workspace}
|
||||
onClose={close}
|
||||
@@ -468,6 +486,7 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
|
||||
}
|
||||
|
||||
function HostsView({
|
||||
selectedHostRef, onSelectHost,
|
||||
workspace,
|
||||
canManageInfrastructure,
|
||||
canManageAssets,
|
||||
@@ -483,14 +502,16 @@ function HostsView({
|
||||
onPoll,
|
||||
onError,
|
||||
}: {
|
||||
selectedHostRef: string | null;
|
||||
onSelectHost: (hostRef: string | null) => void;
|
||||
workspace: ProjectWorkspace;
|
||||
canManageInfrastructure: boolean;
|
||||
canManageAssets: boolean;
|
||||
canManageBindings: boolean;
|
||||
onCreateHost: () => void;
|
||||
onCreateEndpoint: () => void;
|
||||
onCreateDeployment: () => void;
|
||||
onCreateService: () => void;
|
||||
onCreateEndpoint: (hostRef: string) => void;
|
||||
onCreateDeployment: (hostRef: string) => void;
|
||||
onCreateService: (hostRef: string) => void;
|
||||
onRecordHealth: () => void;
|
||||
onCreateAsset: () => void;
|
||||
onCreateAssetBinding: () => void;
|
||||
@@ -499,199 +520,84 @@ function HostsView({
|
||||
onError: (reason: unknown) => void;
|
||||
}) {
|
||||
const [settingsHost, setSettingsHost] = useState<InfrastructureHostView | null>(null);
|
||||
const [selectedHostRef, setSelectedHostRef] = useState<string | null>(null);
|
||||
useEffect(() => setSettingsHost(null), [workspace.project.projectRef]);
|
||||
const [expandedHostRefs, setExpandedHostRefs] = useState<Set<string>>(() => new Set());
|
||||
const inventoryRef = useRef<HTMLDivElement>(null);
|
||||
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 selectedHost = selectedHostRef
|
||||
? topology.hosts.find((host) => host.hostRef === selectedHostRef) ?? null
|
||||
: null;
|
||||
useEffect(() => {
|
||||
if (selectedHostRef) return;
|
||||
resetApplicationPanelScroll(inventoryRef.current);
|
||||
}, [selectedHostRef]);
|
||||
const toggleHost = (hostRef: string) => {
|
||||
setExpandedHostRefs((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(hostRef)) next.delete(hostRef);
|
||||
else next.add(hostRef);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
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) {
|
||||
return (
|
||||
<HostTelemetryWorkspace
|
||||
host={selectedHost}
|
||||
services={topology.serviceInstances.filter((service) => service.hostRef === selectedHost.hostRef)}
|
||||
onBack={() => setSelectedHostRef(null)}
|
||||
onPoll={onPoll}
|
||||
onError={onError}
|
||||
/>
|
||||
);
|
||||
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={source?.contours ?? '—'} /></li>
|
||||
<li><CanonicalResourceRow title="Трекеры проекта" status={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="infrastructure-system-workspace" ref={inventoryRef}>
|
||||
{settingsHost ? <B2HostSettings key={workspace.project.projectRef + settingsHost.hostRef} host={settingsHost} workspace={workspace} onClose={() => setSettingsHost(null)} onChanged={onPoll} onError={onError} /> : null}
|
||||
<section className="infrastructure-overview-block">
|
||||
<div className="infrastructure-workspace-lead">
|
||||
<div>
|
||||
<span className="infrastructure-eyebrow">ИНФРАСТРУКТУРА / VPS И ХОСТЫ</span>
|
||||
<h2>VPS и хосты</h2>
|
||||
<p>Вычислительные узлы проекта, их подключения и запущенные сервисы.</p>
|
||||
</div>
|
||||
{canManageInfrastructure ? (
|
||||
<div className="infrastructure-workspace-actions">
|
||||
<Button size="compact" variant="primary" onClick={onCreateHost}>Новый VPS</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="infrastructure-overview-grid" aria-label="Сводка инфраструктуры">
|
||||
<InfrastructureCount label="ХОСТЫ" value={topology.hosts.length} detail={`${topology.hosts.filter((host) => host.telemetry.freshness === "fresh").length} со свежими данными`} />
|
||||
<InfrastructureCount label="ENDPOINTS" value={topology.endpoints.length} detail="точки подключения" />
|
||||
<InfrastructureCount label="DEPLOYMENTS" value={topology.deployments.length} detail="развёрнутые контуры" />
|
||||
<InfrastructureCount label="SERVICES" value={topology.serviceInstances.length} detail="экземпляры сервисов" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="infrastructure-section infrastructure-hosts-block">
|
||||
<InfrastructureSectionHeading
|
||||
eyebrow="ВЫЧИСЛИТЕЛЬНЫЕ УЗЛЫ"
|
||||
title="Зарегистрированные хосты"
|
||||
description="Компактный список VPS. Раскройте только тот хост, связи которого нужно посмотреть."
|
||||
status={russianCount(topology.hosts.length, "хост", "хоста", "хостов")}
|
||||
actions={canManageInfrastructure ? <>
|
||||
<Button size="compact" onClick={onRecordHealth}>Наблюдение</Button>
|
||||
<Button size="compact" onClick={onCreateEndpoint} disabled={!topology.hosts.length}>Endpoint</Button>
|
||||
<Button size="compact" onClick={onCreateDeployment} disabled={!topology.hosts.length}>Deployment</Button>
|
||||
<Button size="compact" variant="primary" onClick={onCreateService} disabled={!topology.deployments.length}>Service</Button>
|
||||
</> : null}
|
||||
/>
|
||||
{topology.hosts.length ? (
|
||||
<div className="infrastructure-host-list">
|
||||
{topology.hosts.map((host) => {
|
||||
const hostEndpoints = topology.endpoints.filter((item) => item.hostRef === host.hostRef);
|
||||
const hostDeployments = topology.deployments.filter((item) => item.hostRef === host.hostRef);
|
||||
const hostServices = topology.serviceInstances.filter((item) => item.hostRef === host.hostRef);
|
||||
const expanded = expandedHostRefs.has(host.hostRef);
|
||||
const detailsId = `infrastructure-host-details-${host.hostRef.replace(/[^A-Za-z0-9_-]/g, "-")}`;
|
||||
return (
|
||||
<article className="infrastructure-host-card" data-expanded={expanded ? "true" : undefined} key={host.hostRef}>
|
||||
<header className="infrastructure-host-card__summary">
|
||||
<div className="infrastructure-host-card__identity">
|
||||
<span className="infrastructure-eyebrow">COMPUTE HOST</span>
|
||||
<h4>{host.displayName}</h4>
|
||||
<code>{host.externalRef || host.hostKey}</code>
|
||||
</div>
|
||||
<div className="infrastructure-host-card__actions">
|
||||
{canManageInfrastructure ? <IconButton label={`Настройки ${host.displayName}`} onClick={() => setSettingsHost(host)}><Icon name="settings" /></IconButton> : null}
|
||||
<Button size="compact" variant="primary" onClick={() => setSelectedHostRef(host.hostRef)}>Мониторинг</Button>
|
||||
<span
|
||||
className="infrastructure-host-card__freshness"
|
||||
data-freshness={host.telemetry.freshness}
|
||||
role="status"
|
||||
aria-label={freshnessLabel(host.telemetry.freshness)}
|
||||
title={freshnessLabel(host.telemetry.freshness)}
|
||||
/>
|
||||
<IconButton
|
||||
className="infrastructure-host-card__toggle"
|
||||
label={expanded ? `Свернуть ${host.displayName}` : `Развернуть ${host.displayName}`}
|
||||
aria-expanded={expanded}
|
||||
aria-controls={detailsId}
|
||||
onClick={() => toggleHost(host.hostRef)}
|
||||
>
|
||||
<Icon name="chevron-down" size={18} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</header>
|
||||
{expanded ? (
|
||||
<div className="infrastructure-host-card__details" id={detailsId}>
|
||||
<dl className="infrastructure-host-card__facts">
|
||||
<div><dt>Состояние</dt><dd>{host.lifecycleState}</dd></div>
|
||||
<div><dt>Провайдер</dt><dd>{host.providerRef || "Не указан"}</dd></div>
|
||||
<div><dt>Доступ управления</dt><dd>{host.managementCredentialConfigured ? "Настроен" : "Не настроен"}</dd></div>
|
||||
<div><dt>Последнее наблюдение</dt><dd>{formatDate(host.telemetry.observedAt)}</dd></div>
|
||||
</dl>
|
||||
<div className="infrastructure-host-relations">
|
||||
<section>
|
||||
<header><span className="infrastructure-eyebrow">ENDPOINTS</span><strong>{hostEndpoints.length}</strong></header>
|
||||
{hostEndpoints.length ? <div className="infrastructure-registry-list">{hostEndpoints.map((endpoint) => (
|
||||
<InfrastructureRegistryRow key={endpoint.endpointRef} label={endpoint.purpose} title={endpoint.endpointKey} description={endpoint.endpointUri} status={endpoint.lifecycleState} />
|
||||
))}</div> : <p>Точки подключения не зарегистрированы.</p>}
|
||||
</section>
|
||||
<section>
|
||||
<header><span className="infrastructure-eyebrow">DEPLOYMENTS</span><strong>{hostDeployments.length}</strong></header>
|
||||
{hostDeployments.length ? <div className="infrastructure-registry-list">{hostDeployments.map((deployment) => (
|
||||
<InfrastructureRegistryRow key={deployment.deploymentRef} label="DEPLOYMENT" title={deployment.displayName} description={`${deployment.artifactRef} · ${shortDigest(deployment.artifactDigest)}`} status={deployment.lifecycleState} />
|
||||
))}</div> : <p>Развёртывания не зарегистрированы.</p>}
|
||||
</section>
|
||||
<section>
|
||||
<header><span className="infrastructure-eyebrow">SERVICES</span><strong>{hostServices.length}</strong></header>
|
||||
{hostServices.length ? <div className="infrastructure-registry-list">{hostServices.map((service) => {
|
||||
const edge = service.edgeRef ? workspace.edges.find((item) => item.edgeRef === service.edgeRef) : null;
|
||||
const runtimeState = edge?.channel.runtimeState || service.health.state;
|
||||
return <InfrastructureRegistryRow key={service.serviceInstanceRef} label={service.serviceRole} title={service.displayName} description={`${service.serviceKey} · ${edge?.displayName || "Edge не связан"}`} status={runtimeState} />;
|
||||
})}</div> : <p>Сервисы не зарегистрированы.</p>}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : <div className="infrastructure-empty">VPS и хосты для проекта пока не зарегистрированы.</div>}
|
||||
</section>
|
||||
|
||||
<section className="infrastructure-section infrastructure-assets-block">
|
||||
<InfrastructureSectionHeading
|
||||
eyebrow="DEVICE ASSETS"
|
||||
title="Объекты и трекеры"
|
||||
description="Стабильные объекты проекта и история привязанных к ним устройств."
|
||||
status={russianCount(topology.assets.length, "объект", "объекта", "объектов")}
|
||||
actions={<>
|
||||
{canManageAssets ? <Button size="compact" onClick={onCreateAsset}>Новый Asset</Button> : null}
|
||||
{canManageBindings ? <Button size="compact" variant="primary" onClick={onCreateAssetBinding} disabled={!topology.assets.length || !workspace.devices.length}>Привязать tracker</Button> : null}
|
||||
</>}
|
||||
/>
|
||||
{topology.assets.length ? (
|
||||
<div className="infrastructure-asset-grid">
|
||||
{topology.assets.map((asset) => {
|
||||
const activeBindings = topology.assetBindings.filter((binding) => binding.assetRef === asset.assetRef && !binding.validTo);
|
||||
return (
|
||||
<GlassSurface className="infrastructure-asset-card" padding="md" tone="soft" key={asset.assetRef}>
|
||||
<div><span className="infrastructure-eyebrow">{asset.assetTypeRef}</span><strong>{asset.displayName}</strong><small>{asset.assetKey}</small></div>
|
||||
<div><StatusBadge tone={statusTone(asset.lifecycleState)}>{asset.lifecycleState}</StatusBadge><small>{activeBindings.length} активных привязок</small></div>
|
||||
</GlassSurface>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : <div className="infrastructure-empty">Объекты проекта пока не созданы.</div>}
|
||||
{topology.assetBindings.length ? (
|
||||
<div className="infrastructure-registry-list">
|
||||
{topology.assetBindings.map((binding) => (
|
||||
<div className="infrastructure-registry-row" key={binding.assetBindingRef}>
|
||||
<div><span className="infrastructure-eyebrow">DEVICE ↔ ASSET</span><strong>{binding.deviceName} → {binding.assetName}</strong><small>{binding.bindingKind} · {formatDate(binding.validFrom)}</small></div>
|
||||
<div><StatusBadge tone={binding.validTo ? "neutral" : "success"}>{binding.validTo ? "Закрыта" : "Активна"}</StatusBadge>{!binding.validTo && canManageBindings ? <Button size="compact" onClick={() => onCloseAssetBinding(binding)}>Закрыть</Button> : null}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
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>
|
||||
);
|
||||
{b2.error ? <p role="alert">{b2.error}</p> : null}
|
||||
<CanonicalResourceList>{hosts.map((host) => {
|
||||
const remote = b2.data?.hosts.find((item) => item.hostRef === host.hostRef);
|
||||
const expanded = expandedHost === host.hostRef;
|
||||
return <li key={host.hostRef}>
|
||||
<CanonicalResourceRow title={host.displayName} metadata={remote?.endpoint || host.providerRef || undefined}
|
||||
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}`} aria-expanded={expanded} onClick={() => setExpandedHost(expanded ? null : host.hostRef)}><Icon name="chevron-down" /></IconButton>
|
||||
</>} />
|
||||
{expanded ? <SettingsCard title="Сведения о хосте">
|
||||
<CanonicalResourceList>
|
||||
{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}
|
||||
</SettingsCard> : null}
|
||||
</li>;
|
||||
})}</CanonicalResourceList>
|
||||
{!hosts.length ? <p>{showArchive ? 'Архив пуст' : 'Нет подключённых VPS'}</p> : null}
|
||||
<Button variant="ghost" onClick={() => setShowAssets(!showAssets)} aria-expanded={showAssets}>Объекты проекта · {topology.assets.length}</Button>
|
||||
{showAssets ? <SettingsCard title="Объекты проекта" actions={canManageAssets ? <IconButton label="Создать объект" onClick={onCreateAsset}><Icon name="plus" /></IconButton> : undefined}>
|
||||
<CanonicalResourceList>{topology.assets.map((asset) => <li key={asset.assetRef}><CanonicalResourceRow title={asset.displayName} metadata={asset.assetTypeRef} /></li>)}</CanonicalResourceList>
|
||||
{canManageBindings ? <Button disabled={!topology.assets.length || !workspace.devices.length} onClick={onCreateAssetBinding}>Привязать трекер</Button> : null}
|
||||
<CanonicalResourceList>{topology.assetBindings.map((binding) => <li key={binding.assetBindingRef}><CanonicalResourceRow title={`${binding.deviceName} → ${binding.assetName}`} status={<StatusBadge>{binding.validTo ? 'Закрыта' : 'Активна'}</StatusBadge>} actions={!binding.validTo && canManageBindings ? <Button onClick={() => onCloseAssetBinding(binding)}>Закрыть привязку</Button> : undefined} /></li>)}</CanonicalResourceList>
|
||||
</SettingsCard> : null}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function HostTelemetryWorkspace({
|
||||
host,
|
||||
services,
|
||||
onBack,
|
||||
onPoll,
|
||||
onError,
|
||||
}: {
|
||||
host: InfrastructureHostView;
|
||||
services: InfrastructureServiceInstanceView[];
|
||||
onBack: () => void;
|
||||
onPoll: () => Promise<void>;
|
||||
onError: (reason: unknown) => void;
|
||||
}) {
|
||||
@@ -734,12 +640,6 @@ function HostTelemetryWorkspace({
|
||||
</div>
|
||||
<div className="infrastructure-workspace-actions">
|
||||
<StatusBadge tone={freshnessTone(telemetry.freshness)}>{freshnessLabel(telemetry.freshness)}</StatusBadge>
|
||||
<IconButton label="Обновить телеметрию" onClick={() => onPoll().catch(onError)}>
|
||||
<Icon name="refresh" size={17} />
|
||||
</IconButton>
|
||||
<IconButton label="Вернуться к VPS и хостам" onClick={onBack}>
|
||||
<Icon name="chevron-left" size={18} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1447,12 +1347,13 @@ function AssetBindingDialog({ workspace, ...props }: DialogBaseProps & { workspa
|
||||
}
|
||||
|
||||
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 / Host" submit={async () => {
|
||||
return <FormWindow {...props} id="host-form" title="Новый VPS" submit={async () => {
|
||||
await ensureInfrastructureHost({
|
||||
projectRef,
|
||||
hostKey,
|
||||
@@ -1463,24 +1364,27 @@ function HostDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: st
|
||||
lifecycleState: "active",
|
||||
});
|
||||
}}>
|
||||
<KeyField label="Host key" value={hostKey} onChange={setHostKey} />
|
||||
<KeyField label="Код VPS" value={hostKey} onChange={setHostKey} />
|
||||
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
|
||||
<TextField label="Provider ref" value={providerRef} onChange={(event) => setProviderRef(event.target.value)} placeholder="provider:beget" />
|
||||
<TextField label="External resource ref" value={externalRef} onChange={(event) => setExternalRef(event.target.value)} placeholder="provider-resource:vps-123" />
|
||||
<TextField label="Management credential ref" value={credentialRef} onChange={(event) => setCredentialRef(event.target.value)} placeholder="secret-ref:device-core/host-key" description="Только server-side secret reference. Пароль или приватный ключ сюда вводить нельзя." />
|
||||
<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, ...props }: DialogBaseProps & { workspace: ProjectWorkspace }) {
|
||||
const hosts = workspace.ontology.hosts;
|
||||
const [hostRef, setHostRef] = useState(hosts[0]?.hostRef ?? "");
|
||||
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 || "");
|
||||
const [endpointKey, setEndpointKey] = useState("");
|
||||
const [purpose, setPurpose] = useState<"management" | "service" | "monitoring">("management");
|
||||
const [endpointUri, setEndpointUri] = useState("");
|
||||
useEffect(() => {
|
||||
if (!hosts.some((item) => item.hostRef === hostRef)) setHostRef(hosts[0]?.hostRef ?? "");
|
||||
}, [hostRef, hosts]);
|
||||
return <FormWindow {...props} id="endpoint-form" title="Host endpoint" disabled={!hostRef} submit={async () => {
|
||||
return <FormWindow {...props} id="endpoint-form" title="Адрес подключения" disabled={!hostRef} submit={async () => {
|
||||
await ensureInfrastructureEndpoint({
|
||||
projectRef: workspace.project.projectRef,
|
||||
hostRef,
|
||||
@@ -1490,20 +1394,20 @@ function EndpointDialog({ workspace, ...props }: DialogBaseProps & { workspace:
|
||||
lifecycleState: "active",
|
||||
});
|
||||
}}>
|
||||
<Select label="Host" value={hostRef} onChange={setHostRef} options={hosts.map((item) => ({ value: item.hostRef, label: item.displayName }))} />
|
||||
<KeyField label="Endpoint key" value={endpointKey} onChange={setEndpointKey} />
|
||||
<Select label="Purpose" value={purpose} onChange={setPurpose} options={[
|
||||
<Select label="VPS" value={hostRef} onChange={setHostRef} options={hosts.map((item) => ({ value: item.hostRef, label: item.displayName }))} />
|
||||
<KeyField label="Код адреса" value={endpointKey} onChange={setEndpointKey} />
|
||||
<Select label="Назначение" value={purpose} onChange={setPurpose} options={[
|
||||
{ value: "management", label: "Management" },
|
||||
{ value: "monitoring", label: "Monitoring" },
|
||||
{ value: "service", label: "Service" },
|
||||
]} />
|
||||
<TextField label="Endpoint URI" value={endpointUri} onChange={(event) => setEndpointUri(event.target.value)} required placeholder="ssh://203.0.113.10:22/" description="HTTPS, SSH или TCP. URI с userinfo, query или fragment будет отклонён." />
|
||||
<TextField label="Адрес" value={endpointUri} onChange={(event) => setEndpointUri(event.target.value)} required placeholder="ssh://203.0.113.10:22/" description="HTTPS, SSH или TCP. URI с userinfo, query или fragment будет отклонён." />
|
||||
</FormWindow>;
|
||||
}
|
||||
|
||||
function DeploymentDialog({ workspace, ...props }: DialogBaseProps & { workspace: ProjectWorkspace }) {
|
||||
const hosts = workspace.ontology.hosts;
|
||||
const [hostRef, setHostRef] = useState(hosts[0]?.hostRef ?? "");
|
||||
function DeploymentDialog({ 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 || "");
|
||||
const [deploymentKey, setDeploymentKey] = useState("");
|
||||
const [displayName, setDisplayName] = useState("");
|
||||
const [artifactRef, setArtifactRef] = useState("");
|
||||
@@ -1511,7 +1415,7 @@ function DeploymentDialog({ workspace, ...props }: DialogBaseProps & { workspace
|
||||
useEffect(() => {
|
||||
if (!hosts.some((item) => item.hostRef === hostRef)) setHostRef(hosts[0]?.hostRef ?? "");
|
||||
}, [hostRef, hosts]);
|
||||
return <FormWindow {...props} id="deployment-form" title="Infrastructure deployment" disabled={!hostRef} submit={async () => {
|
||||
return <FormWindow {...props} id="deployment-form" title="Развёртывание" disabled={!hostRef} submit={async () => {
|
||||
await ensureInfrastructureDeployment({
|
||||
projectRef: workspace.project.projectRef,
|
||||
hostRef,
|
||||
@@ -1522,7 +1426,7 @@ function DeploymentDialog({ workspace, ...props }: DialogBaseProps & { workspace
|
||||
lifecycleState: "active",
|
||||
});
|
||||
}}>
|
||||
<Select label="Host" value={hostRef} onChange={setHostRef} options={hosts.map((item) => ({ value: item.hostRef, label: item.displayName }))} />
|
||||
<Select label="VPS" value={hostRef} onChange={setHostRef} options={hosts.map((item) => ({ value: item.hostRef, label: item.displayName }))} />
|
||||
<KeyField label="Deployment key" value={deploymentKey} onChange={setDeploymentKey} />
|
||||
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
|
||||
<TextField label="Artifact ref" value={artifactRef} onChange={(event) => setArtifactRef(event.target.value)} required placeholder="artifact:device-edge/1.0.0" />
|
||||
@@ -1530,9 +1434,9 @@ function DeploymentDialog({ workspace, ...props }: DialogBaseProps & { workspace
|
||||
</FormWindow>;
|
||||
}
|
||||
|
||||
function ServiceInstanceDialog({ workspace, ...props }: DialogBaseProps & { workspace: ProjectWorkspace }) {
|
||||
const hosts = workspace.ontology.hosts;
|
||||
const [hostRef, setHostRef] = useState(hosts[0]?.hostRef ?? "");
|
||||
function ServiceInstanceDialog({ 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 || "");
|
||||
const matchingDeployments = workspace.ontology.deployments.filter((item) => item.hostRef === hostRef);
|
||||
const [deploymentRef, setDeploymentRef] = useState(matchingDeployments[0]?.deploymentRef ?? "");
|
||||
const [edgeRef, setEdgeRef] = useState("");
|
||||
@@ -1545,7 +1449,7 @@ function ServiceInstanceDialog({ workspace, ...props }: DialogBaseProps & { work
|
||||
setDeploymentRef(matchingDeployments[0]?.deploymentRef ?? "");
|
||||
}
|
||||
}, [deploymentRef, hostRef, hosts, matchingDeployments]);
|
||||
return <FormWindow {...props} id="service-instance-form" title="Service instance" disabled={!hostRef || !deploymentRef} submit={async () => {
|
||||
return <FormWindow {...props} id="service-instance-form" title="Сервис" disabled={!hostRef || !deploymentRef} submit={async () => {
|
||||
await ensureInfrastructureServiceInstance({
|
||||
projectRef: workspace.project.projectRef,
|
||||
hostRef,
|
||||
@@ -1557,7 +1461,7 @@ function ServiceInstanceDialog({ workspace, ...props }: DialogBaseProps & { work
|
||||
lifecycleState: "active",
|
||||
});
|
||||
}}>
|
||||
<Select label="Host" value={hostRef} onChange={setHostRef} options={hosts.map((item) => ({ value: item.hostRef, label: item.displayName }))} />
|
||||
<Select label="VPS" value={hostRef} onChange={setHostRef} options={hosts.map((item) => ({ value: item.hostRef, label: item.displayName }))} />
|
||||
<Select label="Deployment" value={deploymentRef} onChange={setDeploymentRef} options={matchingDeployments.map((item) => ({ value: item.deploymentRef, label: item.displayName }))} />
|
||||
<Select label="Edge role" value={edgeRef} onChange={setEdgeRef} options={[
|
||||
{ value: "", label: "Без Edge registration" },
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Button,
|
||||
ConfirmationModal,
|
||||
ResourceList,
|
||||
ResourceRow,
|
||||
GlassSurface,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -14,6 +17,7 @@ import {
|
||||
createConfigurationRevision,
|
||||
setDesiredConfiguration,
|
||||
updateDevice,
|
||||
archiveDevice,
|
||||
} from "./api";
|
||||
import {
|
||||
accessLabel,
|
||||
@@ -27,6 +31,8 @@ import type {
|
||||
SessionView,
|
||||
} from "./types";
|
||||
|
||||
import { useB2Inventory } from "./b2/useB2Inventory";
|
||||
|
||||
export type DeviceInventoryDetailState = {
|
||||
deviceRef: string;
|
||||
sectionId: string;
|
||||
@@ -100,15 +106,21 @@ export function DeviceInventoryView({
|
||||
onError: (reason: unknown) => void;
|
||||
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
|
||||
}) {
|
||||
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
|
||||
const [typeFilter, setTypeFilter] = useState("all");
|
||||
const [archiveTarget, setArchiveTarget] = useState<DeviceView | null>(null);
|
||||
const [archiving, setArchiving] = useState(false);
|
||||
const [statusFilter, setStatusFilter] = useState("all");
|
||||
const [sortOrder, setSortOrder] = useState("activity");
|
||||
const selectedDevice = workspace.devices.find(
|
||||
(device) => device.deviceRef === detail?.deviceRef,
|
||||
) ?? null;
|
||||
const pendingEnrollments = workspace.enrollments.filter(
|
||||
(enrollment) => enrollment.lifecycleState !== "claimed",
|
||||
(enrollment) => ["pending", "observed"].includes(enrollment.lifecycleState),
|
||||
);
|
||||
const deviceRows = useMemo(() => workspace.devices
|
||||
.filter((device) => statusFilter === "archived" ? device.lifecycleState === "suspended" : !["suspended", "retired"].includes(device.lifecycleState))
|
||||
.filter((device) => typeFilter === "all" || device.modelProfileRef.toLowerCase().includes("b2"))
|
||||
.map((device) => {
|
||||
const session = latestSession(workspace, device);
|
||||
const online = session?.lifecycleState === "online" || device.session?.state === "online";
|
||||
@@ -128,7 +140,7 @@ export function DeviceInventoryView({
|
||||
return left.online ? -1 : 1;
|
||||
}
|
||||
return String(right.lastSeenAt || "").localeCompare(String(left.lastSeenAt || ""));
|
||||
}), [sortOrder, statusFilter, workspace]);
|
||||
}), [sortOrder, statusFilter, typeFilter, workspace]);
|
||||
|
||||
useEffect(() => {
|
||||
if (detail?.deviceRef && !selectedDevice) onDetailChange(null);
|
||||
@@ -159,16 +171,25 @@ export function DeviceInventoryView({
|
||||
);
|
||||
}
|
||||
|
||||
const remoteRows = (b2.data?.items || []).filter(() => !['pending', 'archived', 'active', 'inactive'].includes(statusFilter))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, 'ru'));
|
||||
const count = workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + (b2.data?.items.length || 0);
|
||||
return (
|
||||
<div className="device-inventory">
|
||||
<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 archiveDevice(workspace.project.projectRef, archiveTarget.deviceRef, archiveTarget.lifecycleState !== 'suspended'); setArchiveTarget(null); await onPoll(); } catch (reason) { onError(reason); } finally { setArchiving(false); }
|
||||
}} />
|
||||
<div className="device-manager-panel-toolbar device-inventory__toolbar">
|
||||
<div>
|
||||
<strong>Реестр устройств</strong>
|
||||
<p>{workspace.devices.length} зарегистрировано · {pendingEnrollments.length} ожидают подключения</p>
|
||||
<p>{count} зарегистрировано · {pendingEnrollments.length} ожидают подключения</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="device-inventory__filters" aria-label="Фильтры устройств">
|
||||
<Select label="Тип устройства" value={typeFilter} onChange={setTypeFilter} options={[{ value: 'all', label: 'Все типы' }, { value: 'arnavi', label: 'ARNavi B2' }]} />
|
||||
<Select
|
||||
label="Состояние"
|
||||
value={statusFilter}
|
||||
@@ -177,6 +198,7 @@ export function DeviceInventoryView({
|
||||
{ value: "active", label: "Активные" },
|
||||
{ value: "inactive", label: "Неактивные" },
|
||||
{ value: "pending", label: "Ожидают подключения" },
|
||||
{ value: "archived", label: "Архив" },
|
||||
]}
|
||||
onChange={setStatusFilter}
|
||||
/>
|
||||
@@ -193,54 +215,22 @@ export function DeviceInventoryView({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{statusFilter !== "pending" && !deviceRows.length ? (
|
||||
<GlassSurface className="device-manager-empty device-inventory__empty" padding="lg" tone="soft">
|
||||
<Icon name="inbox" size={24} />
|
||||
<h3>{workspace.devices.length ? "Устройств с таким состоянием нет" : "В проекте пока нет устройств"}</h3>
|
||||
<p>Добавьте разрешённый трекер через «плюс». Идентификатор попадёт в Device Core по защищённому процессу подключения.</p>
|
||||
</GlassSurface>
|
||||
) : statusFilter !== "pending" ? (
|
||||
<GlassSurface className="device-inventory-table" padding="sm" tone="soft" role="table" aria-label="Устройства проекта">
|
||||
<div className="device-inventory-table__head" role="row">
|
||||
<span role="columnheader">Устройство</span>
|
||||
<span role="columnheader">Профиль</span>
|
||||
<span role="columnheader">IMEI</span>
|
||||
<span role="columnheader">ID интеграционного устройства</span>
|
||||
<span role="columnheader">Канал</span>
|
||||
<span role="columnheader">Последний пакет</span>
|
||||
<span aria-hidden="true" />
|
||||
</div>
|
||||
{deviceRows.map(({ device, session, online, lastSeenAt }) => {
|
||||
return (
|
||||
<Button
|
||||
key={device.deviceRef}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="device-inventory-row"
|
||||
role="row"
|
||||
onClick={() => onDetailChange({
|
||||
deviceRef: device.deviceRef,
|
||||
sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? "passport",
|
||||
editing: false,
|
||||
})}
|
||||
>
|
||||
<span className="device-inventory-row__device" role="cell">
|
||||
<span className="device-inventory-row__icon"><Icon name="apps" size={17} /></span>
|
||||
<span><strong>{device.displayName}</strong><small>{device.deviceKey || "ключ не назначен"}</small></span>
|
||||
</span>
|
||||
<span role="cell">{profileLabel(workspace, device)}</span>
|
||||
<span role="cell">{deviceIdentifierDisplayValue(device) || "не назначен"}</span>
|
||||
<span role="cell">{device.integrationDeviceId || "не назначен"}</span>
|
||||
<span role="cell"><StatusBadge tone={online ? "success" : "neutral"}>{online ? "Онлайн" : session?.lifecycleState || device.lifecycleState}</StatusBadge></span>
|
||||
<span role="cell">{formatDate(lastSeenAt)}</span>
|
||||
<span className="device-inventory-row__open" role="cell" aria-hidden="true"><Icon name="chevron-right" size={16} /></span>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</GlassSurface>
|
||||
) : null}
|
||||
{b2.error ? <p role="alert">{b2.error}</p> : null}
|
||||
{b2.data?.hosts.filter((host) => !host.reachable).map((host) => <ResourceRow key={host.hostRef} title={host.name} status={<StatusBadge tone="warning">Нет связи с VPS</StatusBadge>} />)}
|
||||
{statusFilter !== 'pending' ? <ResourceList>
|
||||
{remoteRows.map((device) => <li key={`${device.hostRef}:${device.id}`}><ResourceRow
|
||||
icon={<Icon name="apps" />} title={device.name || `ARNavi B2 · ${device.number}`} metadata={`ARNavi B2 · ${device.number} · IMEI ${device.identifier.masked}`} description={device.hostName}
|
||||
status={<StatusBadge>{device.active ? 'Зарегистрирован на VPS' : 'Отключён на VPS'}</StatusBadge>} /></li>)}
|
||||
{deviceRows.map(({ device, online, lastSeenAt }) => <li key={device.deviceRef}><ResourceRow
|
||||
icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`}
|
||||
description={lastSeenAt ? formatDate(lastSeenAt) : undefined}
|
||||
status={<StatusBadge tone={online ? 'success' : 'neutral'}>{device.lifecycleState === 'suspended' ? 'В архиве' : online ? 'Онлайн' : 'Не в сети'}</StatusBadge>}
|
||||
actions={<><IconButton label={`Открыть ${device.displayName}`} onClick={() => onDetailChange({ deviceRef: device.deviceRef, sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? 'passport', editing: false })}><Icon name="chevron-right" /></IconButton>
|
||||
{canManageProject && !online ? <Button size="compact" disabled={archiving} onClick={() => setArchiveTarget(device)}>{device.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button> : null}</>} /></li>)}
|
||||
</ResourceList> : null}
|
||||
{statusFilter !== 'pending' && !deviceRows.length && !remoteRows.length ? <GlassSurface className="device-manager-empty device-inventory__empty" padding="lg" tone="soft"><Icon name="inbox" size={24} /><h3>{!b2.data && !b2.error ? 'Загрузка устройств…' : b2.error || b2.data?.hosts.some((host) => !host.reachable) ? 'Реестр VPS недоступен' : statusFilter === 'archived' ? 'Архив пуст' : count ? 'Нет устройств с таким состоянием' : 'В проекте пока нет устройств'}</h3></GlassSurface> : null}
|
||||
|
||||
{(statusFilter === "all" || statusFilter === "pending") ? (
|
||||
{(statusFilter === "pending" || statusFilter === "all" && pendingEnrollments.length > 0) ? (
|
||||
<section className="device-inventory__pending" aria-label="Ожидают подключения">
|
||||
<div className="device-inventory__section-heading">
|
||||
<div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState, type FormEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
|
||||
import {
|
||||
AdminNavigationPanel,
|
||||
AppHeader,
|
||||
@@ -188,6 +188,9 @@ export function DeviceManagerApp() {
|
||||
const [workspace, setWorkspace] = useState<ProjectWorkspace | null>(null);
|
||||
const [activeOwnerRef, setActiveOwnerRef] = useState("");
|
||||
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);
|
||||
@@ -286,9 +289,12 @@ export function DeviceManagerApp() {
|
||||
}, [activeOwnerRef, activeProjectRef, visibleProjects]);
|
||||
|
||||
const selectProject = (projectRef: string) => {
|
||||
if (projectRef === activeProjectRef) return;
|
||||
setInventoryDetail(null);
|
||||
projectRefCurrent.current = projectRef;
|
||||
setWorkspace(null);
|
||||
setSelectedHostRef(null);
|
||||
setActiveProjectRef(projectRef);
|
||||
shell.closeView();
|
||||
};
|
||||
|
||||
const openSection = (section: PrimarySection) => {
|
||||
@@ -305,14 +311,18 @@ export function DeviceManagerApp() {
|
||||
};
|
||||
|
||||
const selectOwner = (ownerRef: string) => {
|
||||
if (ownerRef === activeOwnerRef) return;
|
||||
setActiveOwnerRef(ownerRef);
|
||||
setInventoryDetail(null);
|
||||
setSelectedHostRef(null);
|
||||
setWorkspace(null);
|
||||
const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef);
|
||||
if (nextProject) {
|
||||
projectRefCurrent.current = nextProject.projectRef;
|
||||
setActiveProjectRef(nextProject.projectRef);
|
||||
shell.closeView();
|
||||
}
|
||||
else {
|
||||
projectRefCurrent.current = "";
|
||||
setActiveProjectRef("");
|
||||
setWorkspace(null);
|
||||
shell.closeView();
|
||||
@@ -322,6 +332,7 @@ export function DeviceManagerApp() {
|
||||
const refreshWorkspace = async () => {
|
||||
if (!activeProjectRef) return;
|
||||
const next = await loadWorkspace(activeProjectRef);
|
||||
if (projectRefCurrent.current !== activeProjectRef) return;
|
||||
setWorkspace(next);
|
||||
await refreshProjects();
|
||||
};
|
||||
@@ -329,14 +340,14 @@ export function DeviceManagerApp() {
|
||||
const pollWorkspace = async () => {
|
||||
if (!activeProjectRef) return;
|
||||
const next = await loadWorkspace(activeProjectRef);
|
||||
setWorkspace(next);
|
||||
if (projectRefCurrent.current === activeProjectRef) setWorkspace(next);
|
||||
};
|
||||
|
||||
if (loading || !session) {
|
||||
return <div className="device-manager-boot">Подключаем Device Core…</div>;
|
||||
}
|
||||
|
||||
const activeView = shell.activeView;
|
||||
const activeView = visibleNavigationItems.some((item) => item.id === shell.activeView) ? shell.activeView : null;
|
||||
const selectedInventoryDevice = inventoryDetail
|
||||
? workspace?.devices.find((device) => device.deviceRef === inventoryDetail.deviceRef) ?? null
|
||||
: null;
|
||||
@@ -490,13 +501,18 @@ export function DeviceManagerApp() {
|
||||
onDetailChange={setInventoryDetail}
|
||||
/>
|
||||
) : undefined}
|
||||
utilityActions={[{
|
||||
utilityActions={[...(activeView === "hosts" && selectedHostRef ? [{
|
||||
label: "Вернуться к VPS и хостам", icon: "chevron-left" as const, onClick: () => setSelectedHostRef(null),
|
||||
}] : []), {
|
||||
label: "Обновить данные",
|
||||
icon: "refresh",
|
||||
onClick: () => refreshWorkspace().catch((reason) => setError(errorText(reason))),
|
||||
}]}
|
||||
>
|
||||
<ProjectView
|
||||
key={activeProjectRef}
|
||||
selectedHostRef={selectedHostRef}
|
||||
onSelectHost={setSelectedHostRef}
|
||||
view={activeView}
|
||||
workspace={workspace}
|
||||
canManageCollections={canManageCollections}
|
||||
@@ -783,7 +799,9 @@ function Metric({ label, value, detail, tone = "neutral" }: { label: string; val
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectView({ view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: {
|
||||
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;
|
||||
view: ViewId;
|
||||
workspace: ProjectWorkspace | null;
|
||||
canManageCollections: boolean;
|
||||
@@ -802,6 +820,8 @@ function ProjectView({ view, workspace, canManageCollections, canClaim, canConfi
|
||||
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}
|
||||
|
||||
@@ -442,3 +442,10 @@ async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
}
|
||||
return body as T;
|
||||
}
|
||||
|
||||
export function archiveDevice(projectRef: string, deviceRef: string, archived: boolean) {
|
||||
return mutate("/api/device-manager/devices:update", { projectRef, deviceRef, archived });
|
||||
}
|
||||
export function archiveHost(projectRef: string, hostRef: string, archived: boolean) {
|
||||
return mutate("/api/device-manager/infrastructure-hosts:ensure", { projectRef, hostRef, archived });
|
||||
}
|
||||
|
||||
@@ -1,24 +1,26 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge,
|
||||
TextField, TextAreaField, WindowFooterActions, ConfirmationModal } from '@nodedc/ui-react';
|
||||
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, WindowFooterActions, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
|
||||
import { loadProjects } from '../api';
|
||||
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
|
||||
import { b2Request, type B2Status } from './api';
|
||||
import './b2.css';
|
||||
|
||||
type Section = 'connection' | 'contours' | 'applications';
|
||||
type Section = 'connection' | 'contours';
|
||||
type Form = 'contour' | 'application' | 'project' | null;
|
||||
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
|
||||
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
|
||||
onChanged: () => Promise<void>; onError: (error: unknown) => void;
|
||||
}) {
|
||||
const project = workspace.project;
|
||||
const [section, setSection] = useState<Section>('connection');
|
||||
const [section, setSection] = useState<Section>('contours');
|
||||
const [status, setStatus] = useState<B2Status | null>(null);
|
||||
const [pending, setPending] = useState('');
|
||||
const [pending, setPending] = useState('load');
|
||||
const [connection, setConnection] = useState('');
|
||||
const connectionFile = useRef<HTMLInputElement>(null);
|
||||
const [key, setKey] = useState(''); const [name, setName] = useState('');
|
||||
const [contour, setContour] = useState('');
|
||||
const [key, setKey] = useState(''), [name, setName] = useState('');
|
||||
const [contourId, setContourId] = useState(''), [applicationId, setApplicationId] = useState('');
|
||||
const [form, setForm] = useState<Form>(null);
|
||||
const [showHistory, setShowHistory] = useState(false), [showInactive, setShowInactive] = useState(false);
|
||||
const [targetProject, setTargetProject] = useState(project.projectRef);
|
||||
const [projects, setProjects] = useState<ProjectSummary[]>([]);
|
||||
const [issued, setIssued] = useState('');
|
||||
@@ -27,10 +29,9 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
const refresh = () => request<B2Status>('status').then(setStatus);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setPending('load');
|
||||
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
|
||||
if (!active) return;
|
||||
setStatus(value);
|
||||
setStatus(value); if (!value.connected) setSection('connection');
|
||||
setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef));
|
||||
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
|
||||
return () => { active = false; };
|
||||
@@ -38,111 +39,95 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
async function run(action: string, data: Record<string, unknown> = {}) {
|
||||
setPending(action);
|
||||
try {
|
||||
const result = await request<{ connection?: unknown }>(action, data);
|
||||
const result = await request<{ connection?: unknown; id?: string }>(action, data);
|
||||
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2));
|
||||
if (action === 'connect') setConnection('');
|
||||
await refresh(); await onChanged();
|
||||
} catch (error) { onError(error); } finally { setPending(''); }
|
||||
if (action === 'connect') { setConnection(''); setSection('contours'); }
|
||||
if (action === 'contour-create' && result.id) { setContourId(result.id); setApplicationId(''); }
|
||||
if (action === 'application-create' && result.id) setApplicationId(result.id);
|
||||
setForm(null); setName(''); setKey('');
|
||||
// A successful mutation must not be presented as failed if a subsequent read fails.
|
||||
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
|
||||
return true;
|
||||
} catch (error) { onError(error); return false; } finally { setPending(''); }
|
||||
}
|
||||
const contours = status?.contours || [];
|
||||
const canManage = status?.authority === 'host';
|
||||
const busy = Boolean(pending);
|
||||
const contours = status?.contours || [], selected = contours.find((item) => item.id === contourId);
|
||||
const linkedProject = status?.links?.find((item) => item.contourId === contourId)?.projectRef;
|
||||
const applications = (status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core' && app.grants[contourId]);
|
||||
const application = applications.find((app) => app.id === applicationId);
|
||||
const inactive = (app: typeof applications[number]) => app.credentials.length > 0 && !app.credentials.some((item) => item.enabled);
|
||||
const busy = Boolean(pending), canManage = status?.authority === 'host';
|
||||
const begin = (value: Form) => { setForm(value); setName(''); setKey(''); setTargetProject(project.projectRef); };
|
||||
const back = () => {
|
||||
setIssued(''); setShowHistory(false);
|
||||
if (form) setForm(null); else if (applicationId) setApplicationId(''); else { setContourId(''); setShowInactive(false); }
|
||||
};
|
||||
function downloadIssuedKey() {
|
||||
const url = URL.createObjectURL(new Blob([issued + '\n'], { type: 'application/json' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = 'arnavi-application-key.json';
|
||||
link.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
const link = document.createElement('a'); link.href = url; link.download = 'arnavi-application-key.json';
|
||||
document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
return <>
|
||||
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
|
||||
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
|
||||
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' },
|
||||
{ id: 'contours', label: 'Контуры и проекты', icon: 'layers', disabled: !status?.connected },
|
||||
{ id: 'applications', label: 'Приложения и ключи', icon: 'key', disabled: !status?.connected }]}
|
||||
activeSection={section} onSectionChange={(value) => { setSection(value); setKey(''); setName(''); }} onClose={onClose}
|
||||
footer={<WindowFooterActions><Button onClick={onClose}>Закрыть</Button>
|
||||
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' }, { id: 'contours', label: 'Контуры', icon: 'layers', disabled: !status?.connected }]}
|
||||
activeSection={section} onSectionChange={(value) => { setSection(value); setForm(null); setIssued(''); }} onClose={onClose}
|
||||
footer={<WindowFooterActions>
|
||||
{section === 'contours' && (selected || form) ? <IconButton label={form ? 'Отменить создание' : application ? 'К приложениям контура' : 'К списку контуров'} disabled={busy} onClick={back}><Icon name="chevron-left" /></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></WindowFooterActions>}>
|
||||
<div className="b2-settings">
|
||||
}}><Icon name="refresh" /></IconButton>
|
||||
</WindowFooterActions>}>
|
||||
<div className="b2-settings" aria-busy={busy}>
|
||||
{section === 'connection' ? <>
|
||||
<SettingsCard title="ARNavi VPS" description="Одно подключение сервера для проектов компании. Устройства разделяются контурами.">
|
||||
<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Проверяем подключение' : status ? 'Не подключён' : 'Состояние не получено'}</StatusBadge>
|
||||
{status?.endpoint ? <p>{status.endpoint}</p> : null}
|
||||
</SettingsCard>
|
||||
<SettingsCard title={status?.connected ? 'Заменить ключ подключения' : 'Подключить сервер'} description="Загрузите файл ключа или вставьте ключ, выданный на VPS. После подключения он хранится только на сервере Device Core.">
|
||||
<ResourceRow title={host.displayName} description={status?.endpoint} status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Подключение…' : 'Не подключён'}</StatusBadge>} />
|
||||
<SettingsCard title={status?.connected ? 'Заменить ключ сервера' : 'Подключить сервер'}>
|
||||
<div className="b2-settings">
|
||||
<Button disabled={busy} onClick={() => connectionFile.current?.click()}><Icon name="upload" />Загрузить файл ключа</Button>
|
||||
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл ключа подключения VPS" disabled={busy}
|
||||
onChange={async (event) => {
|
||||
const file = event.currentTarget.files?.[0]; event.currentTarget.value = '';
|
||||
if (!file) return;
|
||||
setPending('file');
|
||||
try {
|
||||
if (file.size > 16384) throw new Error('Файл ключа слишком большой. Выберите JSON-файл, выданный на VPS.');
|
||||
const text = await file.text();
|
||||
try { JSON.parse(text); } catch { throw new Error('Не удалось прочитать файл ключа. Выберите JSON-файл, выданный на VPS.'); }
|
||||
setConnection(text);
|
||||
} catch (error) { onError(error); } finally { setPending(''); }
|
||||
}} />
|
||||
<TextAreaField label="Ключ подключения" value={connection} autoComplete="off" spellCheck={false}
|
||||
onChange={(event) => setConnection(event.target.value)} rows={5} />
|
||||
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл ключа подключения VPS" disabled={busy} onChange={async (event) => {
|
||||
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return; setPending('file');
|
||||
try { if (file.size > 16384) throw new Error(); const text = await file.text(); JSON.parse(text); setConnection(text); }
|
||||
catch { onError(new Error('Не удалось прочитать файл ключа VPS.')); } finally { setPending(''); }
|
||||
}} />
|
||||
<TextAreaField label="Ключ сервера" value={connection} autoComplete="off" spellCheck={false} onChange={(event) => setConnection(event.target.value)} rows={4} />
|
||||
<Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>Подключить</Button>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</> : null}
|
||||
{section === 'contours' ? <>
|
||||
<SettingsCard title="Контуры на VPS" description="Связь с проектом определяет, где появятся устройства. Один контур можно подключить к нескольким приложениям.">
|
||||
<div className="b2-path" aria-label="Текущий раздел">{[host.displayName, selected?.name, application?.name].filter(Boolean).join(' / ')}</div>
|
||||
{form === 'contour' || form === 'application' ? <SettingsCard title={form === 'contour' ? 'Новый контур' : 'Новое приложение'}>
|
||||
<div className="b2-settings">
|
||||
{contours.map((item) => {
|
||||
const link = status?.links?.find((value) => value.contourId === item.id);
|
||||
return <div className="b2-resource" key={item.id}><div><strong>{item.name}</strong><small>{item.key}</small></div>
|
||||
<StatusBadge tone={link ? 'success' : 'neutral'}>{link ? projects.find((p) => p.projectRef === link.projectRef)?.name || 'Связан с проектом' : 'Не связан'}</StatusBadge></div>;
|
||||
})}
|
||||
{!contours.length ? <p>На VPS пока нет контуров.</p> : null}
|
||||
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
|
||||
<Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((item) => ({ value: item.projectRef, label: item.name }))} />
|
||||
<Button loading={pending === 'link'} disabled={busy || !contour || !targetProject} onClick={() => void run('link', { contourId: contour, targetProjectRef: targetProject })}>Связать с проектом</Button>
|
||||
{form === 'application' ? <ResourceRow title={selected?.name} metadata="Контур" /> : null}
|
||||
<TextField label="Название" value={name} maxLength={160} onChange={(e) => setName(e.target.value)} />
|
||||
<TextField label="Код" value={key} placeholder={form === 'contour' ? 'robot2b' : 'delivery-app'} onChange={(e) => setKey(e.target.value.toLowerCase())} />
|
||||
<div className="b2-actions"><Button onClick={() => setForm(null)} disabled={busy}>Отмена</Button><Button loading={busy} disabled={busy || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)} onClick={() => void run(form === 'contour' ? 'contour-create' : 'application-create', { key, name, ...(form === 'application' ? { contourId } : {}) })}>Создать</Button></div>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
{canManage ? <SettingsCard title="Новый контур" description="Контур создаётся на VPS и получает собственный реестр устройств.">
|
||||
<div className="b2-settings"><TextField label="Название" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<TextField label="Код контура" value={key} placeholder="robot2b" onChange={(e) => setKey(e.target.value)} />
|
||||
<Button loading={pending === 'contour-create'} disabled={busy || !/^[a-z][a-z0-9-]{0,63}$/.test(key) || !name.trim()}
|
||||
onClick={() => void run('contour-create', { key, name })}>Создать контур</Button></div>
|
||||
</SettingsCard> : null}
|
||||
</> : null}
|
||||
{section === 'applications' ? <>
|
||||
{issued ? <SettingsCard title="Новый ключ приложения" description="Сохраните файл ключа для подключаемого приложения. Позже ключ можно перевыпустить без потери устройств.">
|
||||
<div className="b2-settings"><TextAreaField label="Ключ" value={issued} readOnly rows={6} />
|
||||
<Button onClick={downloadIssuedKey}><Icon name="download" />Скачать файл ключа</Button>
|
||||
<Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать ключ</Button>
|
||||
<Button onClick={() => setIssued('')}>Скрыть</Button></div>
|
||||
</SettingsCard> : null}
|
||||
{(status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core').map((app) => <SettingsCard key={app.id} title={app.name}
|
||||
description={Object.keys(app.grants).map((id) => contours.find((item) => item.id === id)?.name || id).join(', ')}>
|
||||
<div className="b2-settings">
|
||||
{app.credentials.map((credential) => <div className="b2-resource" key={credential.client_id}>
|
||||
<div><small>{credential.client_id}</small><StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge></div>
|
||||
{credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${app.name}»? Подключённый клиент потеряет доступ.` })}>Отозвать</Button> : null}
|
||||
</div>)}
|
||||
<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: true }, text: `Выдать новый ключ для «${app.name}»? Предыдущие ключи этого приложения перестанут работать. Устройства и история сохранятся.` })}>{app.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>
|
||||
</div>
|
||||
</SettingsCard>)}
|
||||
{canManage ? <SettingsCard title="Подключить новое приложение" description="Для каждого приложения создайте отдельный ключ. Несколько приложений могут работать с одним контуром независимо.">
|
||||
<div className="b2-settings"><TextField label="Название приложения" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<TextField label="Код приложения" value={key} placeholder="robot2b-client" onChange={(e) => setKey(e.target.value)} />
|
||||
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
|
||||
<Button loading={pending === 'application-create'} disabled={busy || !contour || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)}
|
||||
onClick={() => void run('application-create', { key, name, contourId: contour })}>Создать приложение</Button></div>
|
||||
</SettingsCard> : <SettingsCard title="Доступ к контуру" description="Управление ключами доступно через управляющее подключение VPS." />}
|
||||
</SettingsCard> : form === 'project' ? <SettingsCard title="Проект Device Core"><div className="b2-settings">
|
||||
<ResourceRow title={selected?.name} metadata="Контур VPS" /><Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((p) => ({ value: p.projectRef, label: p.name }))} />
|
||||
<div className="b2-actions"><Button disabled={busy} onClick={() => setForm(null)}>Отмена</Button><Button disabled={busy || !targetProject} loading={pending === 'link'} onClick={() => void run('link', { contourId, targetProjectRef: targetProject })}>Связать</Button></div>
|
||||
</div></SettingsCard> : !selected ? <SettingsCard title="Контуры" actions={canManage ? <IconButton label="Создать контур" disabled={busy} onClick={() => begin('contour')}><Icon name="plus" /></IconButton> : undefined}>
|
||||
<ResourceList>{contours.map((item) => {
|
||||
const link = status?.links?.find((value) => value.contourId === item.id), projectName = projects.find((p) => p.projectRef === link?.projectRef)?.name;
|
||||
return <li key={item.id}><ResourceRow title={item.name} metadata={projectName ? `Проект: ${projectName}` : 'Проект не связан'} actions={<IconButton label={`Открыть контур ${item.name}`} disabled={busy} onClick={() => { setContourId(item.id); setApplicationId(''); }}><Icon name="chevron-right" /></IconButton>} /></li>;
|
||||
})}</ResourceList>{!contours.length ? <p>Контуров пока нет</p> : null}
|
||||
</SettingsCard> : !application ? <>
|
||||
<SettingsCard title={selected.name} actions={<StatusBadge>Контур</StatusBadge>}><ResourceRow title={projects.find((p) => p.projectRef === linkedProject)?.name || 'Не выбран'} metadata="Проект Device Core" actions={!linkedProject ? <Button disabled={busy} onClick={() => begin('project')}>Выбрать проект</Button> : undefined} /></SettingsCard>
|
||||
<SettingsCard title="Приложения" actions={canManage ? <IconButton label={`Добавить приложение в ${selected.name}`} disabled={busy} onClick={() => begin('application')}><Icon name="plus" /></IconButton> : undefined}>
|
||||
<ResourceList>{applications.filter((app) => showInactive || !inactive(app)).map((app) => <li key={app.id}><ResourceRow title={app.name} status={<StatusBadge tone={app.credentials.some((c) => c.enabled) ? 'success' : 'neutral'}>{app.credentials.some((c) => c.enabled) ? 'Ключ действует' : 'Нет активного ключа'}</StatusBadge>} actions={<IconButton label={`Ключи ${app.name}`} disabled={busy} onClick={() => { setApplicationId(app.id); setShowHistory(false); }}><Icon name="key" /></IconButton>} /></li>)}</ResourceList>
|
||||
{!applications.filter((app) => showInactive || !inactive(app)).length ? <p>Нет подключённых приложений</p> : null}
|
||||
{applications.some(inactive) ? <Button variant="ghost" onClick={() => setShowInactive(!showInactive)}>{showInactive ? 'Скрыть отключённые' : `Отключённые приложения · ${applications.filter(inactive).length}`}</Button> : null}
|
||||
</SettingsCard>
|
||||
</> : <>
|
||||
{issued ? <SettingsCard title="Новый ключ" description="Сохраните ключ — повторный просмотр недоступен."><div className="b2-settings"><TextAreaField label="Ключ подключения" value={issued} readOnly rows={4} /><div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued('')}>Скрыть</Button></div></div></SettingsCard> : null}
|
||||
<SettingsCard title="Ключи приложения" actions={<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: application.id, replace: true }, text: `Выдать новый ключ для «${application.name}»? Прежний ключ перестанет работать. Устройства сохранятся.` })}>{application.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>}>
|
||||
<ResourceList>{application.credentials.filter((c) => c.enabled || showHistory).map((credential) => <li key={credential.client_id}><ResourceRow metadata="ID ключа" title={<code className="b2-key-id" title={credential.client_id}>{credential.client_id}</code>} status={<StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge>} actions={credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${application.name}»?` })}>Отозвать</Button> : undefined} /></li>)}</ResourceList>
|
||||
{!application.credentials.some((c) => c.enabled) ? <p>Нет активного ключа</p> : null}
|
||||
{application.credentials.some((c) => !c.enabled) ? <Button variant="ghost" onClick={() => setShowHistory(!showHistory)}>{showHistory ? 'Скрыть историю' : `История ключей · ${application.credentials.filter((c) => !c.enabled).length}`}</Button> : null}
|
||||
</SettingsCard>
|
||||
</>}
|
||||
</> : null}
|
||||
</div>
|
||||
</FeatureSettingsWindow>
|
||||
<ConfirmationModal open={Boolean(confirm)} title="Изменить доступ приложения" description={confirm?.text}
|
||||
confirmLabel="Продолжить" cancelLabel="Отмена" onClose={() => setConfirm(null)}
|
||||
onConfirm={async () => { if (confirm) await run(confirm.action, confirm.fields); setConfirm(null); }} />
|
||||
<ConfirmationModal open={Boolean(confirm)} title="Ключ приложения" description={confirm?.text} confirmLabel="Подтвердить" cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
.b2-settings { display: grid; gap: var(--nodedc-space-md, 16px); }
|
||||
.b2-settings p { margin: 0; font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
|
||||
.b2-resource { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-sm, 8px); flex-wrap: wrap; }
|
||||
.b2-resource > div { display: grid; gap: 4px; min-width: 0; }
|
||||
.b2-resource strong { font-size: var(--nodedc-font-size-sm); }
|
||||
.b2-resource small { font-size: var(--nodedc-font-size-xs); overflow-wrap: anywhere; color: var(--nodedc-text-secondary); }
|
||||
.b2-settings { display: grid; gap: var(--nodedc-space-md); }
|
||||
.b2-settings p, .b2-path { margin: 0; font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
|
||||
.b2-path { overflow-wrap: anywhere; }
|
||||
.b2-actions { display: flex; gap: var(--nodedc-space-sm); flex-wrap: wrap; justify-content: flex-end; }
|
||||
.b2-key-id { font-family: inherit; font-size: var(--nodedc-font-size-sm); overflow-wrap: anywhere; font-weight: 400; }
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { b2Request, type B2Device } from './api';
|
||||
export type B2HostState = { hostRef: string; name: string; endpoint: string; contours: number; reachable: boolean; checkedAt: string; devices: number | null };
|
||||
export type B2Inventory = { items: Array<B2Device & { hostRef: string; hostName: string }>; hosts: B2HostState[] };
|
||||
export function useB2Inventory(projectRef: string, refreshSignal: unknown) {
|
||||
const [data, setData] = useState<B2Inventory | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
let active = true, timer: ReturnType<typeof setTimeout>;
|
||||
async function load() {
|
||||
try {
|
||||
const next = await b2Request<B2Inventory>(projectRef, '', 'inventory');
|
||||
if (active) { setData(next); setError(''); }
|
||||
} catch (reason) {
|
||||
if (active) { setData(null); setError(reason instanceof Error ? reason.message : 'VPS недоступен'); }
|
||||
} finally { if (active) timer = setTimeout(load, 30_000); }
|
||||
}
|
||||
void load();
|
||||
return () => { active = false; clearTimeout(timer); };
|
||||
}, [projectRef, refreshSignal]);
|
||||
return { data, error };
|
||||
}
|
||||
@@ -1309,8 +1309,8 @@ body {
|
||||
|
||||
.device-inventory__filters {
|
||||
display: grid;
|
||||
max-width: 620px;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
max-width: 960px;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,10 +21,11 @@ initiates all HTTPS requests; this integration adds no inbound Synology port.
|
||||
3. The server validates that credential against the pinned host before saving
|
||||
it in a separate private persistent filesystem mount. No secret goes into
|
||||
project tables, audit payloads, browser storage, Git or deployment artifacts.
|
||||
4. In Contours and projects, create a contour on the VPS and explicitly link it
|
||||
4. In VPS settings → Contours, create a contour on the VPS and explicitly link it
|
||||
to an accessible project of the same company. Linking another project adds
|
||||
a view of the same host there. It does not duplicate the remote VPS or key.
|
||||
5. In Applications and keys, create an application for a selected contour.
|
||||
5. Open that contour, then add an application inside its Applications list.
|
||||
Open the application to manage its keys.
|
||||
Issue its key, copy the JSON package and transfer it to that application's backend.
|
||||
Copy was verified; the download button is implemented but its in-app-browser
|
||||
download event was not confirmed. The canonical VPS CLI also writes a private
|
||||
@@ -148,3 +149,33 @@ did not expose the missing dependency in Core's standalone package-lock. r17
|
||||
fixes that lock and qualifies the exact production npm context inside the
|
||||
existing device-install CI stage. The separate r15 Gitea artifact-finalization
|
||||
error and permanent build-output capture remain open CI follow-ups.
|
||||
|
||||
## UX correction after live operator review, 2026-09-30
|
||||
|
||||
The r18 functional checks did not establish usability. The next source revision
|
||||
uses the Design Guidelines ResourceList/ResourceRow and existing settings window:
|
||||
VPS → contour → applications → application keys. Project assignment is a separate
|
||||
named relation on the contour. New-object forms appear only after the contextual
|
||||
plus; revoked keys and applications with only revoked credentials are collapsed.
|
||||
No duplicate refresh/back controls remain inside host monitoring; Back is a main
|
||||
window utility beside Refresh. Switching project preserves the open section and
|
||||
clears its selected object; late responses from the previous project are ignored.
|
||||
|
||||
The project inventory reads linked VPS contours through the B2 backend, alongside
|
||||
the legacy Core registry. It releases its DB transaction before network requests,
|
||||
checks the remote host identity, masks identifiers and reports each unreachable
|
||||
host explicitly. A registered/enabled B2 is not labelled online without telemetry.
|
||||
API availability and hardware metrics are separate: hardware metrics are currently
|
||||
not connected for the standalone ARNavi service. Full command/SIM/firmware parity
|
||||
remains open; registration in the list does not imply that parity.
|
||||
|
||||
Legacy device and host archive/restore are explicit modes of the existing
|
||||
`device.update` and `infrastructure_host.ensure` command contracts. They retain
|
||||
identity, history, bindings and secrets, use existing project capability checks
|
||||
and audited/idempotent receipts, and require no schema or runner change. Device
|
||||
archival refuses a live session. The UI exposes Archive and Restore; suspended
|
||||
records stay out of default lists. No physical tracker operation is sent.
|
||||
|
||||
Local validation: 282 Node tests; TypeScript/build; 27 CI contract tests. Production
|
||||
acceptance and the actual cleanup are recorded separately after the main pipeline
|
||||
accepts the new release; these source checks alone do not prove deployment.
|
||||
|
||||
@@ -32,7 +32,46 @@ export class B2Infrastructure {
|
||||
this.clients.set(source.secret_ref, client);
|
||||
return client;
|
||||
}
|
||||
async inventory(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, 'inventory.read');
|
||||
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(); }
|
||||
// Release the database transaction before waiting for any external host.
|
||||
const results = await Promise.all(sources.map(async (source) => {
|
||||
const host = { hostRef: `host:${source.host_id}`, name: source.display_name,
|
||||
endpoint: source.endpoint, contours: source.contour_ids.length };
|
||||
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 items = [];
|
||||
for (const contourId of source.contour_ids) {
|
||||
const snapshot = await remote.call(`/v2/contours/${opaque(contourId)}/devices`);
|
||||
items.push(...snapshot.items.map((device) => ({ id: device.id, name: device.name, number: device.number,
|
||||
active: device.active, identifier: { masked: '…' + String(device.imei).slice(-5) },
|
||||
contourId, hostRef: host.hostRef, hostName: host.name })));
|
||||
}
|
||||
return { host: { ...host, reachable: true, checkedAt: new Date().toISOString(), devices: items.length }, items };
|
||||
} catch {
|
||||
return { host: { ...host, reachable: false, checkedAt: new Date().toISOString(), devices: null }, items: [] };
|
||||
}
|
||||
}));
|
||||
return { items: results.flatMap((result) => result.items), hosts: results.map((result) => result.host) };
|
||||
}
|
||||
async execute(actor, input, requestId) {
|
||||
if (input.action === 'inventory') return this.inventory(actor, input);
|
||||
const projectId = ref(input.projectRef, 'project');
|
||||
const hostId = ref(input.hostRef, 'host');
|
||||
const action = input.action;
|
||||
|
||||
@@ -44,6 +44,16 @@ export function normalizeLifecycleManagementCommand(kind, input) {
|
||||
});
|
||||
}
|
||||
|
||||
if (kind === "device.update" && Object.prototype.hasOwnProperty.call(input, "archived")) {
|
||||
assertAllowedKeys(input, ["projectRef", "deviceRef", "archived"]);
|
||||
if (typeof input.archived !== "boolean") throw new TypeError("device_archive_state_invalid");
|
||||
return Object.freeze({
|
||||
projectId: normalizeEntityRef(input.projectRef, "project"),
|
||||
deviceId: normalizeEntityRef(input.deviceRef, "device"),
|
||||
archived: input.archived,
|
||||
});
|
||||
}
|
||||
|
||||
if (kind === "device.update") {
|
||||
assertAllowedKeys(input, [
|
||||
"projectRef",
|
||||
|
||||
@@ -91,7 +91,24 @@ export async function authorizeLifecycleManagementReplay(
|
||||
}
|
||||
}
|
||||
|
||||
async function archiveDevice(client, actor, command) {
|
||||
const project = await findProjectWithCapability(client, actor, command.projectId, "project.manage");
|
||||
const current = await findDeviceForUpdate(client, command.deviceId);
|
||||
if (current.project_id !== project.id) throw domainError("device_update_project_mismatch", 409);
|
||||
// Archive is a reversible registry operation. It never closes a live channel.
|
||||
if (!["claimed", "suspended"].includes(current.lifecycle_state)) throw domainError("device_archive_lifecycle_blocked", 409);
|
||||
const sessions = await client.query(`select exists(select 1 from device_sessions where device_id=$1
|
||||
and lifecycle_state in ('connecting','online','closing')) as active`, [current.id]);
|
||||
if (sessions.rows[0]?.active) throw domainError("device_archive_active_session", 409);
|
||||
const state = command.archived ? "suspended" : "claimed";
|
||||
await client.query('update device_instances set lifecycle_state=$3, updated_at=now() where id=$1 and project_id=$2', [current.id, project.id, state]);
|
||||
await addAudit(client, { eventType: command.archived ? "device.archived" : "device.restored", actorRef: actor.userRef,
|
||||
projectId: project.id, deviceId: current.id, payload: { deviceRef: `device:${current.id}`, lifecycleState: state } });
|
||||
return { archived: command.archived };
|
||||
}
|
||||
|
||||
async function updateDevice(client, actor, command) {
|
||||
if (typeof command.archived === "boolean") return archiveDevice(client, actor, command);
|
||||
const project = await findProjectWithCapability(
|
||||
client,
|
||||
actor,
|
||||
|
||||
@@ -81,6 +81,16 @@ export function normalizeOntologyManagementCommand(kind, input) {
|
||||
});
|
||||
}
|
||||
|
||||
if (kind === "infrastructure_host.ensure" && Object.prototype.hasOwnProperty.call(input, "archived")) {
|
||||
assertAllowedKeys(input, ["projectRef", "hostRef", "archived"]);
|
||||
if (typeof input.archived !== "boolean") throw new TypeError("device_archive_state_invalid");
|
||||
return Object.freeze({
|
||||
projectId: normalizeEntityRef(input.projectRef, "project"),
|
||||
hostId: normalizeEntityRef(input.hostRef, "host"),
|
||||
archived: input.archived,
|
||||
});
|
||||
}
|
||||
|
||||
if (kind === "infrastructure_host.ensure") {
|
||||
assertAllowedKeys(input, [
|
||||
"projectRef", "hostKey", "displayName", "providerRef", "externalRef",
|
||||
|
||||
@@ -201,7 +201,18 @@ async function closeAssetBinding(client, actor, project, command) {
|
||||
return { closed: true, assetBinding: assetBindingView(row) };
|
||||
}
|
||||
|
||||
async function archiveHost(client, actor, project, command) {
|
||||
const result = await client.query(`update device_infrastructure_hosts set lifecycle_state=$3, updated_at=now()
|
||||
where id=$1 and project_id=$2 and lifecycle_state in ('active','suspended') returning *`,
|
||||
[command.hostId, project.id, command.archived ? 'suspended' : 'active']);
|
||||
const row = requireRow(result, "device_host_not_archivable", 409);
|
||||
await addAudit(client, { actor, project, eventType: command.archived ? 'infrastructure_host.archived' : 'infrastructure_host.restored',
|
||||
payload: { hostRef: `host:${row.id}`, lifecycleState: row.lifecycle_state } });
|
||||
return { archived: command.archived };
|
||||
}
|
||||
|
||||
async function ensureHost(client, actor, project, command) {
|
||||
if (typeof command.archived === "boolean") return archiveHost(client, actor, project, command);
|
||||
const result = await client.query(
|
||||
`insert into device_infrastructure_hosts (
|
||||
id, owner_scope_id, project_id, host_key, display_name, provider_ref,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { normalizeDeviceManagementCommand } from '../src/management-command.mjs';
|
||||
import { applyLifecycleManagementCommand, authorizeLifecycleManagementReplay } from '../src/lifecycle-repository.mjs';
|
||||
import { applyOntologyManagementCommand } from '../src/ontology-repository.mjs';
|
||||
const projectId='11111111-1111-4111-8111-111111111111', entityId='22222222-2222-4222-8222-222222222222';
|
||||
const actor={ userRef:'user:operator', hubRole:'owner', groupRefs:[], ownerScopes:[] };
|
||||
function db({role='owner', entityProject=projectId, active=false}={}) {
|
||||
const writes=[];
|
||||
return { writes, async query(sql, values) {
|
||||
if (sql.includes('from device_projects')) return {rows:[{id:projectId,owner_scope_id:'owner',scope_kind:'company',owner_ref:'company:test',lifecycle_state:'active',owner_lifecycle_state:'active'}]};
|
||||
if (sql.includes('from device_project_grants')) return {rows:[{id:'grant',principal_kind:'user',principal_ref:actor.userRef,project_role:role,capability_allow:[],capability_deny:[],lifecycle_state:'active'}]};
|
||||
if (sql.includes('from device_instances')) return {rows:[{id:entityId,project_id:entityProject,lifecycle_state:'claimed'}]};
|
||||
if (sql.includes('from device_sessions')) return {rows:[{active}]};
|
||||
if (sql.startsWith('update device_infrastructure_hosts')) { writes.push({sql,values}); return {rows:entityProject === projectId ? [{id:entityId,lifecycle_state:values[2]}] : []}; }
|
||||
if (sql.startsWith('update') || sql.includes('insert into device_audit_events')) {writes.push({sql,values});return {rows:[]};}
|
||||
throw Error('Unexpected query '+sql);
|
||||
}};
|
||||
}
|
||||
for (const [kind, ref, apply] of [['device.update','deviceRef',applyLifecycleManagementCommand],['infrastructure_host.ensure','hostRef',applyOntologyManagementCommand]]) {
|
||||
test(`${kind} archive and restore preserve identity and private bindings`,async()=>{
|
||||
for (const archived of [true,false]) {
|
||||
const command=normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived});
|
||||
const client=db(); const result=await apply(client,{actor,commandKind:kind,command});
|
||||
assert.equal(result.archived,archived);
|
||||
const update=client.writes.find((write)=>write.sql.startsWith('update'));
|
||||
assert.match(update.sql,/where id\s*=\s*\$1 and project_id\s*=\s*\$2/);
|
||||
assert.equal(update.sql.includes('management_credential_ref'),false);
|
||||
assert.equal(update.sql.includes('display_name'),false);
|
||||
assert.equal(update.values[2],archived?'suspended':ref==='hostRef'?'active':'claimed');
|
||||
assert.ok(client.writes.some((write)=>write.sql.includes('device_audit_events')));
|
||||
}
|
||||
});
|
||||
test(`${kind} rejects unauthorized and cross-project archive`,async()=>{
|
||||
const command=normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:true});
|
||||
for (const options of [{role:'viewer'},{entityProject:'different'}]) {
|
||||
const client=db(options); await assert.rejects(apply(client,{actor,commandKind:kind,command}));
|
||||
if (options.role) assert.equal(client.writes.length,0);
|
||||
}
|
||||
assert.throws(()=>normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:'true'}));
|
||||
assert.throws(()=>normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:true,displayName:'unexpected'}));
|
||||
});
|
||||
}
|
||||
test('archive cannot interrupt an active device and replay rechecks its project',async()=>{
|
||||
const command=normalizeDeviceManagementCommand('device.update',{projectRef:`project:${projectId}`,deviceRef:`device:${entityId}`,archived:true});
|
||||
const client=db({active:true});
|
||||
await assert.rejects(applyLifecycleManagementCommand(client,{actor,commandKind:'device.update',command}),/device_archive_active_session/);
|
||||
assert.equal(client.writes.length,0);
|
||||
await assert.rejects(authorizeLifecycleManagementReplay(db({entityProject:'different'}),{actor,commandKind:'device.update',command}),/project_mismatch/);
|
||||
});
|
||||
@@ -156,3 +156,42 @@ test('TLS pin is verified before any HTTP credential reaches the peer', async ()
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('project inventory releases DB before networking and never exposes other projects or credentials', async () => {
|
||||
const contour = 'c'.repeat(32); let released = false; const calls = [];
|
||||
const repo = repository({ role: 'viewer' });
|
||||
const db = await repo.pool.connect(); const original = db.query;
|
||||
db.release = () => { released = true; };
|
||||
db.query = async (sql, values) => {
|
||||
if (sql.includes('from device_b2_hosts')) {
|
||||
assert.match(sql, /v.project_id=\$1 and h.lifecycle_state='active'/);
|
||||
assert.match(sql, /l.project_id=v.project_id/);
|
||||
assert.deepEqual(values, [projectId]);
|
||||
return { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [contour] }] };
|
||||
}
|
||||
return original(sql, values);
|
||||
};
|
||||
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
|
||||
assert.equal(released, true); calls.push(path);
|
||||
return path === '/v2/identity' ? { host_id: pkg.host_id } : { items: [{ id: 'device', imei: '123456789012345', number: 1, name: 'B2', active: true }] };
|
||||
} }) });
|
||||
const result = await service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, action: 'inventory' });
|
||||
assert.deepEqual(calls, ['/v2/identity', `/v2/contours/${contour}/devices`]);
|
||||
assert.equal(result.items[0].identifier.masked, '…12345');
|
||||
assert.equal(result.hosts[0].reachable, true);
|
||||
assert.equal(result.hosts[0].devices, 1);
|
||||
const json = JSON.stringify(result);
|
||||
for (const secret of [pkg.client_secret, source.secret_ref, '123456789012345', otherProject]) assert.equal(json.includes(secret), false);
|
||||
assert.equal('online' in result.items[0], false);
|
||||
});
|
||||
|
||||
test('unreachable or mismatched host is reported as unavailable, not an empty healthy fleet', async () => {
|
||||
for (const fail of [false, true]) {
|
||||
const repo = repository(); const db = await repo.pool.connect(); const original = db.query;
|
||||
db.query = (sql, values) => sql.includes('from device_b2_hosts') ? { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [] }] } : original(sql, values);
|
||||
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call() { if (fail) throw Error('contains-private-details'); return { host_id: 'wrong-host' }; } }) });
|
||||
const result = await service.execute(actor, { projectRef: `project:${projectId}`, action: 'inventory' });
|
||||
assert.equal(result.hosts[0].reachable, false); assert.equal(result.hosts[0].devices, null);
|
||||
assert.deepEqual(result.items, []); assert.equal(JSON.stringify(result).includes('private-details'), false);
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user