diff --git a/apps/device-manager/server/device-manager-presentation.test.mjs b/apps/device-manager/server/device-manager-presentation.test.mjs index b83f6ca..fc9e9f9 100644 --- a/apps/device-manager/server/device-manager-presentation.test.mjs +++ b/apps/device-manager/server/device-manager-presentation.test.mjs @@ -84,7 +84,7 @@ test("Device Core overview follows the Mission Core landing-stage geometry", asy assert.ok(!client.includes(' { +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>', - '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"', diff --git a/apps/device-manager/src/DeviceControlViews.tsx b/apps/device-manager/src/DeviceControlViews.tsx index 2f2d6b8..96ee47a 100644 --- a/apps/device-manager/src/DeviceControlViews.tsx +++ b/apps/device-manager/src/DeviceControlViews.tsx @@ -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(null); + const [dialogHostRef, setDialogHostRef] = useState(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" ? ( 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} /> 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(null); - const [selectedHostRef, setSelectedHostRef] = useState(null); - useEffect(() => setSettingsHost(null), [workspace.project.projectRef]); - const [expandedHostRefs, setExpandedHostRefs] = useState>(() => new Set()); - const inventoryRef = useRef(null); + const [expandedHost, setExpandedHost] = useState(null); + const [showArchive, setShowArchive] = useState(false); + const [showAssets, setShowAssets] = useState(false); + const [archiveTarget, setArchiveTarget] = useState(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 ? setSettingsHost(null)} onChanged={onPoll} onError={onError} /> : null; if (selectedHost) { - return ( - service.hostRef === selectedHost.hostRef)} - onBack={() => setSelectedHostRef(null)} - onPoll={onPoll} - onError={onError} - /> - ); + if (isB2(selectedHost)) return
+ {settings} + setSettingsHost(selectedHost)}> : undefined}> + +
  • {source?.reachable ? 'Доступен' : source ? 'Нет связи' : 'Проверка…'}} />
  • +
  • +
  • +
  • Не подключены} />
  • +
    +
    + {b2.error ?

    {b2.error}

    : null} +
    ; + return item.hostRef === selectedHost.hostRef)} onPoll={onPoll} onError={onError} />; } - return ( -
    - {settingsHost ? setSettingsHost(null)} onChanged={onPoll} onError={onError} /> : null} -
    -
    -
    - ИНФРАСТРУКТУРА / VPS И ХОСТЫ -

    VPS и хосты

    -

    Вычислительные узлы проекта, их подключения и запущенные сервисы.

    -
    - {canManageInfrastructure ? ( -
    - -
    - ) : null} -
    -
    - host.telemetry.freshness === "fresh").length} со свежими данными`} /> - - - -
    -
    - -
    - - - - - - : null} - /> - {topology.hosts.length ? ( -
    - {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 ( -
    -
    -
    - COMPUTE HOST -

    {host.displayName}

    - {host.externalRef || host.hostKey} -
    -
    - {canManageInfrastructure ? setSettingsHost(host)}> : null} - - - toggleHost(host.hostRef)} - > - - -
    -
    - {expanded ? ( -
    -
    -
    Состояние
    {host.lifecycleState}
    -
    Провайдер
    {host.providerRef || "Не указан"}
    -
    Доступ управления
    {host.managementCredentialConfigured ? "Настроен" : "Не настроен"}
    -
    Последнее наблюдение
    {formatDate(host.telemetry.observedAt)}
    -
    -
    -
    -
    ENDPOINTS{hostEndpoints.length}
    - {hostEndpoints.length ?
    {hostEndpoints.map((endpoint) => ( - - ))}
    :

    Точки подключения не зарегистрированы.

    } -
    -
    -
    DEPLOYMENTS{hostDeployments.length}
    - {hostDeployments.length ?
    {hostDeployments.map((deployment) => ( - - ))}
    :

    Развёртывания не зарегистрированы.

    } -
    -
    -
    SERVICES{hostServices.length}
    - {hostServices.length ?
    {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 ; - })}
    :

    Сервисы не зарегистрированы.

    } -
    -
    -
    - ) : null} -
    - ); - })} -
    - ) :
    VPS и хосты для проекта пока не зарегистрированы.
    } -
    - -
    - - {canManageAssets ? : null} - {canManageBindings ? : null} - } - /> - {topology.assets.length ? ( -
    - {topology.assets.map((asset) => { - const activeBindings = topology.assetBindings.filter((binding) => binding.assetRef === asset.assetRef && !binding.validTo); - return ( - -
    {asset.assetTypeRef}{asset.displayName}{asset.assetKey}
    -
    {asset.lifecycleState}{activeBindings.length} активных привязок
    -
    - ); - })} -
    - ) :
    Объекты проекта пока не созданы.
    } - {topology.assetBindings.length ? ( -
    - {topology.assetBindings.map((binding) => ( -
    -
    DEVICE ↔ ASSET{binding.deviceName} → {binding.assetName}{binding.bindingKind} · {formatDate(binding.validFrom)}
    -
    {binding.validTo ? "Закрыта" : "Активна"}{!binding.validTo && canManageBindings ? : null}
    -
    - ))} -
    - ) : null} -
    + return
    + {settings} + { 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); } + }} /> +
    + {topology.hosts.some((host) => host.lifecycleState === 'suspended') ? : null} + {canManageInfrastructure ? : null}
    - ); + {b2.error ?

    {b2.error}

    : null} + {hosts.map((host) => { + const remote = b2.data?.hosts.find((item) => item.hostRef === host.hostRef); + const expanded = expandedHost === host.hostRef; + return
  • + {remote ? remote.reachable ? 'Подключён' : 'Нет связи' : host.lifecycleState === 'suspended' ? 'В архиве' : freshnessLabel(host.telemetry.freshness)}} + actions={<> + {canManageInfrastructure && (isB2(host) || (!host.managementCredentialConfigured && !topology.serviceInstances.some((item) => item.hostRef === host.hostRef))) ? setSettingsHost(host)}> : null} + + setExpandedHost(expanded ? null : host.hostRef)}> + } /> + {expanded ? + + {topology.endpoints.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )} + {topology.deployments.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )} + {topology.serviceInstances.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )} +
    + {canManageInfrastructure ?
    : null} + : null} + ; + })} + {!hosts.length ?

    {showArchive ? 'Архив пуст' : 'Нет подключённых VPS'}

    : null} + + {showAssets ? : undefined}> + {topology.assets.map((asset) =>
  • )}
    + {canManageBindings ? : null} + {topology.assetBindings.map((binding) =>
  • {binding.validTo ? 'Закрыта' : 'Активна'}} actions={!binding.validTo && canManageBindings ? : undefined} />
  • )}
    +
    : null} +
    ; } function HostTelemetryWorkspace({ host, services, - onBack, onPoll, onError, }: { host: InfrastructureHostView; services: InfrastructureServiceInstanceView[]; - onBack: () => void; onPoll: () => Promise; onError: (reason: unknown) => void; }) { @@ -734,12 +640,6 @@ function HostTelemetryWorkspace({
    {freshnessLabel(telemetry.freshness)} - onPoll().catch(onError)}> - - - - -
    @@ -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 { + return { await ensureInfrastructureHost({ projectRef, hostKey, @@ -1463,24 +1364,27 @@ function HostDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: st lifecycleState: "active", }); }}> - + setDisplayName(event.target.value)} required /> - setProviderRef(event.target.value)} placeholder="provider:beget" /> - setExternalRef(event.target.value)} placeholder="provider-resource:vps-123" /> - setCredentialRef(event.target.value)} placeholder="secret-ref:device-core/host-key" description="Только server-side secret reference. Пароль или приватный ключ сюда вводить нельзя." /> + + {advanced ? <> + setProviderRef(event.target.value)} placeholder="provider:beget" /> + setExternalRef(event.target.value)} placeholder="provider-resource:vps-123" /> + setCredentialRef(event.target.value)} placeholder="secret-ref:device-core/host-key" description="Ссылка secret-ref из хранилища сервера." /> + : null} ; } -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 { + return { await ensureInfrastructureEndpoint({ projectRef: workspace.project.projectRef, hostRef, @@ -1490,20 +1394,20 @@ function EndpointDialog({ workspace, ...props }: DialogBaseProps & { workspace: lifecycleState: "active", }); }}> - ({ value: item.hostRef, label: item.displayName }))} /> + + ({ value: item.hostRef, label: item.displayName }))} /> + ({ value: item.hostRef, label: item.displayName }))} /> + ({ value: item.deploymentRef, label: item.displayName }))} /> { - 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(''); } - }} /> - setConnection(event.target.value)} rows={5} /> + { + 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(''); } + }} /> + setConnection(event.target.value)} rows={4} /> : null} {section === 'contours' ? <> - +
    {[host.displayName, selected?.name, application?.name].filter(Boolean).join(' / ')}
    + {form === 'contour' || form === 'application' ?
    - {contours.map((item) => { - const link = status?.links?.find((value) => value.contourId === item.id); - return
    {item.name}{item.key}
    - {link ? projects.find((p) => p.projectRef === link.projectRef)?.name || 'Связан с проектом' : 'Не связан'}
    ; - })} - {!contours.length ?

    На VPS пока нет контуров.

    : null} - ({ value: item.projectRef, label: item.name }))} /> - + {form === 'application' ? : null} + setName(e.target.value)} /> + setKey(e.target.value.toLowerCase())} /> +
    -
    - {canManage ? -
    setName(e.target.value)} /> - setKey(e.target.value)} /> -
    -
    : null} - : null} - {section === 'applications' ? <> - {issued ? -
    - - -
    -
    : null} - {(status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core').map((app) => contours.find((item) => item.id === id)?.name || id).join(', ')}> -
    - {app.credentials.map((credential) =>
    -
    {credential.client_id}{credential.enabled ? 'Действует' : 'Отозван'}
    - {credential.enabled ? : null} -
    )} - -
    -
    )} - {canManage ? -
    setName(e.target.value)} /> - setKey(e.target.value)} /> - ({ value: p.projectRef, label: p.name }))} /> +
    +
    : !selected ? begin('contour')}> : undefined}> + {contours.map((item) => { + const link = status?.links?.find((value) => value.contourId === item.id), projectName = projects.find((p) => p.projectRef === link?.projectRef)?.name; + return
  • { setContourId(item.id); setApplicationId(''); }}>} />
  • ; + })}
    {!contours.length ?

    Контуров пока нет

    : null} +
    : !application ? <> + Контур}> p.projectRef === linkedProject)?.name || 'Не выбран'} metadata="Проект Device Core" actions={!linkedProject ? : undefined} /> + begin('application')}> : undefined}> + {applications.filter((app) => showInactive || !inactive(app)).map((app) =>
  • c.enabled) ? 'success' : 'neutral'}>{app.credentials.some((c) => c.enabled) ? 'Ключ действует' : 'Нет активного ключа'}} actions={ { setApplicationId(app.id); setShowHistory(false); }}>} />
  • )}
    + {!applications.filter((app) => showInactive || !inactive(app)).length ?

    Нет подключённых приложений

    : null} + {applications.some(inactive) ? : null} +
    + : <> + {issued ?
    : null} + setConfirm({ action: 'key-issue', fields: { integrationId: application.id, replace: true }, text: `Выдать новый ключ для «${application.name}»? Прежний ключ перестанет работать. Устройства сохранятся.` })}>{application.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}}> + {application.credentials.filter((c) => c.enabled || showHistory).map((credential) =>
  • {credential.client_id}} status={{credential.enabled ? 'Действует' : 'Отозван'}} actions={credential.enabled ? : undefined} />
  • )}
    + {!application.credentials.some((c) => c.enabled) ?

    Нет активного ключа

    : null} + {application.credentials.some((c) => !c.enabled) ? : null} +
    + } : null} - setConfirm(null)} - onConfirm={async () => { if (confirm) await run(confirm.action, confirm.fields); setConfirm(null); }} /> + setConfirm(null)} onConfirm={async () => { if (confirm && await run(confirm.action, confirm.fields)) setConfirm(null); }} /> ; } diff --git a/apps/device-manager/src/b2/b2.css b/apps/device-manager/src/b2/b2.css index 05713e4..7b42bed 100644 --- a/apps/device-manager/src/b2/b2.css +++ b/apps/device-manager/src/b2/b2.css @@ -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; } diff --git a/apps/device-manager/src/b2/useB2Inventory.ts b/apps/device-manager/src/b2/useB2Inventory.ts new file mode 100644 index 0000000..1397a5b --- /dev/null +++ b/apps/device-manager/src/b2/useB2Inventory.ts @@ -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; hosts: B2HostState[] }; +export function useB2Inventory(projectRef: string, refreshSignal: unknown) { + const [data, setData] = useState(null); + const [error, setError] = useState(''); + useEffect(() => { + let active = true, timer: ReturnType; + async function load() { + try { + const next = await b2Request(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 }; +} diff --git a/apps/device-manager/src/styles.css b/apps/device-manager/src/styles.css index 1444c94..e73c6fd 100644 --- a/apps/device-manager/src/styles.css +++ b/apps/device-manager/src/styles.css @@ -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; } diff --git a/docs/ADR_0002_SHARED_ARNAVI_VPS.md b/docs/ADR_0002_SHARED_ARNAVI_VPS.md index 382e18d..110f0ce 100644 --- a/docs/ADR_0002_SHARED_ARNAVI_VPS.md +++ b/docs/ADR_0002_SHARED_ARNAVI_VPS.md @@ -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. diff --git a/services/device-control-core/src/b2/infrastructure.mjs b/services/device-control-core/src/b2/infrastructure.mjs index 795b279..3de196b 100644 --- a/services/device-control-core/src/b2/infrastructure.mjs +++ b/services/device-control-core/src/b2/infrastructure.mjs @@ -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; diff --git a/services/device-control-core/src/lifecycle-management.mjs b/services/device-control-core/src/lifecycle-management.mjs index 2689058..705779b 100644 --- a/services/device-control-core/src/lifecycle-management.mjs +++ b/services/device-control-core/src/lifecycle-management.mjs @@ -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", diff --git a/services/device-control-core/src/lifecycle-repository.mjs b/services/device-control-core/src/lifecycle-repository.mjs index 599eb2b..ec465ed 100644 --- a/services/device-control-core/src/lifecycle-repository.mjs +++ b/services/device-control-core/src/lifecycle-repository.mjs @@ -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, diff --git a/services/device-control-core/src/ontology-management.mjs b/services/device-control-core/src/ontology-management.mjs index 95736f5..f2a5d73 100644 --- a/services/device-control-core/src/ontology-management.mjs +++ b/services/device-control-core/src/ontology-management.mjs @@ -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", diff --git a/services/device-control-core/src/ontology-repository.mjs b/services/device-control-core/src/ontology-repository.mjs index 0fd1ba4..4f04cdd 100644 --- a/services/device-control-core/src/ontology-repository.mjs +++ b/services/device-control-core/src/ontology-repository.mjs @@ -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, diff --git a/services/device-control-core/test/archive.test.mjs b/services/device-control-core/test/archive.test.mjs new file mode 100644 index 0000000..f8e88f0 --- /dev/null +++ b/services/device-control-core/test/archive.test.mjs @@ -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/); +}); diff --git a/services/device-control-core/test/b2-infrastructure.test.mjs b/services/device-control-core/test/b2-infrastructure.test.mjs index 6e6d6be..30d831e 100644 --- a/services/device-control-core/test/b2-infrastructure.test.mjs +++ b/services/device-control-core/test/b2-infrastructure.test.mjs @@ -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); + } +});