Compare commits

10 Commits
Author SHA1 Message Date
DCCONSTRUCTIONS 010fab999e Compact contour actions and delete VPS applications with all access
Device Core qualification / qualify (push) Successful in 7m19s
2026-10-01 01:10:56 +03:00
DCCONSTRUCTIONS 539c0a60b8 Download VPS installer with session and verify release digest
Device Core qualification / qualify (push) Successful in 6m30s
2026-10-01 00:21:27 +03:00
DCCONSTRUCTIONS 53dbd7483e Complete ARNavi VPS onboarding and contextual key controls
Device Core qualification / qualify (push) Successful in 6m45s
2026-09-30 23:57:17 +03:00
DCCONSTRUCTIONS 19aa5e2796 Align tracker footer actions and text with Mission settings
Device Core qualification / qualify (push) Successful in 6m28s
2026-09-30 23:02:25 +03:00
DCCONSTRUCTIONS 1266b06f9b Align tracker receipt states and attempt history with Mission Core
Device Core qualification / qualify (push) Successful in 6m37s
2026-09-30 22:48:50 +03:00
DCCONSTRUCTIONS 8941769b4c Bring Device Core settings to Mission UI and expose scoped B2 controls
Device Core qualification / qualify (push) Successful in 6m40s
2026-09-30 22:43:54 +03:00
DCCONSTRUCTIONS 8031ed76a2 fix(ui): adopt viewport-safe shared settings windows
Device Core qualification / qualify (push) Successful in 6m52s
2026-09-30 21:34:57 +03:00
DCCONSTRUCTIONS a860b00310 fix(ui): align project overview counts and complete functional labels
Device Core qualification / qualify (push) Successful in 8m43s
2026-09-30 21:27:53 +03:00
DCCONSTRUCTIONS b3b0f900c5 refactor(ui): unify registry lists and functional form labels
Device Core qualification / qualify (push) Successful in 8m18s
2026-09-30 20:59:12 +03:00
DCCONSTRUCTIONS b8d240a0a0 feat(device-manager): align functional UI with Mission Core interaction patterns
Device Core qualification / qualify (push) Successful in 8m53s
2026-09-30 20:53:19 +03:00
24 changed files with 1106 additions and 498 deletions
+3 -1
View File
@@ -58,7 +58,9 @@ platform runner registry is validated separately in `NODEDC_PLATFORM`.
The accepted Device Core policy is automatic deployment after a push to `main`
passes its checks. See [Continuous deployment](docs/CONTINUOUS_DEPLOYMENT.md)
for the pinned source qualification workflow, Synology setup and activation
status. Automatic production installation is not enabled yet.
status. Automatic production installation is active: the Synology controller fetches
qualified releases over outbound HTTPS and invokes the canonical runner.
No operator Mac or new inbound port is required.
Artifact builders in `infra/deploy-runner` emit data-only tarballs. They never
orchestrate Docker or mutate a live host. Promotion remains the established
@@ -122,7 +122,6 @@ test("host hardware monitoring retains the established geometry", async () => {
".infrastructure-host-relations {",
"grid-template-columns: repeat(3, minmax(0, 1fr));",
"grid-template-columns: repeat(4, minmax(0, 1fr));",
"background: var(--infrastructure-panel-soft);",
".host-monitoring-series polyline {",
"stroke: var(--nodedc-text-primary);",
".host-monitoring-hardware-facts {",
@@ -134,6 +133,7 @@ test("host hardware monitoring retains the established geometry", async () => {
assert.ok(!infrastructureSource.includes('title="Deployments и endpoints"'));
assert.ok(!infrastructureSource.includes("ceiling={100}"));
assert.ok(!infrastructureSource.includes("Канонический ontology catalog"));
assert.ok(!styles.includes("background: var(--infrastructure-panel-soft);"), "Functional panels must not add nested black surfaces");
assert.ok(!styles.includes(".host-telemetry-metric,"));
assert.ok(!styles.includes(".host-telemetry-facts"));
});
@@ -0,0 +1,17 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
test('downloadable VPS installer matches its immutable release metadata and deploy size limit', async () => {
const metadata = JSON.parse(await readFile(new URL('../src/b2/installer-release.json', import.meta.url), 'utf8'));
assert.match(metadata.filename, /^nodedc-arnavi-vps-\d+\.\d+\.\d+\.pyz$/);
assert.equal(metadata.environment, 'ubuntu-24.04-amd64');
assert.match(metadata.sourceCommit, /^[a-f0-9]{40}$/);
assert.equal(metadata.sourceRepository, 'https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git');
const file = await readFile(new URL('../public/installers/' + metadata.filename, import.meta.url));
assert.equal(file.length, metadata.bytes);
assert.ok(file.length < 16 * 1024 * 1024);
assert.equal(createHash('sha256').update(file).digest('hex'), metadata.sha256);
assert.equal(file.subarray(0, 2).toString(), 'PK');
});
+148 -178
View File
@@ -1,10 +1,10 @@
import { useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from "react";
import { Children, isValidElement, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from "react";
import { auditEventLabel, capabilityLabel, projectRoleLabel } from './presentationLabels';
import {
Button,
ConfirmationModal,
ResourceList as CanonicalResourceList,
ResourceRow as CanonicalResourceRow,
GlassSurface,
Icon,
IconButton,
Select,
@@ -17,6 +17,7 @@ import {
} from "@nodedc/ui-react";
import { useB2Inventory } from "./b2/useB2Inventory";
import { B2AddHost } from "./b2/B2AddHost";
import { B2HostSettings } from "./b2/B2HostSettings";
import {
@@ -30,7 +31,6 @@ import {
ensureEdge,
ensureInfrastructureDeployment,
ensureInfrastructureEndpoint,
ensureInfrastructureHost,
ensureInfrastructureServiceInstance,
ensureRoute,
registerAdapterVersion,
@@ -308,7 +308,8 @@ export function DeviceControlView({
onCreated={completed}
onError={onError}
/>
<HostDialog
<B2AddHost
key={workspace.project.projectRef + ":" + (dialog === "host")}
open={dialog === "host"}
projectRef={workspace.project.projectRef}
onClose={close}
@@ -316,7 +317,7 @@ export function DeviceControlView({
onError={onError}
/>
<EndpointDialog
key={`${dialogHostRef}:${dialog}`}
key={`EndpointDialog:${dialogHostRef}:${dialog}`}
initialHostRef={dialogHostRef}
open={dialog === "endpoint"}
workspace={workspace}
@@ -325,7 +326,7 @@ export function DeviceControlView({
onError={onError}
/>
<DeploymentDialog
key={`${dialogHostRef}:${dialog}`}
key={`DeploymentDialog:${dialogHostRef}:${dialog}`}
initialHostRef={dialogHostRef}
open={dialog === "deployment"}
workspace={workspace}
@@ -334,7 +335,7 @@ export function DeviceControlView({
onError={onError}
/>
<ServiceInstanceDialog
key={`${dialogHostRef}:${dialog}`}
key={`ServiceInstanceDialog:${dialogHostRef}:${dialog}`}
initialHostRef={dialogHostRef}
open={dialog === "service-instance"}
workspace={workspace}
@@ -365,15 +366,15 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
return (
<ControlStack>
<ControlToolbar
copy="Adapter packages и model profiles — глобальный versioned каталог. B2 здесь не является отдельным продуктом."
copy="Модели устройств и версии адаптеров."
actions={canManage ? <>
<Button size="compact" onClick={onCreatePackage}>Пакет</Button>
<Button size="compact" onClick={onCreateVersion} disabled={!workspace.adapterPackages.length}>Версия</Button>
<Button size="compact" variant="primary" onClick={onCreateProfile} disabled={!workspace.adapterVersions.length}>Профиль</Button>
</> : null}
/>
<ControlSection title="Model profiles" count={workspace.modelProfiles.length}>
<ResourceGrid empty="В доступном каталоге пока нет model profiles.">
<ControlSection title="Модели устройств" count={workspace.modelProfiles.length}>
<ResourceGrid empty="Модели устройств пока не добавлены.">
{workspace.modelProfiles.map((profile) => (
<ResourceCard
key={profile.modelProfileRef}
@@ -389,7 +390,7 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
))}
</ResourceGrid>
</ControlSection>
<ControlSection title="Adapter versions" count={workspace.adapterVersions.length}>
<ControlSection title="Версии адаптеров" count={workspace.adapterVersions.length}>
<ResourceGrid empty="Версии адаптеров не зарегистрированы.">
{workspace.adapterVersions.map((version) => (
<ResourceCard
@@ -406,8 +407,8 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
))}
</ResourceGrid>
</ControlSection>
<ControlSection title="Adapter packages" count={workspace.adapterPackages.length}>
<ResourceGrid empty="Adapter packages не зарегистрированы.">
<ControlSection title="Адаптеры" count={workspace.adapterPackages.length}>
<ResourceGrid empty="Адаптеры пока не добавлены.">
{workspace.adapterPackages.map((adapterPackage) => (
<ResourceCard
key={adapterPackage.adapterPackageRef}
@@ -438,13 +439,13 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
return (
<ControlStack>
<ControlToolbar
copy="Edge — зарегистрированная внешняя роль. Route связывает проект, Edge, profile и логический listener без credentials."
copy="Узлы приёма данных и маршруты устройств."
actions={<>
{canManageCatalog ? <Button size="compact" onClick={onCreateEdge}>Новый Edge</Button> : null}
{canManageCatalog ? <Button size="compact" onClick={onCreateEdge}>Новый узел</Button> : null}
{canManageRoutes ? <Button size="compact" variant="primary" onClick={onCreateRoute} disabled={!workspace.edges.length || !workspace.modelProfiles.length}>Новый маршрут</Button> : null}
</>}
/>
<ControlSection title="Routes" count={workspace.routes.length}>
<ControlSection title="Маршруты" count={workspace.routes.length}>
<ResourceGrid empty="Маршрутов в проекте пока нет.">
{workspace.routes.map((route) => (
<ResourceCard
@@ -464,12 +465,12 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
))}
</ResourceGrid>
</ControlSection>
<ControlSection title="Edges" count={workspace.edges.length}>
<ResourceGrid empty="Доступных Edge registrations нет.">
<ControlSection title="Узлы приёма данных" count={workspace.edges.length}>
<ResourceGrid empty="Узлы пока не добавлены.">
{workspace.edges.map((edge) => (
<ResourceCard
key={edge.edgeRef}
eyebrow="DEVICE GATEWAY EDGE"
eyebrow="Узел приёма данных"
title={edge.displayName}
description={edge.edgeKey}
status={edge.lifecycleState}
@@ -567,16 +568,17 @@ function HostsView({
status={<StatusBadge tone={remote ? remote.reachable ? 'success' : 'warning' : freshnessTone(host.telemetry.freshness)}>{remote ? remote.reachable ? 'Подключён' : 'Нет связи' : host.lifecycleState === 'suspended' ? 'В архиве' : freshnessLabel(host.telemetry.freshness)}</StatusBadge>}
actions={<>
{canManageInfrastructure && (isB2(host) || (!host.managementCredentialConfigured && !topology.serviceInstances.some((item) => item.hostRef === host.hostRef))) ? <IconButton label={`Настройки ${host.displayName}`} onClick={() => setSettingsHost(host)}><Icon name="settings" /></IconButton> : null}
<Button size="compact" onClick={() => onSelectHost(host.hostRef)}>Мониторинг</Button>
<IconButton label={`Сведения ${host.displayName}`} aria-expanded={expanded} onClick={() => setExpandedHost(expanded ? null : host.hostRef)}><Icon name="chevron-down" /></IconButton>
<IconButton label={`Мониторинг ${host.displayName}`} onClick={() => onSelectHost(host.hostRef)}><Icon name="activity" /></IconButton>
<IconButton label={`Сведения ${host.displayName}`} aria-expanded={expanded} onClick={() => setExpandedHost(expanded ? null : host.hostRef)}><Icon name={expanded ? "chevron-up" : "chevron-down"} /></IconButton>
</>} />
{expanded ? <SettingsCard title="Сведения о хосте">
<CanonicalResourceList>
{isB2(host) ? <li><CanonicalResourceRow title="ARNavi VPS" description={remote?.endpoint} metadata="Адрес получен из ключа сервера" /></li> : null}
{topology.endpoints.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.endpointRef}><CanonicalResourceRow title="Адрес подключения" description={item.endpointUri} /></li>)}
{topology.deployments.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.deploymentRef}><CanonicalResourceRow title={item.displayName} metadata="Развёртывание" /></li>)}
{topology.serviceInstances.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.serviceInstanceRef}><CanonicalResourceRow title={item.displayName} metadata="Сервис" /></li>)}
</CanonicalResourceList>
{canManageInfrastructure ? <div className="b2-actions"><Button disabled={archiving} onClick={() => setArchiveTarget(host)}>{host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button><Button onClick={() => onCreateEndpoint(host.hostRef)}>Адрес</Button><Button onClick={() => onCreateDeployment(host.hostRef)}>Развёртывание</Button><Button onClick={() => onCreateService(host.hostRef)} disabled={!topology.deployments.length}>Сервис</Button></div> : null}
{canManageInfrastructure ? <div className="b2-actions"><Button disabled={archiving} onClick={() => setArchiveTarget(host)}>{host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button>{!isB2(host) ? <><Button onClick={() => onCreateEndpoint(host.hostRef)}>Адрес</Button><Button onClick={() => onCreateDeployment(host.hostRef)}>Развёртывание</Button><Button onClick={() => onCreateService(host.hostRef)} disabled={!topology.deployments.some((item) => item.hostRef === host.hostRef)}>Сервис</Button></> : null}</div> : null}
</SettingsCard> : null}
</li>;
})}</CanonicalResourceList>
@@ -650,7 +652,7 @@ function HostTelemetryWorkspace({
<HostTelemetrySeries label="NETWORK TX" value={formatRate(networkRate.sent)} resource={networkRate.sent == null ? "нет данных" : "исходящий трафик"} values={sendHistory} />
</section>
<GlassSurface className="host-monitoring-hardware" padding="lg">
<div className="host-monitoring-hardware">
<InfrastructureSectionHeading
eyebrow="HARDWARE"
title={current?.hardware.hostname ?? host.hostKey}
@@ -681,7 +683,7 @@ function HostTelemetryWorkspace({
))}
{!current?.disks.length ? <div className="infrastructure-empty">Данные о дисках ещё не поступили.</div> : null}
</div>
</GlassSurface>
</div>
<section className="infrastructure-section">
<InfrastructureSectionHeading
@@ -693,7 +695,7 @@ function HostTelemetryWorkspace({
{networkInterfaces.length ? (
<div className="host-monitoring-network-grid">
{networkInterfaces.map((item, index) => (
<GlassSurface className="host-monitoring-network-card" padding="md" tone="soft" key={`${item.interface}:${index}`}>
<div className="host-monitoring-network-card" key={`${item.interface}:${index}`}>
<header><strong>{item.interface ?? "Интерфейс"}</strong><small>{formatPackets(item.packetsReceived, item.packetsSent)}</small></header>
<dl>
<div><dt>Получено</dt><dd>{formatMetricBytes(item.bytesReceived)}</dd></div>
@@ -701,7 +703,7 @@ function HostTelemetryWorkspace({
<div><dt>Ошибки RX / TX</dt><dd>{formatNullable(item.errorsReceived)} / {formatNullable(item.errorsSent)}</dd></div>
<div><dt>Потери RX / TX</dt><dd>{formatNullable(item.droppedReceived)} / {formatNullable(item.droppedSent)}</dd></div>
</dl>
</GlassSurface>
</div>
))}
</div>
) : <div className="infrastructure-empty">Сетевые счётчики ещё не поступили.</div>}
@@ -718,7 +720,7 @@ function HostTelemetryWorkspace({
{runtimeServices.length ? (
<div className="infrastructure-runtime-grid">
{runtimeServices.map((service, index) => (
<GlassSurface className="host-monitoring-runtime-card" padding="md" tone="soft" key={`${service.name}:${index}`}>
<div className="host-monitoring-runtime-card" key={`${service.name}:${index}`}>
<header>
<div><span className="infrastructure-eyebrow">SYSTEMD UNIT</span><h3>{service.name ?? "systemd unit"}</h3><code>{service.subState ?? "—"}</code></div>
<StatusBadge tone={service.activeState === "active" ? "success" : service.activeState === "failed" ? "danger" : "warning"}>{service.activeState ?? "unknown"}</StatusBadge>
@@ -729,7 +731,7 @@ function HostTelemetryWorkspace({
<div><dt>Перезапуски</dt><dd>{formatNullable(service.restarts)}</dd></div>
<div><dt>PID</dt><dd>{formatNullable(service.pid)}</dd></div>
</dl>
</GlassSurface>
</div>
))}
</div>
) : <div className="infrastructure-empty">Состояние сервисов ещё не поступило.</div>}
@@ -964,8 +966,8 @@ function formatPackets(received: number | null | undefined, sent: number | null
function SessionsView({ workspace }: { workspace: ProjectWorkspace }) {
return (
<ControlStack>
<ControlToolbar copy="Сессии принадлежат Gateway runtime. Device Manager только читает bounded presence/counter projection." />
<ResourceList empty="Gateway sessions пока не наблюдались.">
<ControlToolbar copy="Подключения устройств" />
<ResourceList empty="Нет подключений">
{workspace.sessions.map((session) => (
<ResourceRow
key={session.sessionRef}
@@ -989,10 +991,10 @@ function BindingsView({ workspace, canManage, onCreate, onRevoke }: {
return (
<ControlStack>
<ControlToolbar
copy="Binding создаёт только source approval. Active появится лишь после отдельного external proof от целевой системы."
actions={canManage ? <Button variant="primary" onClick={onCreate} disabled={!workspace.collections.length && !workspace.devices.length}>Новый binding</Button> : null}
copy="Передача данных в приложения"
actions={canManage ? <Button variant="primary" onClick={onCreate} disabled={!workspace.collections.length && !workspace.devices.length}>Новая привязка</Button> : null}
/>
<ResourceList empty="Data bindings пока не создавались.">
<ResourceList empty="Привязок пока нет">
{workspace.bindings.map((binding) => (
<ResourceRow
key={binding.bindingRef}
@@ -1049,18 +1051,17 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
};
return (
<ControlStack>
<GlassSurface className="device-control-command-policy" padding="md" tone="soft">
<div className="device-control-command-policy">
<Icon name={enabled ? "check" : "lock"} />
<div>
<strong>{enabled ? "Типизированный командный канал активен" : "Command transport выключен"}</strong>
<strong>{enabled ? "Проверка сервиса устройства" : "Команды для этого канала недоступны"}</strong>
<p>{enabled
? "Доступна только безопасная проверка сервиса. Произвольные команды, прошивка, очистка памяти и перезагрузка отсутствуют. Код устройства существует только в памяти Core до отправки или истечения TTL."
: "Ни UI, ни BFF не имеют raw command builder. acknowledged означает подтверждение протокола, verified — отдельное доказательство состояния."}</p>
? "Выберите устройство и введите его шестизначный код."
: "Для этого подключения отправка команд ещё не настроена."}</p>
</div>
</div>
<StatusBadge tone={enabled ? "success" : "warning"}>{workspace.policies.commandTransport}</StatusBadge>
</GlassSurface>
{enabled ? (
<GlassSurface padding="md" tone="soft">
<div>
<form className="device-control-command-form" onSubmit={submit}>
<Select
label="B2 трекер"
@@ -1095,14 +1096,14 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
{submitting ? "Ставим в очередь…" : "Проверить сервис"}
</Button>
</form>
</GlassSurface>
</div>
) : null}
<ResourceList empty="Command intents отсутствуют. Это не означает, что транспорт доступен.">
<ResourceList empty="Команд пока нет">
{workspace.commands.map((command) => (
<ResourceRow
key={command.commandRef}
title={`${command.commandType} · ${command.deviceName}`}
description={`${command.riskClass} · expires ${formatDate(command.expiresAt)}`}
description={`${command.riskClass} · до ${formatDate(command.expiresAt)}`}
status={command.lifecycleState}
trailing={command.terminalReasonCode || command.commandKey}
/>
@@ -1115,15 +1116,15 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
function AuditView({ workspace }: { workspace: ProjectWorkspace }) {
return (
<ControlStack>
<ControlToolbar copy="Показывается immutable metadata projection. Audit payload намеренно не выдаётся в браузер." />
<ResourceList empty="Audit events для проекта отсутствуют.">
<ControlToolbar copy="История действий в проекте" />
<ResourceList empty="Действий пока нет">
{workspace.auditEvents.map((event) => (
<ResourceRow
key={event.auditEventRef}
title={event.eventType}
title={auditEventLabel(event.eventType)}
description={`${event.actorRef} · ${formatDate(event.occurredAt)}`}
status="recorded"
trailing={event.deviceRef || event.discoveryRef || "project"}
trailing={event.deviceRef || event.discoveryRef || "Проект"}
/>
))}
</ResourceList>
@@ -1139,17 +1140,17 @@ function AccessView({ workspace, canManage, onCreate }: {
return (
<ControlStack>
<ControlToolbar
copy="Hub задаёт потолок, а Device Project grant — конкретную роль. Direct user grant имеет приоритет над group grants."
copy="Доступ к проекту"
actions={canManage ? <Button variant="primary" onClick={onCreate}>Добавить доступ</Button> : null}
/>
<ResourceList empty="Project grants недоступны или ещё не созданы.">
<ResourceList empty="Доступ пока не назначен">
{workspace.grants.map((grant) => (
<ResourceRow
key={grant.grantRef}
title={grant.principalRef}
description={`${grant.principalKind} · ${grant.projectRole}`}
description={`${({ user: 'Пользователь', group: 'Группа', service: 'Приложение' } as Record<string, string>)[grant.principalKind] || grant.principalKind} · ${projectRoleLabel(grant.projectRole)}`}
status={grant.lifecycleState}
trailing={grant.capabilityDeny.length ? `deny: ${grant.capabilityDeny.join(", ")}` : "role capabilities"}
trailing={grant.capabilityDeny.length ? `Исключения: ${grant.capabilityDeny.map(capabilityLabel).join(", ")}` : "Права роли"}
/>
))}
</ResourceList>
@@ -1164,32 +1165,27 @@ function SettingsView({ workspace, canConfigure, onCreateConfiguration }: {
}) {
return (
<ControlStack>
<div className="device-control-policy-grid">
<PolicyCard label="Identifiers" value={workspace.policies.identifierProjection} />
<PolicyCard label="Audit payload" value={workspace.policies.auditPayloadProjection} />
<PolicyCard label="Command API" value={workspace.policies.commandPlanningApi} />
</div>
<ControlToolbar
copy="Configuration revisions immutable. Desired и applied — разные указатели; создание desired не означает применение устройством."
actions={canConfigure ? <Button variant="primary" onClick={onCreateConfiguration} disabled={!workspace.devices.length}>Новая desired revision</Button> : null}
copy="Настройки устройств"
actions={canConfigure ? <Button variant="primary" onClick={onCreateConfiguration} disabled={!workspace.devices.length}>Новая версия настроек</Button> : null}
/>
<ResourceList empty="Configuration state пока отсутствует.">
<ResourceList empty="Сохранённых настроек пока нет">
{workspace.configurationStates.map((state) => (
<ResourceRow
key={state.deviceRef}
title={state.deviceName}
description={`desired: ${shortRef(state.desiredConfigurationRevisionRef)} · applied: ${shortRef(state.appliedConfigurationRevisionRef)}`}
description={`Сохранено: ${shortRef(state.desiredConfigurationRevisionRef)} · Применено: ${shortRef(state.appliedConfigurationRevisionRef)}`}
status={state.appliedConfigurationRevisionRef === state.desiredConfigurationRevisionRef ? "applied" : "pending"}
trailing={formatDate(state.updatedAt)}
/>
))}
</ResourceList>
<ControlSection title="Immutable revisions" count={workspace.configurationRevisions.length}>
<ResourceList empty="Configuration revisions отсутствуют.">
<ControlSection title="История настроек" count={workspace.configurationRevisions.length}>
<ResourceList empty="Версий пока нет">
{workspace.configurationRevisions.map((revision) => (
<ResourceRow
key={revision.configurationRevisionRef}
title={`${revision.deviceName} · revision ${revision.revisionNumber}`}
title={`${revision.deviceName} · Версия ${revision.revisionNumber}`}
description={revision.changeSummary || revision.modelProfileRef}
status="immutable"
trailing={shortDigest(revision.configurationDigest)}
@@ -1205,12 +1201,12 @@ function AdapterPackageDialog(props: DialogBaseProps) {
const [packageKey, setPackageKey] = useState("");
const [displayName, setDisplayName] = useState("");
const [publisherRef, setPublisherRef] = useState("");
return <FormWindow {...props} id="adapter-package-form" title="Adapter package" submit={async () => {
return <FormWindow {...props} id="adapter-package-form" title="Адаптер" submit={async () => {
await ensureAdapterPackage({ packageKey, displayName, publisherRef, lifecycleState: "active" });
}}>
<KeyField label="Ключ пакета" value={packageKey} onChange={setPackageKey} />
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
<TextField label="Publisher ref" value={publisherRef} onChange={(event) => setPublisherRef(event.target.value)} required />
<TextField label="Издатель" value={publisherRef} onChange={(event) => setPublisherRef(event.target.value)} required />
</FormWindow>;
}
@@ -1237,12 +1233,12 @@ function AdapterVersionDialog({ packages, ...props }: DialogBaseProps & { packag
lifecycleState: "draft",
});
}}>
<Select label="Adapter package" value={packageRef} onChange={setPackageRef} options={packages.map((item) => ({ value: item.adapterPackageRef, label: item.displayName }))} />
<Select label="Адаптер" value={packageRef} onChange={setPackageRef} options={packages.map((item) => ({ value: item.adapterPackageRef, label: item.displayName }))} />
<TextField label="SemVer" value={version} onChange={(event) => setVersion(event.target.value)} required placeholder="1.0.0" />
<TextField label="Runtime artifact ref" value={runtimeRef} onChange={(event) => setRuntimeRef(event.target.value)} required />
<TextField label="Content digest" value={digest} onChange={(event) => setDigest(event.target.value)} required placeholder="sha256:…" />
<TextField label="Contract version" value={contractVersion} onChange={(event) => setContractVersion(event.target.value)} required />
<TextField label="Capabilities" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} description="Через запятую" />
<TextField label="Файл адаптера" value={runtimeRef} onChange={(event) => setRuntimeRef(event.target.value)} required />
<TextField label="Контрольная сумма" value={digest} onChange={(event) => setDigest(event.target.value)} required placeholder="sha256:…" />
<TextField label="Версия контракта" value={contractVersion} onChange={(event) => setContractVersion(event.target.value)} required />
<TextField label="Возможности" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} description="Через запятую" />
</FormWindow>;
}
@@ -1262,7 +1258,7 @@ function ModelProfileDialog({ versions, ...props }: DialogBaseProps & { versions
setVersionRef(versions[0]?.adapterVersionRef ?? "");
}
}, [versionRef, versions]);
return <FormWindow {...props} id="model-profile-form" title="Model profile" disabled={!versionRef} submit={async () => {
return <FormWindow {...props} id="model-profile-form" title="Профиль модели" disabled={!versionRef} submit={async () => {
await registerModelProfile({
adapterVersionRef: versionRef,
profileRef,
@@ -1277,16 +1273,16 @@ function ModelProfileDialog({ versions, ...props }: DialogBaseProps & { versions
lifecycleState: "draft",
});
}}>
<Select label="Adapter version" value={versionRef} onChange={setVersionRef} options={versions.map((item) => ({ value: item.adapterVersionRef, label: item.version, description: item.runtimePackageRef }))} />
<TextField label="Profile ref" value={profileRef} onChange={(event) => setProfileRef(event.target.value)} required />
<TextField label="Schema version" value={schemaVersion} onChange={(event) => setSchemaVersion(event.target.value)} required />
<TextField label="Vendor" value={vendor} onChange={(event) => setVendor(event.target.value)} required />
<TextField label="Model" value={model} onChange={(event) => setModel(event.target.value)} required />
<KeyField label="Device type" value={deviceType} onChange={setDeviceType} />
<TextField label="Protocol" value={protocol} onChange={(event) => setProtocol(event.target.value)} required />
<TextField label="Schema artifact ref" value={schemaRef} onChange={(event) => setSchemaRef(event.target.value)} required />
<TextField label="Profile digest" value={digest} onChange={(event) => setDigest(event.target.value)} required placeholder="sha256:…" />
<TextField label="Capabilities" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} />
<Select label="Версия адаптера" value={versionRef} onChange={setVersionRef} options={versions.map((item) => ({ value: item.adapterVersionRef, label: item.version, description: item.runtimePackageRef }))} />
<TextField label="Идентификатор профиля" value={profileRef} onChange={(event) => setProfileRef(event.target.value)} required />
<TextField label="Версия схемы" value={schemaVersion} onChange={(event) => setSchemaVersion(event.target.value)} required />
<TextField label="Производитель" value={vendor} onChange={(event) => setVendor(event.target.value)} required />
<TextField label="Модель" value={model} onChange={(event) => setModel(event.target.value)} required />
<KeyField label="Тип устройства" value={deviceType} onChange={setDeviceType} />
<TextField label="Протокол" value={protocol} onChange={(event) => setProtocol(event.target.value)} required />
<TextField label="Файл схемы" value={schemaRef} onChange={(event) => setSchemaRef(event.target.value)} required />
<TextField label="Контрольная сумма профиля" value={digest} onChange={(event) => setDigest(event.target.value)} required placeholder="sha256:…" />
<TextField label="Возможности" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} />
</FormWindow>;
}
@@ -1294,7 +1290,7 @@ function AssetDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: s
const [assetKey, setAssetKey] = useState("");
const [displayName, setDisplayName] = useState("");
const [assetTypeRef, setAssetTypeRef] = useState("asset-type:delivery-trike");
return <FormWindow {...props} id="asset-form" title="Новый Asset" submit={async () => {
return <FormWindow {...props} id="asset-form" title="Новый объект" submit={async () => {
await ensureAsset({
projectRef,
assetKey,
@@ -1303,9 +1299,9 @@ function AssetDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: s
lifecycleState: "active",
});
}}>
<KeyField label="Asset key" value={assetKey} onChange={setAssetKey} />
<KeyField label="Код объекта" value={assetKey} onChange={setAssetKey} />
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
<TextField label="Asset type ref" value={assetTypeRef} onChange={(event) => setAssetTypeRef(event.target.value)} required description="Канонический тип или стабильная ссылка на тип, не модель трекера." />
<TextField label="Тип объекта" value={assetTypeRef} onChange={(event) => setAssetTypeRef(event.target.value)} required description="Канонический тип или стабильная ссылка на тип, не модель трекера." />
</FormWindow>;
}
@@ -1323,7 +1319,7 @@ function AssetBindingDialog({ workspace, ...props }: DialogBaseProps & { workspa
setAssetRef(workspace.ontology.assets[0]?.assetRef ?? "");
}
}, [assetRef, deviceRef, workspace]);
return <FormWindow {...props} id="asset-binding-form" title="Привязать Device к Asset" disabled={!deviceRef || !assetRef} submit={async () => {
return <FormWindow {...props} id="asset-binding-form" title="Привязать устройство к объекту" disabled={!deviceRef || !assetRef} submit={async () => {
await ensureAssetBinding({
projectRef: workspace.project.projectRef,
bindingKey,
@@ -1334,44 +1330,15 @@ function AssetBindingDialog({ workspace, ...props }: DialogBaseProps & { workspa
provenanceRef,
});
}}>
<Select label="Device" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} />
<Select label="Asset" value={assetRef} onChange={setAssetRef} options={workspace.ontology.assets.map((item) => ({ value: item.assetRef, label: item.displayName, description: item.assetTypeRef }))} />
<KeyField label="Binding key" value={bindingKey} onChange={setBindingKey} />
<Select label="Relation" value={bindingKind} onChange={setBindingKind} options={[
<Select label="Устройство" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} />
<Select label="Объект" value={assetRef} onChange={setAssetRef} options={workspace.ontology.assets.map((item) => ({ value: item.assetRef, label: item.displayName, description: item.assetTypeRef }))} />
<KeyField label="Код связи" value={bindingKey} onChange={setBindingKey} />
<Select label="Тип связи" value={bindingKind} onChange={setBindingKind} options={[
{ value: "tracking", label: "Tracking" },
{ value: "installed", label: "Installed" },
{ value: "assigned", label: "Assigned" },
]} />
<TextField label="Provenance ref" value={provenanceRef} onChange={(event) => setProvenanceRef(event.target.value)} required />
</FormWindow>;
}
function HostDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: string }) {
const [advanced, setAdvanced] = useState(false);
const [hostKey, setHostKey] = useState("");
const [displayName, setDisplayName] = useState("");
const [providerRef, setProviderRef] = useState("");
const [externalRef, setExternalRef] = useState("");
const [credentialRef, setCredentialRef] = useState("");
return <FormWindow {...props} id="host-form" title="Новый VPS" submit={async () => {
await ensureInfrastructureHost({
projectRef,
hostKey,
displayName,
providerRef: providerRef || null,
externalRef: externalRef || null,
managementCredentialRef: credentialRef || null,
lifecycleState: "active",
});
}}>
<KeyField label="Код VPS" value={hostKey} onChange={setHostKey} />
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
<Button variant="ghost" aria-expanded={advanced} onClick={() => setAdvanced(!advanced)}>Дополнительно</Button>
{advanced ? <>
<TextField label="Провайдер" value={providerRef} onChange={(event) => setProviderRef(event.target.value)} placeholder="provider:beget" />
<TextField label="Идентификатор у провайдера" value={externalRef} onChange={(event) => setExternalRef(event.target.value)} placeholder="provider-resource:vps-123" />
<TextField label="Ссылка на серверный ключ" value={credentialRef} onChange={(event) => setCredentialRef(event.target.value)} placeholder="secret-ref:device-core/host-key" description="Ссылка secret-ref из хранилища сервера." />
</> : null}
<TextField label="Источник сведений" value={provenanceRef} onChange={(event) => setProvenanceRef(event.target.value)} required />
</FormWindow>;
}
@@ -1401,7 +1368,7 @@ function EndpointDialog({ workspace, initialHostRef, ...props }: DialogBaseProps
{ value: "monitoring", label: "Monitoring" },
{ value: "service", label: "Service" },
]} />
<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 будет отклонён." />
<TextField label="Адрес" value={endpointUri} onChange={(event) => setEndpointUri(event.target.value)} required placeholder="ssh://203.0.113.10:22/" description="HTTPS, SSH или TCP, без паролей и параметров запроса." />
</FormWindow>;
}
@@ -1427,10 +1394,10 @@ function DeploymentDialog({ workspace, initialHostRef, ...props }: DialogBasePro
});
}}>
<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} />
<KeyField label="Код развёртывания" 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" />
<TextField label="Artifact digest" value={artifactDigest} onChange={(event) => setArtifactDigest(event.target.value)} required placeholder="sha256:…" />
<TextField label="Файл сборки" value={artifactRef} onChange={(event) => setArtifactRef(event.target.value)} required placeholder="artifact:device-edge/1.0.0" />
<TextField label="Контрольная сумма сборки" value={artifactDigest} onChange={(event) => setArtifactDigest(event.target.value)} required placeholder="sha256:…" />
</FormWindow>;
}
@@ -1462,21 +1429,21 @@ function ServiceInstanceDialog({ workspace, initialHostRef, ...props }: DialogBa
});
}}>
<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" },
<Select label="Развёртывание" value={deploymentRef} onChange={setDeploymentRef} options={matchingDeployments.map((item) => ({ value: item.deploymentRef, label: item.displayName }))} />
<Select label="Узел приёма данных" value={edgeRef} onChange={setEdgeRef} options={[
{ value: "", label: "Без привязки к узлу" },
...workspace.edges.map((item) => ({ value: item.edgeRef, label: item.displayName, description: item.channel.runtimeState })),
]} />
<KeyField label="Service key" value={serviceKey} onChange={setServiceKey} />
<KeyField label="Код сервиса" value={serviceKey} onChange={setServiceKey} />
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
<TextField label="Service role" value={serviceRole} onChange={(event) => setServiceRole(event.target.value.toLowerCase())} required placeholder="device.edge" />
<TextField label="Роль сервиса" value={serviceRole} onChange={(event) => setServiceRole(event.target.value.toLowerCase())} required placeholder="device.edge" />
</FormWindow>;
}
function HealthObservationDialog({ workspace, ...props }: DialogBaseProps & { workspace: ProjectWorkspace }) {
const targets = [
...workspace.ontology.hosts.map((item) => ({ value: `host|${item.hostRef}`, label: item.displayName, description: "Host" })),
...workspace.ontology.serviceInstances.map((item) => ({ value: `service-instance|${item.serviceInstanceRef}`, label: item.displayName, description: "Service instance" })),
...workspace.ontology.hosts.map((item) => ({ value: `host|${item.hostRef}`, label: item.displayName, description: "Хост" })),
...workspace.ontology.serviceInstances.map((item) => ({ value: `service-instance|${item.serviceInstanceRef}`, label: item.displayName, description: "Сервис" })),
];
const [target, setTarget] = useState(targets[0]?.value ?? "");
const [observedState, setObservedState] = useState<"reachable" | "degraded" | "unreachable">("reachable");
@@ -1485,7 +1452,7 @@ function HealthObservationDialog({ workspace, ...props }: DialogBaseProps & { wo
useEffect(() => {
if (!targets.some((item) => item.value === target)) setTarget(targets[0]?.value ?? "");
}, [target, targets]);
return <FormWindow {...props} id="health-observation-form" title="Health evidence" disabled={!target} submit={async () => {
return <FormWindow {...props} id="health-observation-form" title="Записать состояние" disabled={!target} submit={async () => {
const [subjectKind, subjectRef] = target.split("|");
const observedAt = new Date();
const ttl = Number(ttlMinutes);
@@ -1502,15 +1469,15 @@ function HealthObservationDialog({ workspace, ...props }: DialogBaseProps & { wo
expiresAt: new Date(observedAt.valueOf() + ttl * 60_000).toISOString(),
});
}}>
<Select label="Subject" value={target} onChange={setTarget} options={targets} />
<Select label="Observed state" value={observedState} onChange={setObservedState} options={[
{ value: "reachable", label: "Reachable" },
{ value: "degraded", label: "Degraded" },
{ value: "unreachable", label: "Unreachable" },
<Select label="Объект" value={target} onChange={setTarget} options={targets} />
<Select label="Состояние" value={observedState} onChange={setObservedState} options={[
{ value: "reachable", label: "Доступен" },
{ value: "degraded", label: "Работает с ошибками" },
{ value: "unreachable", label: "Недоступен" },
]} />
<TextField label="TTL, минут" value={ttlMinutes} onChange={(event) => setTtlMinutes(event.target.value)} required inputMode="numeric" />
<TextAreaField label="Bounded evidence JSON" value={evidence} onChange={(event) => setEvidence(event.target.value)} required />
<p className="device-manager-card-copy">Это ручное наблюдение с TTL. Автоматический probe должен писать тот же canonical contract от собственного source ref.</p>
<TextField label="Действует, минут" value={ttlMinutes} onChange={(event) => setTtlMinutes(event.target.value)} required inputMode="numeric" />
<TextAreaField label="Данные наблюдения JSON" value={evidence} onChange={(event) => setEvidence(event.target.value)} required />
<p className="device-manager-card-copy">Состояние действует до указанного срока.</p>
</FormWindow>;
}
@@ -1518,12 +1485,12 @@ function EdgeDialog(props: DialogBaseProps) {
const [edgeKey, setEdgeKey] = useState("");
const [displayName, setDisplayName] = useState("");
const [deploymentRef, setDeploymentRef] = useState("");
return <FormWindow {...props} id="edge-form" title="Новый Edge" submit={async () => {
return <FormWindow {...props} id="edge-form" title="Новый узел" submit={async () => {
await ensureEdge({ edgeKey, displayName, deploymentRef: deploymentRef || null, lifecycleState: "provisioning" });
}}>
<KeyField label="Edge key" value={edgeKey} onChange={setEdgeKey} />
<KeyField label="Код узла" value={edgeKey} onChange={setEdgeKey} />
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
<TextField label="Deployment ref" value={deploymentRef} onChange={(event) => setDeploymentRef(event.target.value)} description="Opaque artifact/deployment reference, не адрес и не credential." />
<TextField label="Ссылка на развёртывание" value={deploymentRef} onChange={(event) => setDeploymentRef(event.target.value)} description="" />
</FormWindow>;
}
@@ -1555,12 +1522,12 @@ function RouteDialog({ workspace, ...props }: DialogBaseProps & { workspace: Pro
lifecycleState: "draft",
});
}}>
<KeyField label="Route key" value={routeKey} onChange={setRouteKey} />
<KeyField label="Код маршрута" value={routeKey} onChange={setRouteKey} />
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
<Select label="Edge" value={edgeRef} onChange={setEdgeRef} options={workspace.edges.map((item) => ({ value: item.edgeRef, label: item.displayName, description: item.lifecycleState }))} />
<Select label="Model profile" value={profileRef} onChange={setProfileRef} options={workspace.modelProfiles.map((item) => ({ value: item.modelProfileRef, label: `${item.vendor} ${item.model}`, description: item.protocol }))} />
<TextField label="Listener ref" value={listenerRef} onChange={(event) => setListenerRef(event.target.value)} required />
<p className="device-manager-card-copy">Маршрут создаётся draft. Его activation остаётся отдельным осознанным изменением данных.</p>
<Select label="Узел приёма данных" value={edgeRef} onChange={setEdgeRef} options={workspace.edges.map((item) => ({ value: item.edgeRef, label: item.displayName, description: item.lifecycleState }))} />
<Select label="Профиль модели" value={profileRef} onChange={setProfileRef} options={workspace.modelProfiles.map((item) => ({ value: item.modelProfileRef, label: `${item.vendor} ${item.model}`, description: item.protocol }))} />
<TextField label="Канал приёма" value={listenerRef} onChange={(event) => setListenerRef(event.target.value)} required />
<p className="device-manager-card-copy">После создания маршрут можно активировать в списке.</p>
</FormWindow>;
}
@@ -1580,7 +1547,7 @@ function BindingDialog({ workspace, ...props }: DialogBaseProps & { workspace: P
setSourceValue(sources[0]?.value ?? "");
}
}, [sourceValue, sources]);
return <FormWindow {...props} id="binding-form" title="Новый data binding" disabled={!sourceValue} submit={async () => {
return <FormWindow {...props} id="binding-form" title="Новая связь с приложением" disabled={!sourceValue} submit={async () => {
const [kind, ref] = sourceValue.split("|");
await ensureDeviceBinding({
projectRef: workspace.project.projectRef,
@@ -1592,12 +1559,12 @@ function BindingDialog({ workspace, ...props }: DialogBaseProps & { workspace: P
capabilities: commaList(capabilities),
});
}}>
<Select label="Source" value={sourceValue} onChange={setSourceValue} options={sources} />
<KeyField label="Binding key" value={bindingKey} onChange={setBindingKey} />
<Select label="Источник" value={sourceValue} onChange={setSourceValue} options={sources} />
<KeyField label="Код связи" value={bindingKey} onChange={setBindingKey} />
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
<TextField label="Target kind" value={targetKind} onChange={(event) => setTargetKind(event.target.value)} required placeholder="foundry.application" />
<TextField label="Target ref" value={targetRef} onChange={(event) => setTargetRef(event.target.value)} required />
<TextField label="Capabilities" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} description="observe, inspect, configure, command" required />
<TextField label="Тип приложения" value={targetKind} onChange={(event) => setTargetKind(event.target.value)} required placeholder="foundry.application" />
<TextField label="Идентификатор приложения" value={targetRef} onChange={(event) => setTargetRef(event.target.value)} required />
<TextField label="Возможности" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} description="observe, inspect, configure, command" required />
</FormWindow>;
}
@@ -1607,7 +1574,7 @@ function GrantDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: s
const [role, setRole] = useState("viewer");
const [allow, setAllow] = useState("");
const [deny, setDeny] = useState("");
return <FormWindow {...props} id="grant-form" title="Project access" submit={async () => {
return <FormWindow {...props} id="grant-form" title="Доступ к проекту" submit={async () => {
await upsertProjectGrant({
projectRef,
principalKind,
@@ -1618,11 +1585,11 @@ function GrantDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: s
lifecycleState: "active",
});
}}>
<Select label="Principal type" value={principalKind} onChange={setPrincipalKind} options={[{ value: "user", label: "User" }, { value: "group", label: "Group" }]} />
<TextField label="Principal ref" value={principalRef} onChange={(event) => setPrincipalRef(event.target.value)} required />
<Select label="Project role" value={role} onChange={setRole} options={["viewer", "operator", "engineer", "admin", "owner"].map((value) => ({ value, label: value, disabled: value === "owner" && principalKind === "group" }))} />
<TextField label="Capability allow" value={allow} onChange={(event) => setAllow(event.target.value)} description="Опциональные точечные добавления" />
<TextField label="Capability deny" value={deny} onChange={(event) => setDeny(event.target.value)} description="Deny имеет приоритет" />
<Select label="Кому предоставить доступ" value={principalKind} onChange={setPrincipalKind} options={[{ value: "user", label: "Пользователь" }, { value: "group", label: "Группа" }]} />
<TextField label="Идентификатор пользователя или группы" value={principalRef} onChange={(event) => setPrincipalRef(event.target.value)} required />
<Select label="Роль в проекте" value={role} onChange={setRole} options={["viewer", "operator", "engineer", "admin", "owner"].map((value) => ({ value, label: value, disabled: value === "owner" && principalKind === "group" }))} />
<TextField label="Дополнительные разрешения" value={allow} onChange={(event) => setAllow(event.target.value)} description="Опциональные точечные добавления" />
<TextField label="Запреты" value={deny} onChange={(event) => setDeny(event.target.value)} description="Запреты имеют приоритет" />
</FormWindow>;
}
@@ -1635,7 +1602,7 @@ function ConfigurationDialog({ workspace, ...props }: DialogBaseProps & { worksp
setDeviceRef(workspace.devices[0]?.deviceRef ?? "");
}
}, [deviceRef, workspace.devices]);
return <FormWindow {...props} id="configuration-form" title="Новая desired configuration" disabled={!deviceRef} submit={async () => {
return <FormWindow {...props} id="configuration-form" title="Новая конфигурация" disabled={!deviceRef} submit={async () => {
const parsed = JSON.parse(configuration) as Record<string, unknown>;
const created = await createConfigurationRevision({
projectRef: workspace.project.projectRef,
@@ -1649,10 +1616,10 @@ function ConfigurationDialog({ workspace, ...props }: DialogBaseProps & { worksp
configurationRevisionRef: created.result.configurationRevision.configurationRevisionRef,
});
}}>
<Select label="Device" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} />
<TextAreaField label="Configuration JSON" value={configuration} onChange={(event) => setConfiguration(event.target.value)} required />
<TextAreaField label="Change summary" value={summary} onChange={(event) => setSummary(event.target.value)} />
<p className="device-manager-card-copy">Secret-like keys и значения будут отклонены Core. Сохранение desired не выставляет applied.</p>
<Select label="Устройство" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} />
<TextAreaField label="Параметры JSON" value={configuration} onChange={(event) => setConfiguration(event.target.value)} required />
<TextAreaField label="Описание изменений" value={summary} onChange={(event) => setSummary(event.target.value)} />
<p className="device-manager-card-copy">После сохранения конфигурация ожидает подтверждения устройства.</p>
</FormWindow>;
}
@@ -1713,36 +1680,39 @@ function ControlSection({ title, count, children }: { title: string; count: numb
function ResourceGrid({ children, empty }: { children: ReactNode; empty: string }) {
const hasChildren = Array.isArray(children) ? children.length > 0 : Boolean(children);
return hasChildren ? <div className="device-control-resource-grid">{children}</div> : <div className="device-manager-panel-empty">{empty}</div>;
return hasChildren ? <CanonicalResourceList>{Children.toArray(children).map((child, index) => <li key={isValidElement(child) ? child.key ?? index : index}>{child}</li>)}</CanonicalResourceList> : <div className="device-manager-panel-empty">{empty}</div>;
}
function ResourceCard({ eyebrow, title, description, status, meta, action = null }: { eyebrow: string; title: string; description: string; status: string; meta: string[]; action?: ReactNode }) {
return <SettingsCard eyebrow={eyebrow} title={title} description={description} actions={<><StatusBadge tone={statusTone(status)}>{status}</StatusBadge>{action}</>}>
{meta.length ? <div className="device-manager-capabilities">{meta.map((item) => <StatusBadge key={item}>{item}</StatusBadge>)}</div> : <p className="device-manager-card-copy">Metadata-only projection</p>}
</SettingsCard>;
const [expanded, setExpanded] = useState(false);
return <div className="device-control-disclosure">
<CanonicalResourceRow title={title} description={description} metadata={statusLabel(status)}
status={<StatusBadge variant="indicator" tone={statusTone(status)} aria-label={statusLabel(status)} />} statusPlacement="leading"
actions={<>{action}<IconButton label={`Сведения: ${title}`} aria-expanded={expanded} onClick={() => setExpanded(!expanded)}><Icon name={expanded ? 'chevron-up' : 'chevron-down'} /></IconButton></>} />
{expanded ? <div className="device-control-disclosure__body"><p>{eyebrow}</p>{meta.length ? <ul>{meta.map((item) => <li key={item}>{item}</li>)}</ul> : null}</div> : null}
</div>;
}
function ResourceList({ children, empty }: { children: ReactNode; empty: string }) {
const hasChildren = Array.isArray(children) ? children.length > 0 : Boolean(children);
return hasChildren ? <div className="device-manager-entity-list">{children}</div> : <div className="device-manager-panel-empty">{empty}</div>;
return hasChildren ? <CanonicalResourceList>{Children.toArray(children).map((child, index) => <li key={isValidElement(child) ? child.key ?? index : index}>{child}</li>)}</CanonicalResourceList> : <div className="device-manager-panel-empty">{empty}</div>;
}
function ResourceRow({ title, description, status, trailing }: { title: string; description: string; status: string; trailing: ReactNode }) {
return <GlassSurface className="device-manager-entity device-control-row" padding="md" tone="soft">
<span className="device-manager-entity__icon"><Icon name="circle" /></span>
<span className="device-manager-entity__body"><strong>{title}</strong><small>{description}</small></span>
<span className="device-control-row__status"><StatusBadge tone={statusTone(status)}>{status}</StatusBadge>{typeof trailing === "string" ? <small>{trailing}</small> : trailing}</span>
</GlassSurface>;
}
function PolicyCard({ label, value }: { label: string; value: string }) {
return <GlassSurface padding="md" tone="soft"><small>{label}</small><strong>{value}</strong></GlassSurface>;
return <CanonicalResourceRow title={title} description={description}
status={<StatusBadge variant="indicator" tone={statusTone(status)} aria-label={statusLabel(status)} title={statusLabel(status)} />} statusPlacement="leading"
metadata={[statusLabel(status), typeof trailing === "string" ? trailing : null].filter(Boolean).join(" · ")}
actions={typeof trailing === "string" ? undefined : trailing} />;
}
function commaList(value: string) {
return [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))].sort();
}
function statusLabel(status: string) {
return ({ active: 'Активно', accepted: 'Принято', online: 'На связи', verified: 'Подтверждено', applied: 'Применено', recorded: 'Записано', immutable: 'Сохранено', absent: 'Не обнаружено', failed: 'Ошибка', rejected: 'Отклонено', revoked: 'Отозвано', retired: 'В архиве', connecting: 'Подключение', draft: 'Черновик', provisioning: 'Подготовка', pending: 'Ожидание', pending_external_approval: 'Ожидает подтверждения', unknown: 'Нет данных', unobserved: 'Нет наблюдений', disabled: 'Отключено' } as Record<string, string>)[status] || status;
}
function statusTone(status: string): "neutral" | "success" | "warning" | "danger" {
if (["active", "accepted", "online", "verified", "applied", "recorded", "immutable"].includes(status)) return "success";
if (["absent", "failed", "rejected", "revoked", "retired"].includes(status)) return "danger";
+28 -96
View File
@@ -1,10 +1,10 @@
import { useEffect, useMemo, useRef, useState } from "react";
import {
Button,
FeatureSettingsWindow,
ConfirmationModal,
ResourceList,
ResourceRow,
GlassSurface,
Icon,
IconButton,
Select,
@@ -31,6 +31,8 @@ import type {
SessionView,
} from "./types";
import { B2TrackerSettings } from "./b2/B2TrackerSettings";
import type { TrackerRef } from "./b2/tracker";
import { useB2Inventory } from "./b2/useB2Inventory";
export type DeviceInventoryDetailState = {
@@ -39,52 +41,6 @@ export type DeviceInventoryDetailState = {
editing: boolean;
};
export function DeviceDetailHeaderTools({
device,
detail,
canEdit,
onDetailChange,
}: {
device: DeviceView;
detail: DeviceInventoryDetailState;
canEdit: boolean;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
const catalog = getDeviceProfileCatalog(device.modelProfileRef);
const activeSection = catalog.sections.find((section) => section.id === detail.sectionId)
?? catalog.sections[0];
return (
<div className="device-detail-header-tools">
<Select
className="device-detail-section-select"
label="Раздел устройства"
value={activeSection?.id ?? catalog.sections[0]?.id ?? "passport"}
options={catalog.sections.map((section) => ({
value: section.id,
label: section.label,
}))}
onChange={(sectionId) => onDetailChange({ ...detail, sectionId })}
placement="bottom-end"
minMenuWidth={320}
menuWidth="anchor"
variant="split"
/>
<IconButton
label={detail.editing ? "Завершить редактирование" : "Редактировать устройство"}
disabled={!canEdit}
data-active={detail.editing || undefined}
onClick={() => onDetailChange({
...detail,
editing: !detail.editing,
})}
>
<Icon name="edit" size={17} />
</IconButton>
</div>
);
}
export function DeviceInventoryView({
workspace,
canClaim,
@@ -106,6 +62,7 @@ export function DeviceInventoryView({
onError: (reason: unknown) => void;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
const [tracker, setTracker] = useState<{ device: TrackerRef; projectRef: string; section: string } | null>(null);
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const [typeFilter, setTypeFilter] = useState("all");
const [archiveTarget, setArchiveTarget] = useState<DeviceView | null>(null);
@@ -155,27 +112,15 @@ export function DeviceInventoryView({
return () => window.clearInterval(timer);
}, [detail?.deviceRef, onError, onPoll]);
if (selectedDevice && detail) {
return (
<DeviceDetailView
device={selectedDevice}
detail={detail}
workspace={workspace}
canConfigure={canConfigure}
canManageProject={canManageProject}
onDetailChange={onDetailChange}
onSaved={onPoll}
onError={onError}
onBack={() => onDetailChange(null)}
/>
);
}
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">
{tracker && tracker.projectRef===workspace.project.projectRef ? <B2TrackerSettings key={`${tracker.projectRef}:${tracker.device.id}`} projectRef={tracker.projectRef} device={tracker.device} initialSection={tracker.section} onClose={()=>setTracker(null)} onError={onError} onChanged={onPoll} canConfigure={canConfigure} canCommand={workspace.project.access.capabilities.includes('command.dispatch')} /> : null}
{selectedDevice && detail ? <DeviceDetailView key={selectedDevice.deviceRef} device={selectedDevice} detail={detail} workspace={workspace}
canConfigure={canConfigure} canManageProject={canManageProject} onDetailChange={onDetailChange} onSaved={onPoll} onError={onError} onBack={() => onDetailChange(null)} /> : null}
<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);
@@ -220,15 +165,15 @@ export function DeviceInventoryView({
{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>)}
actions={<><IconButton label={`Команды: ${device.name || 'ARNavi B2'}`} onClick={()=>setTracker({device,projectRef:workspace.project.projectRef,section:'commands'})}><Icon name="terminal" /></IconButton><IconButton label={`Настройки: ${device.name || 'ARNavi B2'}`} onClick={()=>setTracker({device,projectRef:workspace.project.projectRef,section:'identity'})}><Icon name="settings" /></IconButton></>} /></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>
actions={<><IconButton label={`Настройки ${device.displayName}`} onClick={() => onDetailChange({ deviceRef: device.deviceRef, sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? 'passport', editing: false })}><Icon name="settings" /></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 !== 'pending' && !deviceRows.length && !remoteRows.length ? <div className="device-manager-empty device-inventory__empty"><Icon name="inbox" size={24} /><h3>{!b2.data && !b2.error ? 'Загрузка устройств…' : b2.error || b2.data?.hosts.some((host) => !host.reachable) ? 'Реестр VPS недоступен' : statusFilter === 'archived' ? 'Архив пуст' : count ? 'Нет устройств с таким состоянием' : 'В проекте пока нет устройств'}</h3></div> : null}
{(statusFilter === "pending" || statusFilter === "all" && pendingEnrollments.length > 0) ? (
<section className="device-inventory__pending" aria-label="Ожидают подключения">
@@ -254,9 +199,9 @@ export function DeviceInventoryView({
<p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p>
</SettingsCard>
)) : (
<GlassSurface className="device-manager-panel-empty device-inventory__pending-empty" padding="md" tone="soft">
<div className="device-manager-panel-empty device-inventory__pending-empty">
Нет ожидающих подключений.
</GlassSurface>
</div>
)}
</section>
) : null}
@@ -407,35 +352,21 @@ function DeviceDetailView({
};
return (
<FeatureSettingsWindow open title="Настройки устройства" subtitle={workspace.project.name}
identity={{ title: device.displayName, subtitle: `${catalog.vendor} · ${catalog.model}`, avatarLabel: catalog.vendor.slice(0, 2) }}
sections={catalog.sections.map((section) => ({ id: section.id, label: section.label }))}
activeSection={activeSection.id} onSectionChange={(sectionId) => onDetailChange({ ...detail, sectionId })} onClose={onBack}
headerActions={<><IconButton label="Обновить устройство" disabled={saving} onClick={() => void onSaved().catch(onError)}><Icon name="refresh" /></IconButton>
{(canConfigure || canManageProject) ? <IconButton label={detail.editing ? 'Завершить редактирование' : 'Редактировать устройство'} disabled={saving} onClick={() => onDetailChange({ ...detail, editing: !detail.editing })}><Icon name="edit" /></IconButton> : null}</>}>
<div ref={detailRef} className="device-detail">
<div className="device-detail__header">
<IconButton label="Вернуться к списку устройств" onClick={onBack}>
<Icon name="chevron-left" size={18} />
</IconButton>
<div className="device-detail__identity">
<small>{catalog.vendor} · {catalog.model}</small>
<h2>{device.displayName}</h2>
<p>{identifierDisplayValue || "Идентификатор не назначен"} · {device.modelProfileRef}</p>
</div>
<StatusBadge tone={session?.lifecycleState === "online" ? "success" : "neutral"}>
{session?.lifecycleState === "online" ? "Онлайн" : session?.lifecycleState || device.lifecycleState}
</StatusBadge>
</div>
<div className="device-detail__legend" aria-label="Режимы доступа">
<AccessBadge access="read-only" />
<AccessBadge access="managed" />
<AccessBadge access="protected" />
</div>
<GlassSurface className="device-detail__connection" padding="md" tone="soft">
<div className="device-detail__connection">
<div><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div>
<div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div>
<div><span>Протокол</span><strong>{session?.protocol || profile?.protocol || "Нет данных"}</strong></div>
<div><span>Последняя активность</span><strong>{formatDate(session?.lastSeenAt || device.session?.lastSeenAt)}</strong></div>
<div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div>
<div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div>
</GlassSurface>
</div>
<div className="device-detail__layout">
<section className="device-detail-section">
@@ -465,7 +396,7 @@ function DeviceDetailView({
? draftValues[item.path]
: readPath(context, item.path);
return (
<GlassSurface key={item.key} className="device-detail-field" padding="sm" tone="soft" data-access={access} data-editing={editable || undefined}>
<div key={item.key} className="device-detail-field" data-access={access} data-editing={editable || undefined}>
{editable && item.valueKind === "boolean" ? (
<Switch
checked={Boolean(value)}
@@ -493,7 +424,7 @@ function DeviceDetailView({
{item.description ? <small>{item.description}</small> : null}
</>
)}
</GlassSurface>
</div>
);
})}
</div>
@@ -524,14 +455,15 @@ function DeviceDetailView({
) : null}
<div className="device-detail-section__state">
<span>Desired</span>
<span>Запрошенная конфигурация</span>
<strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong>
<span>Applied</span>
<span>Подтверждена устройством</span>
<strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong>
</div>
</section>
</div>
</div>
</FeatureSettingsWindow>
);
}
@@ -604,12 +536,12 @@ function AccessNotice({
commandTransport: ProjectWorkspace["policies"]["commandTransport"];
}) {
if (access === "read-only") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></div>;
}
if (access === "protected") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></div>;
}
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></div>;
}
function latestSession(workspace: ProjectWorkspace, device: DeviceView): SessionView | null {
+37 -48
View File
@@ -9,6 +9,8 @@ import {
Dropdown,
FeatureSettingsWindow,
GlassSurface,
ResourceList,
ResourceRow,
HeaderNavigation,
HeaderProfile,
HeaderWorkspace,
@@ -56,12 +58,13 @@ import type {
ProjectWorkspace,
} from "./types";
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
import { useB2Inventory } from "./b2/useB2Inventory";
import { capabilityLabel, projectRoleLabel } from "./presentationLabels";
import {
DeviceControlView,
type ControlViewId,
} from "./DeviceControlViews";
import {
DeviceDetailHeaderTools,
DeviceInventoryView,
type DeviceInventoryDetailState,
} from "./DeviceInventoryView";
@@ -99,7 +102,7 @@ const sectionNavigation: Record<PrimarySection, NavigationItem[]> = {
],
infrastructure: [
{ id: "hosts", label: "VPS и хосты", icon: "building", capability: "telemetry.observe" },
{ id: "infrastructure", label: "Edges и маршруты", icon: "globe", capability: "telemetry.observe" },
{ id: "infrastructure", label: "Узлы и маршруты", icon: "globe", capability: "telemetry.observe" },
{ id: "catalog", label: "Модели и адаптеры", icon: "database", capability: "project.read" },
],
management: [
@@ -234,6 +237,7 @@ export function DeviceManagerApp() {
useEffect(() => {
applyNodedcTheme(document.documentElement, {
theme: presentation.environment.theme,
appearance: "mission",
accent: hexToRgb(presentation.environment.accentHex),
});
}, [presentation.environment.accentHex, presentation.environment.theme]);
@@ -348,9 +352,6 @@ export function DeviceManagerApp() {
}
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;
return (
<>
<ApplicationShell
@@ -493,14 +494,6 @@ export function DeviceManagerApp() {
expanded={shell.contentExpanded}
onExpandedChange={shell.setContentExpanded}
onClose={shell.closeView}
headerTools={activeView === "inventory" && selectedInventoryDevice && inventoryDetail ? (
<DeviceDetailHeaderTools
device={selectedInventoryDevice}
detail={inventoryDetail}
canEdit={canConfigure || canManageProject}
onDetailChange={setInventoryDetail}
/>
) : undefined}
utilityActions={[...(activeView === "hosts" && selectedHostRef ? [{
label: "Вернуться к VPS и хостам", icon: "chevron-left" as const, onClick: () => setSelectedHostRef(null),
}] : []), {
@@ -789,16 +782,6 @@ function EnvironmentBackdrop({
);
}
function Metric({ label, value, detail, tone = "neutral" }: { label: string; value: number; detail: string; tone?: "neutral" | "success" | "warning" }) {
return (
<GlassSurface className="device-manager-metric" padding="md" tone="soft">
<span>{label}</span>
<strong>{value}</strong>
<StatusBadge tone={tone}>{detail}</StatusBadge>
</GlassSurface>
);
}
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;
@@ -846,7 +829,7 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
if (view === "collections") return (
<div className="device-manager-stack">
<div className="device-manager-panel-toolbar">
<p>Коллекции группируют устройства для последующих bindings и задач.</p>
<p>Группы устройств проекта.</p>
<Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button>
</div>
<EntityList
@@ -861,16 +844,28 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
/>
</div>
);
return <ProjectOverview key={workspace.project.projectRef} workspace={workspace} />;
}
function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) {
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const [showPermissions, setShowPermissions] = useState(false);
const incomplete = !b2.data || b2.data.hosts.some((host) => !host.reachable);
const deviceCount = incomplete ? null : workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + b2.data!.items.length;
const deviceDetail = !incomplete ? 'В реестре' : (b2.error || b2.data) ? 'Данные VPS недоступны' : 'Загрузка…';
const metrics = [
{ label: 'Устройства', value: deviceCount, detail: deviceDetail },
{ label: 'Ожидают проверки', value: workspace.discoveries.filter((item) => item.lifecycleState === 'quarantine').length, detail: 'Обнаружены' },
{ label: 'Коллекции', value: workspace.collections.length, detail: 'Группы устройств' },
];
return (
<div className="device-manager-overview-grid">
<Metric label="Устройства" value={workspace.devices.length} detail="inventory" />
<Metric label="Quarantine" value={workspace.discoveries.filter((item) => item.lifecycleState === "quarantine").length} detail="safe projection" />
<Metric label="Коллекции" value={workspace.collections.length} detail="bindings ready" />
<SettingsCard title="Права проекта" description={workspace.project.access.projectRole || "read"}>
<div className="device-manager-capabilities">
{workspace.project.access.capabilities.map((capability) => <StatusBadge key={capability}>{capability}</StatusBadge>)}
</div>
</SettingsCard>
<ResourceList>{metrics.map((metric) => <li key={metric.label}><ResourceRow title={metric.label} metadata={metric.detail} status={<StatusBadge>{metric.value ?? '—'}</StatusBadge>} /></li>)}</ResourceList>
<ResourceRow title="Ваш доступ" metadata={projectRoleLabel(workspace.project.access.projectRole || 'read')}
actions={<IconButton label="Права в проекте" aria-expanded={showPermissions} aria-controls="project-permissions" onClick={() => setShowPermissions(!showPermissions)}><Icon name={showPermissions ? 'chevron-up' : 'chevron-down'} /></IconButton>} />
{showPermissions ? <div id="project-permissions"><ResourceList>
{workspace.project.access.capabilities.map((capability) => <li key={capability}><ResourceRow title={capabilityLabel(capability)} /></li>)}
</ResourceList></div> : null}
</div>
);
}
@@ -954,7 +949,7 @@ function ProjectSettingsDialog({ open, workspace, presentation, onClose, onSaved
avatarUrl: iconPreview ?? undefined,
}}
sections={[
{ id: "identity", label: "Идентичность", icon: "profile", group: "Проект" },
{ id: "identity", label: "Основное", icon: "profile", group: "Проект" },
{ id: "media", label: "Медиа", icon: "image", group: "Оформление" },
]}
activeSection={section}
@@ -1253,13 +1248,9 @@ function EnvironmentSettingsDialog({ open, presentation, onClose, onSaved, onErr
function EntityList({ items, empty }: { items: Array<{ id: string; title: string; subtitle: string; status: string; tone: "neutral" | "success" | "warning" }>; empty: string }) {
if (!items.length) return <div className="device-manager-panel-empty">{empty}</div>;
return <div className="device-manager-entity-list">{items.map((item) => (
<GlassSurface key={item.id} className="device-manager-entity" padding="md" tone="soft">
<span className="device-manager-entity__icon"><Icon name="circle" /></span>
<span className="device-manager-entity__body"><strong>{item.title}</strong><small>{item.subtitle}</small></span>
<StatusBadge tone={item.tone}>{item.status}</StatusBadge>
</GlassSurface>
))}</div>;
return <ResourceList>{items.map((item) => <li key={item.id}><ResourceRow
icon={<Icon name="folder" />} title={item.title} description={item.subtitle}
status={<StatusBadge tone={item.tone}>{item.status}</StatusBadge>} /></li>)}</ResourceList>;
}
function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: {
@@ -1299,7 +1290,7 @@ function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated,
await onCreated();
} catch (reason) { onError(reason); } finally { setPending(false); }
};
return <Window open={open} title="Новый Device Project" subtitle={ownerScope?.displayName || "Owner scope недоступен"} onClose={onClose} footer={
return <Window open={open} title="Новый проект" subtitle={ownerScope?.displayName || "Компания недоступна"} onClose={onClose} footer={
<WindowFooterActions><Button variant="ghost" onClick={onClose}>Отмена</Button><Button type="submit" form="device-project-form" variant="primary" disabled={pending || !ownerScope}>{pending ? "Создаём…" : "Создать"}</Button></WindowFooterActions>
}>
<form id="device-project-form" className="device-manager-form" onSubmit={submit}>
@@ -1373,7 +1364,6 @@ function ClaimDialog({ enrollment, project, onClose, onClaimed, onError }: {
<form id="device-claim-form" className="device-manager-form" onSubmit={submit}>
<TextField label="Название устройства" value={name} onChange={(event) => setName(event.target.value)} required maxLength={160} />
<TextField label="Ключ устройства" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<p className="device-manager-card-copy">Claim использует только ссылки на enrollment и discovery. Исходный идентификатор не запрашивается повторно.</p>
</form>
</Window>;
}
@@ -1452,7 +1442,6 @@ function EnrollmentDialog({ open, workspace, onClose, onCreated, onError }: {
<TextField label="Ключ enrollment" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<TextField label="IMEI" value={imei} onChange={(event) => setImei(event.target.value.replace(/\D/g, "").slice(0, 15))} required pattern="[0-9]{15}" inputMode="numeric" autoComplete="off" />
<TextField label="Истекает" type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} description="Опционально. Время будет сохранено в UTC." />
<p className="device-manager-card-copy">IMEI передаётся один раз по HTTPS в Device Control Core. В базе, audit и ответе останутся только HMAC и маска.</p>
</form>
</Window>;
}
@@ -1478,11 +1467,11 @@ function viewTitle(view: ViewId) {
collections: "Коллекции",
catalog: "Модели и адаптеры",
hosts: "VPS и хосты",
infrastructure: "Edges и маршруты",
sessions: "Gateway sessions",
bindings: "Data bindings",
commands: "Command ledger",
audit: "Immutable audit",
infrastructure: "Узлы и маршруты",
sessions: "Подключения устройств",
bindings: "Связи с Foundry",
commands: "Команды",
audit: "Аудит",
access: "Доступ к проекту",
settings: "Настройки и конфигурации",
})[view];
+72
View File
@@ -0,0 +1,72 @@
import { useRef, useState } from 'react';
import { Button, Icon, Select, SettingsCard, TextAreaField, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
import { b2Request } from './api';
import release from './installer-release.json';
import './b2.css';
const installCommand = `sudo python3 ${release.filename} --device-core`;
const keyCommand = 'sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection';
export function B2AddHost({ open, projectRef, onClose, onCreated, onError }: {
open: boolean; projectRef: string; onClose: () => void; onCreated: () => Promise<void>; onError: (error: unknown) => void;
}) {
const [name, setName] = useState('ARNavi VPS'), [connection, setConnection] = useState('');
const [pending, setPending] = useState(false);
const [downloading, setDownloading] = useState(false);
const fileInput = useRef<HTMLInputElement>(null);
async function downloadInstaller() {
setDownloading(true);
try {
const response = await fetch(`/installers/${release.filename}`, { credentials: 'same-origin', signal: AbortSignal.timeout(45000) });
if (!response.ok) throw new Error('Не удалось скачать установщик. Проверьте вход в Device Core и повторите.');
const bytes = await response.arrayBuffer();
const digest = await crypto.subtle.digest('SHA-256', bytes);
const sha256 = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
if (bytes.byteLength !== release.bytes || sha256 !== release.sha256) throw new Error('Загруженный файл не прошёл проверку. Повторите скачивание.');
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
const link = document.createElement('a'); link.href = url; link.download = release.filename;
document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (error) {
onError(error instanceof Error && ['TimeoutError', 'AbortError'].includes(error.name)
? new Error('Сервер не успел передать установщик. Повторите скачивание.') : error);
} finally { setDownloading(false); }
}
return <Window open={open} title="Добавить VPS" size="lg" onClose={onClose} footer={
<WindowFooterActions><Button onClick={onClose}>Отмена</Button><Button type="submit" form="b2-add-vps" loading={pending} disabled={pending || !name.trim() || !connection.trim()}>Подключить VPS</Button></WindowFooterActions>
}>
<form id="b2-add-vps" className="b2-settings" onSubmit={async (event) => {
event.preventDefault(); if (pending) return;
setPending(true);
try {
await b2Request(projectRef, '', 'register-host', { name: name.trim(), connection });
setConnection(''); await onCreated();
} catch (error) { onError(error); } finally { setPending(false); }
}}>
<Select label="Поддерживаемый VPS" value="arnavi" onChange={() => undefined} options={[{ value: 'arnavi', label: 'ARNavi VPS' }]} />
<div className="b2-onboarding-grid">
<SettingsCard title="1. Установить сервер" description={`ARNavi VPS ${release.version} · Ubuntu Server 24.04 LTS · x86-64`}>
<div className="b2-settings">
<div className="b2-actions"><Button disabled={downloading} loading={downloading} onClick={downloadInstaller}><Icon name="download" />Скачать установщик</Button></div>
<p>Перенесите файл на новый VPS. В его терминале выполните команду и укажите публичный IP или домен.</p>
<TextAreaField label="Установка на VPS" rows={2} readOnly value={installCommand} />
<p>Порты сервера: 19443/TCP для API и 9922/TCP для трекеров. Ключ администратора Device Core создаётся при первой установке.</p>
<TextAreaField label="Получить ключ подключения на VPS" rows={2} readOnly value={keyCommand} />
<p>Скопируйте полученный JSON в блок подключения или загрузите сохранённый файл.</p>
<p className="b2-key-id">SHA-256 установщика: {release.sha256}</p>
</div>
</SettingsCard>
<SettingsCard title="2. Подключить сервер">
<div className="b2-settings">
<TextField label="Название VPS" value={name} maxLength={160} disabled={pending} required onChange={(event) => setName(event.target.value)} />
<Button disabled={pending} onClick={() => fileInput.current?.click()}><Icon name="upload" />Загрузить ключ сервера</Button>
<input ref={fileInput} type="file" hidden accept=".json,application/json" aria-label="Файл ключа сервера" onChange={async (event) => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return;
try { if (file.size > 16384) throw new Error('Файл ключа слишком большой.'); const text = await file.text(); JSON.parse(text); setConnection(text); }
catch { onError(new Error('Не удалось прочитать JSON ключа сервера.')); }
}} />
<TextAreaField label="Ключ администратора VPS · JSON" value={connection} disabled={pending} rows={4} autoComplete="off" spellCheck={false} maxLength={16384} required onChange={(event) => setConnection(event.target.value)} />
</div>
</SettingsCard>
</div>
</form>
</Window>;
}
+112 -81
View File
@@ -1,12 +1,11 @@
import { useEffect, useRef, useState } from 'react';
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, WindowFooterActions, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, 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 { b2Request, type B2Status, type B2Application } from './api';
import './b2.css';
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;
@@ -15,119 +14,151 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
const [section, setSection] = useState<Section>('contours');
const [status, setStatus] = useState<B2Status | null>(null);
const [pending, setPending] = useState('load');
const [connection, setConnection] = useState('');
const [connection, setConnection] = useState(''), [importOpen, setImportOpen] = useState(false);
const connectionFile = useRef<HTMLInputElement>(null);
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('');
const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
const [creating, setCreating] = useState(''), [name, setName] = useState('');
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string } | null>(null);
const [hiddenHistory, setHiddenHistory] = useState<string[]>([]);
const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null);
const [credentialRows, setCredentialRows] = useState<string[]>([]);
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
const request = <T,>(action: string, data: Record<string, unknown> = {}) => b2Request<T>(project.projectRef, host.hostRef, action, data);
const request = <T,>(action: string, data: Record<string, unknown> = {}, requestId?: string) => b2Request<T>(project.projectRef, host.hostRef, action, data, requestId);
const refresh = () => request<B2Status>('status').then(setStatus);
useEffect(() => {
let active = true;
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
if (!active) return;
setStatus(value); if (!value.connected) setSection('connection');
setStatus(value); if (!value.connected) { setSection('connection'); setImportOpen(true); }
setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef));
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
return () => { active = false; };
}, [host.hostRef, project.projectRef]);
async function run(action: string, data: Record<string, unknown> = {}) {
async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) {
setPending(action);
try {
const result = await request<{ connection?: unknown; id?: string }>(action, data);
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2));
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.
const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string }>(action, data, requestId);
if (result.connection) {
const { integration_id: applicationId, client_id: clientId } = result.connection;
setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) });
setKeyRows((rows) => [...new Set([...rows, applicationId])]);
setCredentialRows((rows) => [...new Set([...rows, clientId])]);
}
if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null);
if (action === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null);
if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); }
setCreating(''); setName(''); setCreationIntent(null);
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
return true;
} catch (error) { onError(error); return false; } finally { setPending(''); }
} catch (error) { onError(error); await refresh().catch(() => undefined); return false; } finally { setPending(''); }
}
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); }
};
const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id];
function downloadIssuedKey() {
const url = URL.createObjectURL(new Blob([issued + '\n'], { type: 'application/json' }));
if (!issued) return;
const url = URL.createObjectURL(new Blob([issued.value + '\n'], { type: 'application/json' }));
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);
}
function applicationRow(app: B2Application) {
const legacy = app.key === 'legacy-mission-core';
const open = keyRows.includes(app.id), active = app.credentials.some((item) => item.enabled);
return <li key={app.id} className="b2-disclosure">
<ResourceRow title={app.name} metadata={legacy ? 'Подключение Mission Core · v1' : active ? 'Ключ выдан' : 'Нет действующего ключа'}
actions={<>
{open && !legacy ? <>
<IconButton label={`История ключей ${app.name}`} aria-pressed={!hiddenHistory.includes(app.id)} onClick={() => setHiddenHistory(toggle(hiddenHistory, app.id))}><Icon name={hiddenHistory.includes(app.id) ? 'eye-off' : 'eye'} /></IconButton>
{canManage ? <>
<IconButton label={`${active ? 'Перевыпустить' : 'Выдать'} ключ ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: active }, text: active ? `Перевыпустить ключ «${app.name}»? Прежний ключ перестанет работать.` : `Выдать ключ «${app.name}»?` })}><Icon name="plus" /></IconButton>
<IconButton label={`Удалить приложение ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'application-delete', fields: { integrationId: app.id }, text: `Удалить «${app.name}» со всеми ключами и связями с контурами на этом VPS? Доступ приложения прекратится. Устройства, данные контуров и другие приложения сохранятся.` })}><Icon name="trash" /></IconButton>
</> : null}
</> : null}
<IconButton label={`Ключи ${app.name}`} aria-expanded={open} aria-controls={`keys-${app.id}`} onClick={() => setKeyRows(toggle(keyRows, app.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>
</>} />
{open ? <div id={`keys-${app.id}`} className="b2-disclosure__body">
{legacy ? <>
<dl className="b2-tracker-facts"><dt>Тип подключения</dt><dd>Прямая привязка Mission Core</dd><dt>ID приложения</dt><dd>{app.id}</dd></dl>
<p>Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.</p>
</> : <>
<ResourceList>{app.credentials.filter((item) => item.enabled || !hiddenHistory.includes(app.id)).map((item) => {
const keyOpen = credentialRows.includes(item.client_id);
const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null;
return <li key={item.client_id} className="b2-disclosure">
<ResourceRow title={`Ключ · …${item.client_id.slice(-8)}`} status={<StatusBadge tone={item.enabled ? 'success' : 'neutral'}>{item.enabled ? 'Действует' : 'Отозван'}</StatusBadge>}
actions={<IconButton label={`Сведения ключа ${item.client_id}`} aria-expanded={keyOpen} aria-controls={`credential-${item.client_id}`} onClick={() => setCredentialRows(toggle(credentialRows, item.client_id))}><Icon name={keyOpen ? 'chevron-up' : 'chevron-down'} /></IconButton>} />
{keyOpen ? <div id={`credential-${item.client_id}`} className="b2-disclosure__body">
<dl className="b2-tracker-facts"><dt>ID для сверки</dt><dd><code className="b2-key-id">{item.client_id}</code></dd><dt>VPS</dt><dd>{status?.endpoint}</dd></dl>
{secret ? <SettingsCard title="Ключ подключения приложения" description="Импортируйте файл в приложение с поддержкой ARNavi API v2. Секрет показывается один раз."><div className="b2-settings">
<TextAreaField label="Файл подключения" value={secret.value} readOnly rows={4} />
<div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(secret.value).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued(null)}>Скрыть секрет</Button></div>
</div></SettingsCard> : <p>Секрет скрыт. ID ключа можно сверить с полем client_id в сохранённом файле подключения.</p>}
{item.enabled && canManage ? <div className="b2-actions"><Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: item.client_id }, text: `Отозвать ключ «${app.name}»?` })}>Отозвать ключ</Button></div> : null}
</div> : null}
</li>;
})}</ResourceList>
{!app.credentials.length ? <p>Ключи ещё не выданы</p> : null}
</>}
</div> : null}
</li>;
}
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 }]}
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 () => {
sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]}
activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
}}><Icon name="refresh" /></IconButton>
</WindowFooterActions>}>
}}><Icon name="refresh" /></IconButton>}>
<div className="b2-settings" aria-busy={busy}>
{section === 'connection' ? <>
<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) => {
<ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>}
actions={<IconButton label="Импортировать ключ доступа Device Core" aria-expanded={importOpen} onClick={() => setImportOpen(!importOpen)}><Icon name="key" /></IconButton>} />
{importOpen ? <SettingsCard title="Доступ Device Core к VPS" description="Файл доступа выдаёт администратор этого VPS."><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(); const text = await file.text(); JSON.parse(text); setConnection(text); }
catch { onError(new Error('Не удалось прочитать файл ключа VPS.')); } finally { setPending(''); }
catch { onError(new Error('Не удалось прочитать файл доступа.')); } 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>
<TextAreaField label="Содержимое файла доступа" value={connection} autoComplete="off" spellCheck={false} onChange={(event) => setConnection(event.target.value)} rows={4} />
<div className="b2-actions"><Button disabled={busy} onClick={() => { setImportOpen(false); setConnection(''); }}>Отмена</Button><Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>{status?.connected ? 'Обновить доступ Device Core' : 'Подключить Device Core'}</Button></div>
</div></SettingsCard> : null}
</> : null}
{section === 'contours' ? <>
<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">
{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> : 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>{pending === 'load' ? 'Загрузка контуров…' : status ? 'Контуров пока нет' : 'Контуры недоступны'}</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>
{section === 'contours' ? <ResourceList>{projects.map((item) => {
const links = (status?.links || []).filter((link) => link.projectRef === item.projectRef);
const linked = links.length > 0, open = expanded.includes(item.projectRef);
const apps = (status?.applications || []).filter((app) => app.authority !== 'host' && links.some((link) => app.grants[link.contourId]));
const available = (status?.contours || []).filter((contour) => !status?.links?.some((link) => link.contourId === contour.id));
return <li key={item.projectRef} className="b2-disclosure">
<ResourceRow title={item.name} metadata={linked ? 'Контур VPS связан с проектом' : 'Проект Device Core'}
actions={<>
{open && linked && canManage ? <IconButton label={`Добавить приложение в ${item.name}`} disabled={busy} onClick={() => { setCreating(item.projectRef); setName(''); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : null}
<IconButton label={`Контур ${item.name}`} aria-expanded={open} aria-controls={`contour-${item.projectRef}`} onClick={() => setExpanded(toggle(expanded, item.projectRef))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>
</>} />
{open ? <div id={`contour-${item.projectRef}`} className="b2-disclosure__body">
{!linked ? <>
{canManage ? <Button disabled={busy} loading={pending === 'project-connect'} onClick={() => void run('project-connect', { targetProjectRef: item.projectRef })}>Подключить проект к VPS</Button> : null}
{available.length ? <Select label="Связать с существующим контуром" value="" options={[{ value: '', label: 'Выбрать контур VPS' }, ...available.map((c) => ({ value: c.id, label: c.name }))]} onChange={(contourId) => { if (contourId) void run('link', { contourId, targetProjectRef: item.projectRef }); }} disabled={busy} /> : null}
</> : <>
{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>
<div className="b2-section-heading"><strong>Приложения и ключи</strong></div>
<ResourceList>{apps.map(applicationRow)}</ResourceList>
{!apps.length && creating !== item.projectRef ? <p>Ключи приложений ещё не выданы</p> : null}
{creating === item.projectRef ? <div className="b2-settings">
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={(event) => setName(event.target.value)} />
<div className="b2-actions"><Button disabled={busy} onClick={() => { setCreating(''); setCreationIntent(null); }}>Отмена</Button><Button loading={pending === 'application-connect'} disabled={busy || !name.trim()} onClick={() => {
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim() };
setCreationIntent(intent);
void run('application-connect', { name: intent.name, contourId: links[0].contourId }, intent.id);
}}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div>
</div> : null}
</>}
</> : null}
</div> : null}
</li>;
})}</ResourceList> : 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={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Ключ приложения'} description={confirm?.text} confirmLabel={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Подтвердить'} cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && !busy && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
</>;
}
@@ -0,0 +1,144 @@
import { useEffect, useRef, useState } from 'react';
import { Button, FeatureSettingsWindow, Icon, IconButton, ResourceList, ResourceRow, Select, SettingsCard, StatusBadge, Switch, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
import { trackerRequest, newIntent, operationName, stateName, operationTone, formatTime, type TrackerRef, type TrackerState, type Policy, type Operation } from './tracker';
import { B2RequestError } from './api';
import './b2.css';
type Props = { projectRef:string;device:TrackerRef;initialSection?:string;onClose:()=>void;onError:(error:unknown)=>void;onChanged:()=>Promise<void>;canConfigure:boolean;canCommand:boolean };
export function B2TrackerSettings({projectRef,device,initialSection='identity',onClose,onError,onChanged,canConfigure,canCommand}:Props) {
const [section,setSection]=useState(initialSection==='commands'?'commands':'identity');
const [data,setData]=useState<TrackerState|null>(null), [name,setName]=useState(device.name);
const [policy,setPolicy]=useState<Policy>({parameters:{},connectivity:{mode:'preserve'}});
const [profile,setProfile]=useState(''),[profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false);
const [busy,setBusy]=useState('load'),[dirty,setDirty]=useState(false),[commandsOpen,setCommandsOpen]=useState(initialSection==='commands');
const [bootstrapFirmware,setBootstrapFirmware]=useState(''),[bootstrapPassword,setBootstrapPassword]=useState('');
const profileIntent=useRef<Record<string,unknown>|null>(null);
const [latest,setLatest]=useState<Operation|null>(null);
const request=<T,>(body:Record<string,unknown>)=>trackerRequest<T>(projectRef,device,body);
const alive=useRef(true), intent=useRef<{action:string;request:Record<string,unknown>}|null>(null);
const file=useRef<HTMLInputElement>(null);
useEffect(()=>{
alive.current=true;
request<TrackerState>({action:'state'}).then(value=>{if(alive.current){setData(value);setLatest(value.latest_operation);setName(value.name);setPolicy(value.policy);}}).catch(onError).finally(()=>{if(alive.current)setBusy('');});
return()=>{alive.current=false;};
},[device.id,projectRef]);
async function refresh() { const next=await request<TrackerState>({action:'state'}); if(alive.current){setData(next);setLatest(next.latest_operation);} return next; }
useEffect(()=>{
if(!latest || !['queued','dispatched'].includes(latest.state))return;
let active=true;
const timer=setTimeout(async()=>{try {const result=await request<{items:Operation[]}>({action:'journal'});const item=result.items.find(row=>row.id===latest.id);if(active&&item){setLatest(item);if(!['queued','dispatched'].includes(item.state))await refresh();}}catch(error){if(active)onError(error);}},3000);
return()=>{active=false;clearTimeout(timer);};
},[latest]);
const edit=(value:Policy)=>{setPolicy(value);setDirty(true);};
async function run(label:string,work:()=>Promise<void>) {setBusy(label);try{await work();}catch(error){onError(error);}finally{if(alive.current)setBusy('');}}
async function save() {
if(!data)return 0;
const result=await request<{revision:number}>({action:'save',revision:data.revision,name,policy});
setData({...data,revision:result.revision,name,policy});setDirty(false);await onChanged();return result.revision;
}
async function operation(action:'read'|'apply') {
if(!data)return;
const pending=intent.current;
if(pending && pending.action!==action)throw new Error('Сначала уточните результат предыдущей отправки.');
if(!pending){
const revision=action==='apply'&&dirty?await save():data.revision;
intent.current={action,request:{action,id:newIntent(),...(action==='apply'?{revision,expected_sha256:data.observed?.sha256}:!data.observed?{bootstrap:{firmware:bootstrapFirmware,password:bootstrapPassword}}:{})}};
}
try {const result=await request<Operation>(intent.current!.request);intent.current=null;setBootstrapPassword('');setLatest(result);} catch(error) {if(error instanceof B2RequestError&&error.rejected)intent.current=null;throw error;}
}
const groupNames=[...new Set(data?.fields.map(field=>field.group)||[])];
const pending=Boolean(latest&&['queued','dispatched'].includes(latest.state));
const disabled=Boolean(busy)||pending||!canConfigure;
const connected=Boolean(data?.last_seen_at && Date.now()/1000-data.last_seen_at<120);
async function uploadFirmware(value:File) {
if(!/\.dfw$/i.test(value.name)||value.size>4*1024*1024||!value.size)throw new Error('Выберите непустой файл .dfw до 4 МБ.');
const bytes=new Uint8Array(await value.arrayBuffer());
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),n=>n.toString(16).padStart(2,'0')).join('');
for(let offset=0;offset<bytes.length;offset+=24576){const chunk=btoa(String.fromCharCode(...bytes.slice(offset,offset+24576)));await request({action:'firmware-upload',digest,filename:value.name,size:bytes.length,offset,chunk});}
await refresh();
}
async function downloadFirmware(digest:string) {
const chunks:Uint8Array<ArrayBuffer>[]=[];let offset=0,size=1,filename='firmware.dfw';
while(offset<size){const result=await request<{chunk:string;size:number;filename:string}>({action:'firmware-download',digest,offset});size=result.size;filename=result.filename;const bytes=Uint8Array.from(atob(result.chunk),c=>c.charCodeAt(0));if(!bytes.length)throw new Error('Неполный файл прошивки');chunks.push(bytes);offset+=bytes.length;}
const blob=new Blob(chunks);const actual=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await blob.arrayBuffer())),n=>n.toString(16).padStart(2,'0')).join('');
if(actual!==digest)throw new Error('Контрольная сумма файла не совпала');
const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
return <>
<FeatureSettingsWindow open={!profileOpen&&!commandsOpen} title="Настройки устройства" subtitle={`ARNavi B2 · ${device.number}`}
identity={{title:'ARNavi B2',subtitle:`IMEI ${device.identifier.masked}`,avatarLabel:'AR'}}
sections={[{id:'identity',label:'Устройство и проект'},{id:'connection',label:'Сервер и связь'},{id:'commands',label:'Команды'},{id:'firmware',label:'Прошивка'},...groupNames.map((group,index)=>({id:group,label:group,group:index===0?'Параметры профиля':undefined}))]}
activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={<IconButton label="Обновить сведения о трекере" disabled={Boolean(busy)} loading={busy==='refresh'} onClick={()=>void run('refresh',async()=>{await refresh();})}><Icon name="refresh" /></IconButton>}
footer={section!=='commands'&&section!=='firmware'?<WindowFooterActions><Button disabled={disabled||!dirty||!data} loading={busy==='save'} onClick={()=>void run('save',async()=>{await save();})}>Сохранить настройки</Button><Button disabled={disabled||!data} onClick={()=>{profileIntent.current=null;setProfileName('');setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>:undefined}>
<div className="b2-tracker-form" aria-busy={Boolean(busy)}>
<StatusBadge tone={connected?'success':'neutral'}>{connected?'Передаёт данные на VPS':data?'Нет свежих данных':'Загрузка…'}</StatusBadge>
{data&&section!=='commands'&&section!=='firmware'?<SettingsCard title="Настройки через VPS">
<div className="b2-tracker-form">
<span>{data.observed?`Последнее чтение: ${formatTime(data.observed.received_at)}`:'Настройки трекера ещё не прочитаны'}</span>
{latest?<StatusBadge tone={operationTone(latest.state)}>{stateName(latest.state)}</StatusBadge>:null}{pending?<span>Задание сохранено на VPS. Окно можно закрыть.</span>:null}
<Button disabled={Boolean(busy)||pending||!canConfigure||!canCommand||!data.capabilities.configuration} loading={busy==='apply'} onClick={()=>void run('apply',()=>operation('apply'))}>{intent.current?.action==='apply'?'Уточнить отправку':'Отправить через VPS'}</Button>
{!data.observed?<><Select label="Версия прошивки B2" value={bootstrapFirmware} disabled={Boolean(busy)||!canCommand} onChange={setBootstrapFirmware} options={[{value:'',label:'Выберите установленную версию'},{value:'0.01',label:'0.01'},{value:'0.06',label:'0.06'}]} /><TextField label="Пароль конфигурации трекера" type="password" autoComplete="off" maxLength={6} value={bootstrapPassword} disabled={Boolean(busy)||!canCommand} onChange={event=>setBootstrapPassword(event.target.value)} /></>:null}
<Button disabled={Boolean(busy)||pending||!canCommand||(!data.capabilities.configuration&&!intent.current&&(!bootstrapFirmware||!/^\d{6}$/.test(bootstrapPassword)))} loading={busy==='read'} onClick={()=>void run('read',()=>operation('read'))}>{intent.current?.action==='read'?'Уточнить чтение':'Прочитать через VPS'}</Button>
</div>
</SettingsCard>:null}
{section==='identity'&&data?<>
<TextField label="Название" value={name} disabled={disabled} onChange={event=>{setName(event.target.value);setDirty(true);}} />
<Select label="Сохранённый профиль" value={profile} disabled={disabled} options={[{value:'',label:'Без профиля'},...data.profiles.map(item=>({value:item.id,label:item.name}))]} onChange={id=>{setProfile(id);const selected=data.profiles.find(item=>item.id===id);if(selected)edit(structuredClone(selected.policy));}} />
<SettingsCard title="Сведения об устройстве"><dl className="b2-tracker-facts"><dt>Модель</dt><dd>ARNavi B2 · 231</dd><dt>Номер</dt><dd>{data.number}</dd><dt>IMEI</dt><dd>{data.identifier}</dd><dt>Прошивка</dt><dd>{data.firmware||'Не прочитана'}</dd><dt>Последние данные</dt><dd>{formatTime(data.last_seen_at)}</dd></dl></SettingsCard>
</>:null}
{section==='connection'&&data?<>
{[1,2].map(slot=><SettingsCard key={slot} title={`SIM${slot}`} actions={data.modem?.active_sim===slot&&Date.now()/1000-data.modem.measured_at<90?<StatusBadge tone="success">Интернет</StatusBadge>:undefined}>
<div className="b2-tracker-form"><span>{data.sims[String(slot)]?.identifier||'Нет сведений о карте'}</span><dl className="b2-tracker-facts"><dt>Регистрация</dt><dd>{({0:'Не обнаружена',1:'В домашней сети',2:'Поиск сети',3:'Отказ регистрации',4:'Нет сведений',5:'Роуминг'} as Record<number,string>)[data.cellular.status?.sim_states[String(slot)]??4]}</dd><dt>Сигнал</dt><dd>{data.cellular.networks?.[String(slot)]?.signal!=null?`${data.cellular.networks[String(slot)].signal} / 31`:'—'}</dd><dt>Наблюдение</dt><dd>{formatTime(data.cellular.measured_at)}</dd><dt>APN</dt><dd>{(slot===1?data.observed?.apn1:data.observed?.apn2)||'Автоматически'}</dd></dl>
<Select label={`Настройки оператора SIM${slot}`} value={policy.connectivity[slot===1?'preset1':'preset2']||''} disabled={disabled||policy.connectivity.mode==='native'} options={[{value:'',label:'Сохранить или указать APN'},...data.carrier_presets.map(item=>({value:item.id,label:item.label}))]} onChange={preset=>{const connectivity={...policy.connectivity};const key=slot===1?'preset1':'preset2';if(preset)connectivity[key]=preset;else delete connectivity[key];edit({...policy,connectivity});}} />
<TextField label={`APN SIM${slot}`} placeholder="Сохранить текущее значение" value={policy.connectivity[slot===1?'apn1':'apn2']??''} disabled={disabled||policy.connectivity.mode==='native'||Boolean(policy.connectivity[slot===1?'preset1':'preset2'])} onChange={event=>edit({...policy,connectivity:{...policy.connectivity,[slot===1?'apn1':'apn2']:event.target.value}})} />
</div>
</SettingsCard>)}
<Select label="Режим интернета" value={policy.connectivity.mode} disabled={disabled} onChange={mode=>edit({...policy,connectivity:{...policy.connectivity,mode}})} options={[{value:'preserve',label:'Сохранить режим трекера'},{value:'native',label:'Автоматический режим без заданного APN'},{value:'both',label:'Автоматический режим — сохранить APN'},{value:'sim1',label:'Только SIM1'},{value:'sim2',label:'Только SIM2'}]} />
<SettingsCard title="Сервер мониторинга"><div className="b2-tracker-form">
<Switch label="Задать сервер в профиле" checked={Boolean(policy.endpoint)} disabled={disabled} onChange={checked=>edit({...policy,endpoint:checked?{slot:1,host:data.observed?.servers[0]?.host||'',port:data.observed?.servers[0]?.port||9922}:null})} />
{policy.endpoint?<><TextField label="DNS/IP сервера" value={policy.endpoint.host} disabled={disabled} onChange={event=>edit({...policy,endpoint:{...policy.endpoint!,host:event.target.value}})} /><TextField label="Порт" type="number" min={1} max={65535} value={policy.endpoint.port} disabled={disabled} onChange={event=>edit({...policy,endpoint:{...policy.endpoint!,port:Number(event.target.value)}})} /><Select label="Слот сервера" value={String(policy.endpoint.slot)} disabled={disabled} options={[1,3,4].map(slot=>({value:String(slot),label:`Сервер ${slot}`}))} onChange={slot=>edit({...policy,endpoint:{...policy.endpoint!,slot:Number(slot)}})} /></>:null}
<ResourceList>{data.observed?.servers.map(server=><li key={server.slot}><ResourceRow title={`Сервер ${server.slot}`} metadata={`${server.host}:${server.port}`} description={server.slot===2?'Связь с текущим VPS':undefined} /></li>)}</ResourceList>
</div></SettingsCard>
</>:null}
{groupNames.includes(section)&&data?<><span>Пустое поле — сохранить значение трекера.</span>{data.fields.filter(field=>field.group===section).map(field=><TextField key={field.id} label={field.label} hint={`${field.minimum} … ${field.maximum}`} type="number" step={1} min={field.minimum} max={field.maximum} disabled={disabled||!Object.hasOwn(data.observed?.parameters||{},field.id)} placeholder={String(data.observed?.parameters[field.id]??'Недоступно на этой прошивке')} value={policy.parameters[field.id]??''} onChange={event=>{const parameters={...policy.parameters};if(event.target.value==='')delete parameters[field.id];else parameters[field.id]=Number(event.target.value);edit({...policy,parameters});}} />)}</>:null}
{section==='commands'?<SettingsCard title="Команды устройства"><Button onClick={()=>setCommandsOpen(true)}>Открыть консоль команд</Button></SettingsCard>:null}
{section==='firmware'&&data?<><SettingsCard title="Прошивка устройства"><ResourceRow title={`Установлена ${data.firmware||'неизвестная версия'}`} metadata="Архив файлов · установка по сети недоступна" /></SettingsCard>
<SettingsCard title="Архив прошивок" actions={<IconButton label="Добавить прошивку" disabled={disabled} onClick={()=>file.current?.click()}><Icon name="plus" /></IconButton>}>
<input ref={file} type="file" accept=".dfw" hidden onChange={event=>{const selected=event.target.files?.[0];event.target.value='';if(selected)void run('firmware',()=>uploadFirmware(selected));}} />
<ResourceList>{data.firmwares.map(item=><li key={item.sha256}><ResourceRow title={item.filename} metadata={`${item.bytes.toLocaleString('ru-RU')} байт · ${formatTime(item.added_at)}`} description={item.complete?undefined:'Загрузка не завершена — выберите файл повторно'} actions={<IconButton label={`Скачать ${item.filename}`} disabled={!item.complete||Boolean(busy)} onClick={()=>void run('firmware',()=>downloadFirmware(item.sha256))}><Icon name="download" /></IconButton>} /></li>)}</ResourceList>
{!data.firmwares.length?<span>Нет сохранённых файлов</span>:null}
</SettingsCard></>:null}
</div>
</FeatureSettingsWindow>
{commandsOpen?<B2CommandWindow projectRef={projectRef} device={device} data={data} canCommand={canCommand} onClose={()=>setCommandsOpen(false)} onError={onError} />:null}
<Window open={profileOpen} title="Сохранить профиль" size="sm" onClose={()=>setProfileOpen(false)} footer={<WindowFooterActions><Button loading={busy==='profile'} disabled={Boolean(busy)||!profileName.trim()} onClick={()=>void run('profile',async()=>{profileIntent.current ||= {action:'profile-save',id:newIntent(),name:profileName,policy};try{await request(profileIntent.current);profileIntent.current=null;}catch(error){if(error instanceof B2RequestError&&error.rejected)profileIntent.current=null;throw error;}setProfileOpen(false);await refresh();})}>Сохранить профиль</Button></WindowFooterActions>}><TextField label="Название профиля" disabled={Boolean(busy)||Boolean(profileIntent.current)} autoFocus value={profileName} onChange={event=>setProfileName(event.target.value)} /></Window>
</>;
}
const presets=[{id:'position',label:'Запросить координаты',command:{kind:'request-position'}},{id:'restart',label:'Перезапустить B2',command:{kind:'restart'}},...[4,5,6].flatMap(pin=>[...([true,false] as const).map(enabled=>({id:`pin${pin}-${enabled}`,label:`${enabled?'Включить':'Выключить'} выход PIN${pin}`,command:{kind:'set-output',pin,enabled}})),{id:`pin${pin}-pulse`,label:`Импульс PIN${pin} · 5 с`,command:{kind:'pulse-output',pin,seconds:5}}])];
function B2CommandWindow({projectRef,device,data,canCommand,onClose,onError}:{projectRef:string;device:TrackerRef;data:TrackerState|null;canCommand:boolean;onClose:()=>void;onError:(error:unknown)=>void}) {
const [filter,setFilter]=useState('all');
const [selection,setSelection]=useState('position'),[rows,setRows]=useState<Operation[]>([]),[before,setBefore]=useState<number|null>(null),[busy,setBusy]=useState(false),[details,setDetails]=useState<string[]>([]),[history,setHistory]=useState<Record<string,unknown>>({});
const intent=useRef<Record<string,unknown>|null>(null),alive=useRef(true);
const request=<T,>(body:Record<string,unknown>)=>trackerRequest<T>(projectRef,device,body);
async function refresh(append=false) {const result=await request<{items:Operation[];before:number|null}>({action:'journal',...(append&&before?{before}:{})});if(alive.current){setRows(old=>append?[...old,...result.items]:result.items);setBefore(result.before);}}
useEffect(()=>{alive.current=true;void refresh().catch(onError);return()=>{alive.current=false;};},[]);
useEffect(()=>{if(!rows.some(row=>['queued','dispatched'].includes(row.state)))return;const timer=setTimeout(()=>void refresh().catch(onError),3000);return()=>clearTimeout(timer);},[rows]);
const selected=presets.find(item=>item.id===selection)!;
const pin='pin' in selected.command?selected.command.pin:null;
const available=data?.capabilities.configuration&&(!pin||data.observed?.output_modes[String(pin)]===1);
async function send(command:Record<string,unknown>=selected.command) {setBusy(true);try {intent.current ||= {action:'command',id:newIntent(),command};await request(intent.current);intent.current=null;await refresh();}catch(error){if(error instanceof B2RequestError&&error.rejected)intent.current=null;onError(error);}finally{setBusy(false);}}
return <Window open title="Команды устройства" subtitle={`ARNavi B2 · ${device.number}`} size="lg" onClose={onClose} headerActions={<IconButton label="Обновить журнал команд" disabled={busy} onClick={()=>void refresh().catch(onError)}><Icon name="refresh" /></IconButton>}>
<div className="b2-tracker-form">
<SettingsCard title="Отправка команды"><div className="b2-tracker-form"><Select label="Команда" value={selection} disabled={busy||Boolean(intent.current)} options={presets.map(item=>({value:item.id,label:item.label,disabled:'pin' in item.command&&data?.observed?.output_modes[String(item.command.pin)]!==1}))} onChange={setSelection} />
{pin?<span>Подтверждение доставки не определяет положение контактов реле.</span>:null}
<Button loading={busy} disabled={busy||!canCommand||!available} onClick={()=>void send()}>{intent.current?'Уточнить отправку':'Отправить'}</Button>
</div></SettingsCard>
<SettingsCard title="Журнал команд"><Select label="Показать команды" value={filter} onChange={setFilter} options={[{value:'all',label:'Все команды'},{value:'pending',label:'Ожидают результата'},{value:'finished',label:'Завершённые'}]} /><ResourceList>{rows.filter(row=>filter==='all'||(filter==='pending')===['queued','dispatched'].includes(row.state)).map(row=><li key={row.id}><ResourceRow title={operationName(row.kind,row.command)} metadata={formatTime(row.created_at)} status={<StatusBadge tone={operationTone(row.state)}>{stateName(row.state)}</StatusBadge>} actions={<>{canCommand&&row.repeatable&&row.command?<IconButton label={`Повторить ${operationName(row.kind,row.command)}`} disabled={busy||Boolean(intent.current)} onClick={()=>{const preset=presets.find(item=>JSON.stringify(item.command)===JSON.stringify(row.command));if(preset)setSelection(preset.id);void send(row.command);}}><Icon name="refresh" /></IconButton>:null}<IconButton label={`Подробнее ${row.id}`} aria-expanded={details.includes(row.id)} onClick={()=>{setDetails(old=>old.includes(row.id)?old.filter(id=>id!==row.id):[...old,row.id]);void request({action:'attempts',operation:row.id}).then(value=>setHistory(old=>({...old,[row.id]:value}))).catch(onError);}}><Icon name={details.includes(row.id)?'chevron-up':'chevron-down'} /></IconButton>{canCommand&&['queued','dispatched'].includes(row.state)?<IconButton label={`Остановить ${row.id}`} onClick={()=>void request({action:'cancel',operation:row.id,kind:row.kind}).then(()=>refresh()).catch(onError)}><Icon name="close" /></IconButton>:null}</>} />
{details.includes(row.id)?<div className="b2-disclosure__body"><dl className="b2-tracker-facts"><dt>Попытки</dt><dd>{row.attempt_count??0}</dd><dt>Отправлена</dt><dd>{formatTime(row.dispatched_at)}</dd><dt>Ответ</dt><dd>{formatTime(row.received_at||row.delivered_at||row.verified_at)}</dd><dt>Результат</dt><dd>{stateName(row.state)}</dd><dt>ID</dt><dd>{row.id}</dd></dl><AttemptRows value={history[row.id]} onMore={before=>void request<{items:Operation[];next_before:number|null}>({action:'attempts',operation:row.id,before}).then(value=>setHistory(old=>({...old,[row.id]:{...value,items:[...((old[row.id] as {items:Operation[]})?.items||[]),...value.items]}}))).catch(onError)} /></div>:null}
</li>)}</ResourceList>{!rows.length?<span>Команд пока нет</span>:null}{before?<Button onClick={()=>void refresh(true).catch(onError)}>Предыдущие команды</Button>:null}</SettingsCard>
</div>
</Window>;
}
function AttemptRows({value,onMore}:{value:unknown;onMore:(before:number)=>void}) { const page=value as {items?:Operation[];next_before?:number|null}|undefined;return page?.items?.length?<><ResourceList>{page.items.map((item,index)=><li key={item.id||index}><ResourceRow title={`Попытка ${item.number??index+1}`} metadata={formatTime(item.dispatched_at)} status={<StatusBadge tone={operationTone(item.state)}>{stateName(item.state)}</StatusBadge>} /></li>)}</ResourceList>{page.next_before?<Button onClick={()=>onMore(page.next_before!)}>Предыдущие попытки</Button>:null}</>:null; }
+12 -3
View File
@@ -6,8 +6,14 @@ export type B2Status = { connected: boolean; endpoint?: string; authority?: 'hos
links?: Array<{ contourId: string; projectRef: string }> };
export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string };
const messages: Record<string, string> = {
b2_settings_revision_changed: 'Настройки изменились. Обновите сведения о трекере перед отправкой.',
b2_settings_initial_read_required: 'Сначала прочитайте настройки трекера через VPS.',
b2_settings_sim_observation_required: 'Нет свежих данных выбранной SIM. Дождитесь регистрации карты и обновите сведения.',
b2_request_invalid: 'Проверьте параметры: VPS отклонил запрос.',
b2_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.',
b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.',
b2_host_management_required: 'Нужен ключ администратора VPS из установщика. Ключ приложения подходит только для доступа к его контуру.',
b2_host_identity_mismatch: 'Сервер не совпадает с идентификатором в файле подключения.',
b2_host_not_connected: 'Сначала подключите VPS.',
b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.',
b2_key_rejected: 'VPS не принял ключ подключения.',
@@ -20,13 +26,16 @@ const messages: Record<string, string> = {
b2_company_mismatch: 'Выберите проект той же компании.',
device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.',
};
export async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}): Promise<T> {
export class B2RequestError extends Error {
constructor(message: string, public readonly rejected: boolean) { super(message); }
}
export async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}, requestId = crypto.randomUUID().replaceAll('-', '')): Promise<T> {
const response = await fetch('/api/device-manager/b2/infrastructure', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID().replaceAll('-', '') },
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': requestId },
body: JSON.stringify({ projectRef, hostRef, action, ...fields }),
});
const body = await response.json().catch(() => null);
if (!response.ok || body?.ok !== true) throw new Error(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.');
if (!response.ok || body?.ok !== true) throw new B2RequestError(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.', response.status >= 400 && response.status < 500);
return body.result as T;
}
+11
View File
@@ -3,3 +3,14 @@
.b2-path { overflow-wrap: anywhere; }
.b2-actions { display: flex; gap: var(--nodedc-space-2); 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; }
.b2-disclosure { display: grid; gap: var(--nodedc-space-2); }
.b2-disclosure__body { display: grid; gap: var(--nodedc-space-3); padding: var(--nodedc-space-2) var(--nodedc-space-3) var(--nodedc-space-4); }
.b2-section-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-3); font-size: var(--nodedc-font-size-sm); }
.b2-tracker-form { display: grid; min-width: 0; gap: 1rem; font-size: var(--nodedc-font-size-sm); }
.b2-tracker-facts { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr); gap: .65rem 1rem; margin: 0; font-size: var(--nodedc-font-size-sm); }
.b2-tracker-facts dt { color: var(--nodedc-text-muted); }
.b2-tracker-facts dd { margin: 0; overflow-wrap: anywhere; }
.b2-onboarding-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--nodedc-space-4); align-items: start; }
.b2-onboarding-grid > * { min-width: 0; }
@@ -0,0 +1,10 @@
{
"version": "0.2.3",
"filename": "nodedc-arnavi-vps-0.2.3.pyz",
"sha256": "0d52c38d0e8afd7c1d72bb59e01d20328f8ac2cd8bb2abfd50f3d265db4bcaf4",
"bytes": 16126822,
"sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git",
"sourceCommit": "973e994f02176d438e8ff42f17baccc5fddb6184",
"manifestSha256": "b5aa33a08addace744b0ffecc23777fbe56a8d1ea58f6dd59e5161082a6a847a",
"environment": "ubuntu-24.04-amd64"
}
+22
View File
@@ -0,0 +1,22 @@
import { b2Request, type B2Device } from './api';
export type TrackerRef = B2Device & { hostRef: string; hostName: string };
export type Policy = { parameters: Record<string, number>; connectivity: { mode: string; apn1?: string; apn2?: string; preset1?: string; preset2?: string }; endpoint?: { host: string; port: number; slot: number } | null };
export type Operation = { command?:Record<string,unknown>;repeatable?:boolean;number?:number; id: string; kind: string; state: string; runtime_phase?: string; reason?: string; sequence?: number; created_at?: number; received_at?: number; dispatched_at?: number; verified_at?: number; delivered_at?: number; attempt_count?: number; roundtrip_seconds?: number; delivery_seconds?: number; stop_requested?: boolean };
export type TrackerState = { id: string; name: string; number: number; identifier: string; revision: number; firmware: string | null; policy: Policy;
observed: { sha256: string; received_at: number; parameters: Record<string, number>; servers: Array<{slot:number;host:string;port:number}>; apn1:string;apn2:string;internet_mode:string;output_modes:Record<string,number> } | null;
carrier_presets: Array<{id:string;label:string;apn:string}>;
cellular: {measured_at?:number;status?:{sim_states:Record<string,number>};networks?:Record<string,{mcc:number|null;mnc:number;signal:number|null}>};
fields: Array<{id:string;label:string;group:string;minimum:number;maximum:number}>;
profiles: Array<{id:string;name:string;policy:Policy}>;
firmwares: Array<{sha256:string;filename:string;bytes:number;complete:boolean;added_at:number}>;
latest_operation:Operation|null; last_seen_at: number | null; modem: {active_sim:number;measured_at:number} | null; sims: Record<string,{identifier:string;measured_at:number|null}>;
capabilities: {configuration:boolean;firmware_archive:boolean;firmware_install:boolean};
};
export function trackerRequest<T>(projectRef: string, device: TrackerRef, request: Record<string, unknown>) {
return b2Request<T>(projectRef,device.hostRef,'tracker',{contourId:device.contourId,deviceId:device.id,request});
}
export const newIntent = () => crypto.randomUUID().replaceAll('-','');
export const operationName = (kind: string, command?:Record<string,unknown>) => command?.pin ? `${kind==='pulse-output'?'Импульс':command.enabled?'Включить':'Выключить'} PIN${command.pin}${kind==='pulse-output'?` · ${command.seconds} с`:''}` : ({'request-position':'Запросить координаты',restart:'Перезапустить B2','read-configuration':'Прочитать настройки','configure-all':'Применить настройки','select-sim':'Изменить режим SIM','set-output':'Переключить выход','pulse-output':'Импульс выхода'}[kind] || 'Операция B2');
export const stateName = (state: string) => ({queued:'В очереди VPS',dispatched:'Отправлено B2',observed:'Настройки прочитаны',verified:'Настройки проверены',accepted:'Принято B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',sim_selected:'SIM подключена',reconnected:'Связь после перезапуска подтверждена',delivered:'Доставлено',stopped:'Повторы остановлены',cancelled:'Отменено до отправки',rejected:'Отклонено',uncertain:'Результат неизвестен',unconfirmed:'Результат не подтверждён',not_applied:'Не применено',expired:'Попытка завершилась без ответа',failed:'Ошибка'}[state] || 'Неизвестный статус');
export const operationTone = (state:string):'success'|'warning'|'neutral' => ['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral';
export const formatTime = (value?: number | null) => value ? new Date(value*1000).toLocaleString('ru-RU') : '—';
+4 -5
View File
@@ -3,20 +3,19 @@ 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('');
const [snapshot, setSnapshot] = useState<{ projectRef: string; data: B2Inventory | null; error: string } | null>(null);
useEffect(() => {
let active = true, timer: ReturnType<typeof setTimeout>;
async function load() {
try {
const next = await b2Request<B2Inventory>(projectRef, '', 'inventory');
if (active) { setData(next); setError(''); }
if (active) setSnapshot({ projectRef, data: next, error: '' });
} catch (reason) {
if (active) { setData(null); setError(reason instanceof Error ? reason.message : 'VPS недоступен'); }
if (active) setSnapshot({ projectRef, data: null, error: 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 };
return snapshot?.projectRef === projectRef ? snapshot : { data: null, error: '' };
}
@@ -0,0 +1,42 @@
const roles: Record<string, string> = {
owner: 'Владелец', admin: 'Администратор', operator: 'Оператор',
maintainer: 'Сопровождение', viewer: 'Наблюдатель', read: 'Просмотр',
};
export const projectRoleLabel = (role: string) => roles[role] || role;
const capabilities: Record<string, string> = {
'access.manage': 'Управление доступом', 'asset.manage': 'Управление объектами',
'audit.read': 'Просмотр аудита', 'binding.manage': 'Управление связями с Foundry',
'collection.manage': 'Управление коллекциями', 'command.confirm': 'Подтверждение команд',
'command.dispatch': 'Отправка команд', 'command.plan': 'Подготовка команд',
'configuration.manage': 'Изменение настроек устройств', 'configuration.read': 'Просмотр настроек устройств',
'credential.manage': 'Управление ключами', 'device.claim': 'Привязка устройств',
'device.enroll': 'Регистрация устройств', 'device.transfer': 'Перенос устройств',
'infrastructure.manage': 'Изменение инфраструктуры', 'infrastructure.read': 'Просмотр инфраструктуры',
'inventory.read': 'Просмотр реестра', 'observation.write': 'Запись наблюдений',
'project.manage': 'Управление проектом', 'project.read': 'Просмотр проекта',
'route.manage': 'Управление маршрутами', 'telemetry.observe': 'Просмотр телеметрии',
};
export const capabilityLabel = (capability: string) => capabilities[capability] || capability;
const eventObjects: Record<string, string> = {
owner_scope: 'Компания', project: 'Проект', collection: 'Коллекция',
project_grant: 'Доступ к проекту', command: 'Команда', device: 'Устройство',
discovery: 'Обнаруженное устройство', enrollment_intent: 'Регистрация устройства',
device_credential_binding: 'Ключ устройства', device_binding: 'Связь устройства',
device_configuration_revision: 'Версия настроек', device_configuration: 'Настройки устройства',
asset: 'Объект', asset_binding: 'Привязка объекта', edge: 'Узел', route: 'Маршрут',
infrastructure_host: 'VPS', infrastructure_endpoint: 'Точка подключения',
infrastructure_deployment: 'Развёртывание', infrastructure_service_instance: 'Сервис',
health_observation: 'Наблюдение',
};
const eventActions: Record<string, string> = {
created: 'создание', updated: 'изменение', archived: 'архивирование', restored: 'восстановление',
revoked: 'отзыв', claimed: 'привязка', queued: 'добавление в очередь', dispatched: 'отправка',
verified: 'подтверждение', confirmed: 'подтверждение', closed: 'закрытие', recorded: 'запись',
desired_changed: 'сохранение изменений', transferred_in: 'перенос в проект', transferred_out: 'перенос из проекта',
};
export function auditEventLabel(event: string) {
const [object, action] = event.split('.');
return eventObjects[object] && eventActions[action] ? `${eventObjects[object]} · ${eventActions[action]}` : event;
}
+10 -62
View File
@@ -5,7 +5,6 @@
.device-control-toolbar {
align-items: center;
padding: 2px 0 14px;
border-bottom: 1px solid var(--nodedc-glass-outline);
}
.device-control-toolbar > p {
@@ -42,8 +41,8 @@
.device-control-resource-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
gap: var(--nodedc-space-3);
grid-template-columns: minmax(0, 1fr);
}
.device-control-row {
@@ -122,9 +121,7 @@
}
.device-control-form {
max-height: min(62vh, 680px);
overflow-y: auto;
padding-right: 3px;
min-width: 0;
}
.infrastructure-system-workspace {
@@ -142,55 +139,9 @@
.infrastructure-assets-block {
min-width: 0;
border-radius: var(--nodedc-radius-card);
background: var(--infrastructure-panel-soft);
padding: 1rem;
}
.infrastructure-system-workspace .nodedc-status {
min-height: auto;
justify-content: flex-start;
gap: 0.42rem;
border-radius: 0;
background: transparent;
color: var(--nodedc-text-primary);
padding: 0;
font-size: var(--nodedc-font-size-sm);
font-weight: var(--nodedc-font-weight-medium);
}
.infrastructure-system-workspace .nodedc-status::before {
width: 0.42rem;
height: 0.42rem;
flex: 0 0 0.42rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
content: "";
}
.infrastructure-system-workspace .nodedc-status[data-tone="success"],
.infrastructure-system-workspace .nodedc-status[data-tone="warning"],
.infrastructure-system-workspace .nodedc-status[data-tone="danger"],
.infrastructure-system-workspace .nodedc-status[data-tone="accent"] {
background: transparent;
color: var(--nodedc-text-primary);
}
.infrastructure-system-workspace .nodedc-status[data-tone="success"]::before {
background: rgb(var(--nodedc-success-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="warning"]::before {
background: rgb(var(--nodedc-warning-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="danger"]::before {
background: rgb(var(--nodedc-danger-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="accent"]::before {
background: var(--nodedc-text-primary);
}
.infrastructure-eyebrow {
display: block;
color: var(--nodedc-text-muted);
@@ -264,7 +215,6 @@
.host-monitoring-series {
min-width: 0;
border-radius: var(--nodedc-radius-card);
background: var(--infrastructure-panel-soft);
}
.infrastructure-count-card {
@@ -425,7 +375,6 @@
margin: 0;
padding: 0.72rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
}
.infrastructure-host-card__facts > div {
@@ -464,7 +413,6 @@
gap: 0.55rem;
padding: 0.72rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
}
.infrastructure-host-relations > section > header {
@@ -573,7 +521,6 @@
gap: 0.9rem;
padding: 0.72rem 0.8rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
}
.infrastructure-registry-row > div,
@@ -610,7 +557,6 @@
.infrastructure-empty {
padding: 0.8rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
color: var(--nodedc-text-muted);
font-size: 0.65rem;
line-height: 1.5;
@@ -696,7 +642,6 @@
margin: 0;
gap: 0;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
}
.host-monitoring-hardware-facts dl > div {
@@ -1319,7 +1264,6 @@ body {
gap: 0.75rem;
margin-top: 0.45rem;
padding-top: 1rem;
border-top: 1px solid var(--nodedc-glass-border);
}
.device-inventory__section-heading {
@@ -1441,7 +1385,6 @@ body {
align-items: center;
gap: 0.9rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--nodedc-glass-border);
}
.device-detail__identity {
@@ -1604,7 +1547,6 @@ body {
display: flex;
justify-content: flex-end;
gap: 0.55rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem;
}
@@ -1640,7 +1582,6 @@ body {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.35rem 0.7rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem;
color: var(--nodedc-text-secondary);
font-size: 0.65rem;
@@ -1750,3 +1691,10 @@ body {
}
}
/* Domain groups use the panel canvas; shared ResourceRow/SettingsCard own surfaces. */
.device-inventory__empty { min-height: 12rem; }
.device-manager-empty h3 { font-size: var(--nodedc-font-size-md); }
.device-control-disclosure__body { padding: var(--nodedc-space-4); color: var(--nodedc-text-secondary); }
.device-control-disclosure__body p { margin-top: 0; }
+90
View File
@@ -0,0 +1,90 @@
# ARNavi VPS: установка и подключение из Device Core
## Пользовательский путь
«Инфраструктура → VPS и хосты → +» открывает один диалог с выбором
поддерживаемого продукта и двумя последовательными блоками по всей ширине. Сейчас поддерживается ARNavi VPS.
1. Скачать установщик 0.2.3, перенести на новый Ubuntu Server 24.04 LTS x86-64.
2. В терминале **этого VPS** выполнить
`sudo python3 nodedc-arnavi-vps-0.2.3.pyz --device-core`.
Установщик запрашивает публичный IP/домен. Требуются 19443/TCP для API и
9922/TCP для трекеров на VPS; это не порты Synology.
3. В том же терминале выполнить
`sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection`.
Это чтение уже созданного закрытого JSON подключения, а не выпуск ещё одного ключа.
4. Вставить JSON или загрузить его файлом во второй блок Device Core,
указать название и нажать «Подключить VPS».
Сервер проверяет полномочия пользователя, TLS fingerprint, identity VPS и
доступ администратора **до** создания записи. Ключ отдельного приложения
не подходит для регистрации VPS. Повторное подключение того же сервера в
том же проекте использует существующую запись. Секрет сохраняется только
в закрытом хранилище Core, не в журнале аудита.
Установщик в режиме `--device-core` создаёт администратора без фиктивного
Mission Core и без заранее выдуманных контуров. Контуры связываются с уже
существующими проектами Device Core через настройки VPS. Существующий VPS
с прямой привязкой Mission Core этот режим менять отказывается: для него
нужен ранее экспортированный ключ администратора, не повторная установка.
## Ключи приложений
Настройки VPS → Контуры → нужный проект → Приложения и ключи.
Выпущенный JSON появляется внутри соответствующей строки ключа. Его нужно
импортировать в приложение, реализующее ARNavi API v2; он содержит endpoint,
TLS fingerprint и OAuth client credentials. Создание ключа само по себе не
подключает и не запускает другое приложение. Для отдельного приложения
создаётся отдельная интеграция в том же контуре.
Полный секрет доступен один раз. После скрытия/закрытия остаётся `client_id`
для сверки с сохранённым JSON, состояние и отзыв. Перевыпуск явно предупреждает
об отключении предыдущего ключа. Отозванные ключи доступны в истории.
Строка прямой привязки Mission Core v1 раскрывает её тип и ID; это не OAuth
credential и кнопка отзыва ключа v2 не должна притворяться её отключением.
## Инфраструктурный реестр
Для подключённого ARNavi VPS строка содержит настройки, круглую кнопку
мониторинга и раскрытие сведений. «В архив» обратимо скрывает локальную запись,
не удаляет VPS. Ручные действия «Адрес», «Развёртывание», «Сервис» оставлены
для общего инфраструктурного реестра, но не предлагаются в обычном ARNavi
сценарии. Они регистрируют метаданные, не устанавливают ПО: сервис требует
записи развёртывания именно выбранного хоста.
## Происхождение скачиваемого файла
Исходный сервер остаётся в отдельном репозитории
`SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS`, commit
`973e994f02176d438e8ff42f17baccc5fddb6184`. Device Core раздаёт только
неизменяемый официальный установщик из `public/installers`.
Метаданные в `src/b2/installer-release.json`; тест проверяет размер и SHA-256.
Сборка: `scripts/build_vps_host.py` отдельного VPS-репозитория с закреплённым
Hydra 26.2.0 archive. Две сборки дали одинаковый SHA-256:
`0d52c38d0e8afd7c1d72bb59e01d20328f8ac2cd8bb2abfd50f3d265db4bcaf4`.
Размер 16126822 байт, ниже лимита одного файла канонического deploy artifact.
Для обновления скачать/собрать новый проверенный релиз в VPS-репозитории,
опубликовать его commit, заменить asset и metadata вместе и пройти CI.
Нельзя редактировать содержимое PYZ в Device Core или переписывать старый релиз.
307 серверных теста покрывают пустое состояние, отдельный bootstrap,
изоляцию контуров, отказ смены режима и прежнюю привязку. Полная установка
0.2.3 на чистую Ubuntu в этой задаче **не выполнялась**. Действующий VPS
обновляется отдельно штатным plan/apply с сохранением identity и данных. Прохождение тестов не является актом приёмки новой машины.
## Компактные действия и удаление приложения
Плюс добавления приложения находится в строке раскрытого контура. В раскрытой
строке приложения: глаз (история отозванных ключей по умолчанию включена), плюс
(выпуск/перевыпуск), корзина (удаление с подтверждением). JSON ключа остаётся
внутри своей строки. Удаление отзывает все ключи и убирает grants/subscriptions
приложения на VPS. Устройства, данные и остальные приложения сохраняются.
Tombstone и audit предотвращают позднее восстановление старым запросом.
Host-admin и прежняя привязка Mission Core v1 защищены от этой операции.
Вкладка «Сервер» — управляющее подключение Device Core к VPS. «Обновить доступ»
импортирует новый JSON управляющего ключа после его перевыпуска на VPS.
Работающее подключение не требует повторного импорта. Это отдельно от ключей
приложений внутри контуров; обновление доступа не устанавливает ПО на сервер.
+40
View File
@@ -0,0 +1,40 @@
# Device Core: UI and UX contract
Device Core remains a separate application with its own companies, projects,
device registry, infrastructure, access rules and management functions. Mission
Core is the reference for interaction and presentation, not its domain model.
The existing home video and media configuration are preserved.
## Components
Consume the pinned NODEDC_DESIGN_GUIDELINE packages. Use ResourceRow for
registries, FeatureSettingsWindow for entity settings, SettingsCard for coherent
forms, and canonical controls and status indicators. Domain wrappers only arrange
these exports; they must not reproduce their visual styles. Avoid nested canvas
surfaces. Keep refresh beside close in the window header. Expand related items
in place instead of replacing the settings page with a back-navigation stack.
## VPS and projects
Existing Device Core projects are the list shown under a VPS. Connecting a
project requests a contour on that VPS using a stable project-derived identity,
then saves the link. Retries reuse that identity. No second project registry is
created. Explicit linking is available for a pre-existing remote contour.
Applications and their keys expand under their project. Creating an application
requires its human-readable name only. Device Core generates its technical ID;
VPS generates the credential. A lost response retains the same creation request
ID in the open form. The status refresh exposes partially completed issuance;
use explicit reissue when a one-time secret was lost. Key IDs are public IDs,
never secrets. Issued means a credential exists, not that the client is online.
Legacy Mission Core access is visible as a compatible connection.
## Acceptance
- Check all five application sections and their empty, populated and error states.
- Verify project switches retain the selected section while clearing entity state.
- Verify project, host, contour and credential isolation with unauthorized actors.
- Verify inline expansion, keyboard focus, Escape, top refresh and narrow layouts.
- Verify the existing home video/media survives releases.
- Full B2 command/settings parity remains a distinct domain integration task;
a UI release or successful deployment must not be recorded as its completion.
+42
View File
@@ -0,0 +1,42 @@
# Device Core · Mission Core visual reference
Reference inspected in the running Mission Core on 2026-09-30: environment
settings; VPS settings; B2 identity, connection, commands, firmware and every
profile section. The actual application is authoritative for appearance; its
rover domain is not imported into Device Core.
The shared `appearance: "mission"` profile lives in Design Guideline/ui-core.
Device Core applies it on documentElement so portals inherit it. Existing Window,
FeatureSettingsWindow, SettingsCard, ResourceRow, Select, Button and StatusBadge
remain the component source. No application-local replica of the modal is added.
Reference measurements in dark mode: modal rgba(15,15,17,.97), radius28px,
plain avatar, selected navigation rgba(247,248,244,.14), control height46px,
settings-card padding16px, status dot6.72px. The material rim and gradient are
removed from this opt-in profile. Light mode keeps the same neutral hierarchy.
Other applications retain their previous appearance unless opting in.
| Surface | Device Core behavior |
| --- | --- |
| B2 inventory | terminal and gear at right; no redundant registered badge |
| B2 settings | persistent left navigation, identity, connection, commands, firmware,86parameters |
| VPS settings | same window; project contours expand inline; refresh at top |
| Keys | application belongs to expanded project contour; server generates identity |
| Project switch | retained active application section; no foreign project device window |
| Product model | company/project permissions remain Device Core's |
| Overview | existing yellow video retained |
Network settings go through the VPS product API documented in the server repo's
TRACKER_SETTINGS_API.md. The backend checks capability, linked project/contour and
server identity. Unknown/private configuration records and recovery endpoint are
preserved. Saving a portable profile is separate from applying it to a tracker.
The web app has no connection to the operator's local USB. USB provisioning stays
in local Mission Core; new network-reachable devices support initial config read
with their installed firmware and configuration password. Firmware controls match
the reference archive/import/download scope; no network flashing is advertised.
Validation: Device Core TypeScript/production build,286server/application tests,
15B2permission/transport tests; VPS298tests; Mission Core71compatibility tests.
Live deployment and UI acceptance are recorded in Ops MISSIONCOR-86 after release;
these local results are not a production acceptance claim.
+1 -1
View File
@@ -5,7 +5,7 @@
"dependencies": {
"NODEDC_DESIGN_GUIDELINE": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"commit": "1b63366d2e7a911e18a293d30cddb0c95e0ba653"
"commit": "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2"
},
"NODEDC_LAUNCHER": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
@@ -149,7 +149,9 @@ export function createB2Client(input, { fetchImpl } = {}) {
const value = await res.json().catch(() => null);
if (!res.ok) {
if (res.status === 401 || res.status === 403) { token = null; throw b2Error('b2_access_denied', 403); }
if (res.status === 409 && ['settings_revision_changed', 'settings_initial_read_required', 'settings_sim_observation_required'].includes(value?.error)) throw b2Error('b2_' + value.error, 409);
if (res.status === 409) throw b2Error('b2_conflict', 409);
if (res.status === 400) throw b2Error('b2_request_invalid', 400);
throw b2Error('b2_host_request_failed', 502);
}
if (!value || typeof value !== 'object') throw b2Error('b2_response_invalid', 502);
@@ -32,6 +32,66 @@ export class B2Infrastructure {
this.clients.set(source.secret_ref, client);
return client;
}
async verifyConnection(input) {
let value;
try { value = typeof input === 'string' ? JSON.parse(input) : input; }
catch { throw b2Error('b2_connection_invalid'); }
const pkg = connectionPackage(value);
const remote = this.clientFactory(pkg);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const status = await remote.call(pkg.authority === 'host' ? '/v2/management' : '/v2/contours');
if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
return pkg;
}
async saveSource(db, project, pkg) {
const secret = await this.secrets.save(pkg);
const saved = (await db.query(`insert into device_b2_hosts
(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
values($1,$2,$3,$4,$5,$6,$7,$8)
on conflict(owner_scope_id,remote_host_id) do update set
secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now()
where device_b2_hosts.integration_id=excluded.integration_id
and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint
and device_b2_hosts.authority=excluded.authority returning id`,
[randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0];
if (!saved) throw b2Error('b2_connection_identity_conflict', 409);
return saved;
}
async registerHost(actor, input, requestId) {
fields(input, ['connection', 'name']);
const projectId = ref(input.projectRef, 'project');
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
const db = await this.pool.connect();
try {
await db.query('begin');
const project = await findProjectWithCapability(db, actor, projectId, 'infrastructure.manage');
assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
await findProjectWithCapability(db, actor, projectId, 'credential.manage');
// A rejected key never leaves an empty host in the user's registry.
const pkg = await this.verifyConnection(input.connection);
if (pkg.authority !== 'host') throw b2Error('b2_host_management_required', 403);
await db.query('select pg_advisory_xact_lock(hashtextextended($1,0))', [project.owner_scope_id + ':' + pkg.host_id]);
const saved = await this.saveSource(db, project, pkg);
const existing = (await db.query(`select h.host_key from device_b2_host_views v
join device_infrastructure_hosts h on h.id=v.host_id
where v.source_id=$1 and v.project_id=$2`, [saved.id, projectId])).rows[0];
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: input.projectRef, hostKey: existing?.host_key || `b2-${saved.id}`,
displayName: input.name.trim(), providerRef: null, externalRef: pkg.host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
const hostRef = registered.host.hostRef;
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [ref(hostRef, 'host'), projectId, project.owner_scope_id, saved.id]);
await db.query(`insert into device_audit_events(id,event_type,actor_ref,payload,project_id)
values($1,$2,$3,$4::jsonb,$5)`, [randomUUID(), 'b2.register-host', actor.userRef,
JSON.stringify({ projectRef: input.projectRef, hostRef, requestId }), projectId]);
await db.query('commit');
return { connected: true, hostRef, endpoint: pkg.endpoint, authority: pkg.authority };
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
}
async inventory(actor, input) {
fields(input, []);
const projectId = ref(input.projectRef, 'project');
@@ -70,8 +130,44 @@ export class B2Infrastructure {
}));
return { items: results.flatMap((result) => result.items), hosts: results.map((result) => result.host) };
}
async tracker(actor, input) {
fields(input, ['contourId', 'deviceId', 'request']);
const projectId = ref(input.projectRef, 'project'), hostId = ref(input.hostRef, 'host');
const contourId = opaque(input.contourId), deviceId = opaque(input.deviceId);
const request = input.request;
const permissions = {
state: 'configuration.read', journal: 'audit.read', attempts: 'audit.read',
'firmware-download': 'configuration.read', 'firmware-upload': 'configuration.manage',
save: 'configuration.manage', 'profile-save': 'configuration.manage',
read: 'command.dispatch', apply: 'configuration.manage', command: 'command.dispatch', cancel: 'command.dispatch',
};
if (!request || typeof request !== 'object' || !permissions[request.action]) throw b2Error('b2_request_invalid');
const db = await this.pool.connect();
let source;
try {
await db.query('begin');
await findProjectWithCapability(db, actor, projectId, permissions[request.action]);
if (request.action === 'apply') await findProjectWithCapability(db, actor, projectId, 'command.dispatch');
source = (await db.query(`select s.* from device_b2_hosts s
join device_b2_host_views v on v.source_id=s.id
join device_b2_contour_links l on l.source_id=s.id and l.project_id=v.project_id
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
where v.host_id=$1 and v.project_id=$2 and l.contour_id=$3 and h.lifecycle_state='active'`,
[hostId, projectId, contourId])).rows[0];
if (!source) throw b2Error('b2_access_denied', 403);
await db.query('commit');
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
const remote = await this.clientFor(source);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
// VPS checks the device's actual contour as well; a forged device ID cannot
// borrow the host administrator credential from another project.
return remote.call(`/v2/contours/${contourId}/devices/${deviceId}/settings`, request);
}
async execute(actor, input, requestId) {
if (input.action === 'register-host') return this.registerHost(actor, input, requestId);
if (input.action === 'inventory') return this.inventory(actor, input);
if (input.action === 'tracker') return this.tracker(actor, input);
const projectId = ref(input.projectRef, 'project');
const hostId = ref(input.hostRef, 'host');
const action = input.action;
@@ -83,7 +179,7 @@ export class B2Infrastructure {
// Host management can affect all projects of the company. A project-only
// grant must not turn into company-wide administration.
if (action !== 'devices') assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
if (['connect', 'key-issue', 'key-revoke'].includes(action)) {
if (['connect', 'key-issue', 'key-revoke', 'application-connect', 'application-delete'].includes(action)) {
await findProjectWithCapability(db, actor, projectId, 'credential.manage');
}
const host = (await db.query('select id,host_key,display_name,provider_ref from device_infrastructure_hosts where id=$1 and project_id=$2 and lifecycle_state <> $3 for share',
@@ -103,16 +199,7 @@ export class B2Infrastructure {
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const status = pkg.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const secret = await this.secrets.save(pkg);
const saved = (await db.query(`insert into device_b2_hosts
(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
values($1,$2,$3,$4,$5,$6,$7,$8)
on conflict(owner_scope_id,remote_host_id) do update set
secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now()
where device_b2_hosts.integration_id=excluded.integration_id
and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint
and device_b2_hosts.authority=excluded.authority returning id`,
[randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0];
const saved = await this.saveSource(db, project, pkg);
if (!saved) throw b2Error('b2_connection_identity_conflict', 409);
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [hostId, projectId, project.owner_scope_id, saved.id]);
@@ -129,12 +216,21 @@ export class B2Infrastructure {
result = { connected: true, endpoint: source.endpoint, authority: source.authority,
contours: value.contours || value.items, applications: value.applications || [],
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
} else if (action === 'link') {
fields(input, ['contourId', 'targetProjectRef']);
} else if (action === 'link' || action === 'project-connect') {
fields(input, action === 'link' ? ['contourId', 'targetProjectRef'] : ['targetProjectRef']);
const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
const contour = opaque(input.contourId);
let contour;
if (action === 'project-connect') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
const linked = links.filter((link) => link.project_id === targetId);
if (linked.length > 1) throw b2Error('b2_conflict', 409);
// Stable project identity makes a retry recover the same contour.
contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', {
key: 'dc-' + targetId, name: target.name,
})).id;
} else contour = opaque(input.contourId);
const permitted = await remote.call('/v2/contours');
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
const current = links.find((link) => link.contour_id === contour);
@@ -176,6 +272,23 @@ export class B2Infrastructure {
result = await remote.call('/v2/management/applications', {
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
});
} else if (action === 'application-connect') {
fields(input, ['name', 'contourId']);
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
const contour = opaque(input.contourId);
if (!links.some((link) => link.contour_id === contour)) throw b2Error('b2_access_denied', 403);
if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
const app = await remote.call('/v2/management/applications', {
key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: 'manage' },
});
// The VPS reserves issuance before returning a one-time secret. If
// the response is lost, status exposes the app for explicit reissue.
result = { id: app.id, connection: await remote.call('/v2/management/credentials', {
integration_id: app.id, replace: false, request_id: requestId,
}) };
} else if (action === 'application-delete') {
fields(input, ['integrationId']);
result = await remote.call('/v2/management/applications/delete', { integration_id: opaque(input.integrationId) });
} else if (action === 'key-issue') {
fields(input, ['integrationId', 'replace']);
if (typeof input.replace !== 'boolean') throw b2Error('b2_replace_invalid');
@@ -24,7 +24,7 @@ function repository({ role = 'owner', links = [], otherOwner = ownerId } = {}) {
const db = { release() {}, async query(sql, values) {
if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] };
if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner,
lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
name: 'Test project', lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
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_infrastructure_hosts')) return { rows: [{ id: hostId }] };
@@ -195,3 +195,126 @@ test('unreachable or mismatched host is reported as unavailable, not an empty he
assert.deepEqual(result.items, []); assert.equal(JSON.stringify(result).includes('private-details'), false);
}
});
test('project connection generates stable contour identity and links it without user codes', async () => {
const repo = repository(); const calls = []; const contour = 'c'.repeat(32);
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
calls.push({ path, body });
return path === '/v2/management/contours' ? { id: contour } : { items: [{ id: contour }] };
} }) });
const result = await service.execute(actor, { action: 'project-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, targetProjectRef: `project:${projectId}` }, 'a'.repeat(32));
assert.equal(result.linked, true);
assert.equal(calls[0].body.key, 'dc-' + projectId);
assert.equal(calls[0].body.name, 'Test project');
assert.equal(repo.writes.filter((x) => x.sql.includes('device_b2_contour_links')).length, 1);
});
test('connecting an already linked project does not create another contour', async () => {
const contour = 'c'.repeat(32); const repo = repository({ links: [{ contour_id: contour, project_id: projectId }] });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
assert.equal(path, '/v2/contours'); return { items: [{ id: contour }] };
} }) });
const result = await service.execute(actor, { action: 'project-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}` }, 'a'.repeat(32));
assert.equal(result.contourId, contour);
});
test('application creation and issuance use one server-generated request identity', async () => {
const contour = 'c'.repeat(32); const repo = repository({ links: [{ contour_id: contour, project_id: projectId }] });
const calls = []; const requestId = 'd'.repeat(32); const app = 'e'.repeat(32);
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
calls.push({ path, body }); return path.endsWith('applications') ? { id: app } : { synthetic: true };
} }) });
const result = await service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Partner', contourId: contour }, requestId);
assert.equal(calls[0].body.key, 'app-' + requestId);
assert.equal(calls[1].body.request_id, requestId);
assert.equal(result.id, app);
assert.ok(result.connection);
assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false);
await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32) }, requestId), /b2_access_denied/);
assert.equal(calls.length, 2);
});
test('tracker settings keep project and contour authority across remote calls', async () => {
const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = [];
const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect();
let released = false; const original = db.query;
db.release = () => { released = true; };
db.query = async (sql, values) => {
if (sql.includes('from device_b2_hosts')) {
assert.match(sql, /l.project_id=v.project_id/);
assert.match(sql, /h.lifecycle_state='active'/);
assert.deepEqual(values, [hostId, projectId, contour]);
return { rows: [source] };
}
return original(sql, values);
};
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
assert.equal(released, true); calls.push({path,body});
return path === '/v2/identity' ? {host_id:pkg.host_id} : {revision:1};
} }) });
const input = {action:'tracker',projectRef:`project:${projectId}`,hostRef:`host:${hostId}`,contourId:contour,deviceId:device,request:{action:'state'}};
assert.deepEqual(await service.execute({...actor,hubRole:'member'},input), {revision:1});
assert.equal(calls[1].path, `/v2/contours/${contour}/devices/${device}/settings`);
for (const action of ['save','apply','read','command','cancel','firmware-upload','profile-save']) {
await assert.rejects(service.execute({...actor,hubRole:'member'},{...input,request:{action}}));
}
assert.equal(calls.length,2);
db.query = async (sql,values) => sql.includes('from device_b2_hosts') ? {rows:[]} : original(sql,values);
await assert.rejects(service.execute(actor,input), /b2_access_denied/);
assert.equal(calls.length,2);
});
test('VPS onboarding rejects invalid or application-only credentials without creating a host', async () => {
for (const input of ['bad-json', JSON.stringify({ ...pkg, authority: 'contours' }), JSON.stringify(pkg)]) {
const repo = repository(); let secrets = 0;
const service = new B2Infrastructure({ pool: repo.pool,
secrets: { save: async () => { secrets += 1; return 'private-ref'; } },
clientFactory: () => ({ call: async (path) => path === '/v2/identity' ? { host_id: input === JSON.stringify(pkg) ? 'foreign-host' : pkg.host_id } : { items: [] } }) });
await assert.rejects(service.execute(actor, { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: input }, 'a'.repeat(32)));
assert.equal(secrets, 0); assert.deepEqual(repo.writes, []);
}
});
test('VPS onboarding reuses the project host and audits no credential material', async () => {
const queries = []; let existing = false;
const base = repository(); const db = await base.pool.connect(); const original = db.query.bind(db);
db.query = async (sql, values) => {
queries.push({ sql, values });
if (sql.includes('pg_advisory_xact_lock')) return { rows: [] };
if (sql.startsWith('insert into device_b2_hosts')) return { rows: [{ id: source.id }] };
if (sql.startsWith('select h.host_key')) return { rows: existing ? [{ host_key: 'b2-existing-project-view' }] : [] };
if (sql.startsWith('insert into device_infrastructure_hosts')) return { rows: [{ id: hostId, host_key: values[3],
display_name: values[4], project_id: projectId, owner_scope_id: ownerId, lifecycle_state: 'active', created: !existing }] };
if (sql.startsWith('insert into device_b2_host_views')) { existing = true; return { rows: [] }; }
return original(sql, values);
};
const service = new B2Infrastructure({ pool: base.pool, secrets: { save: async () => 'private-ref' },
clientFactory: () => ({ call: async () => ({ host_id: pkg.host_id }) }) });
const input = { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: JSON.stringify(pkg) };
const first = await service.execute(actor, input, 'a'.repeat(32));
const second = await service.execute(actor, input, 'b'.repeat(32));
assert.equal(first.hostRef, second.hostRef);
assert.equal(queries.filter((q) => q.sql === 'commit').length, 2);
const hosts = queries.filter((q) => q.sql.startsWith('insert into device_infrastructure_hosts'));
assert.equal(hosts[0].values[3], `b2-${source.id}`);
assert.equal(hosts[1].values[3], 'b2-existing-project-view');
const audit = queries.filter((q) => q.sql.includes('insert into device_audit_events'));
assert.ok(audit.length > 0);
assert.ok(!JSON.stringify(audit).includes(pkg.client_secret));
});
test('application deletion requires company and credential authority and forwards only the application ID', async () => {
const repo = repository(); const calls = [];
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg },
clientFactory: () => ({ async call(path, body) { calls.push({ path, body }); return { deleted: true, id: body.integration_id }; } }) });
const input = { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'application-delete', integrationId: 'c'.repeat(32) };
await assert.rejects(service.execute({ ...actor, hubRole: 'member', ownerScopes: [] }, input, '1'.repeat(32)), /device_owner_scope_access_denied/);
await assert.rejects(service.execute(actor, { ...input, integrationId: '../foreign' }, '1'.repeat(32)), /b2_identifier_invalid/);
await assert.rejects(service.execute(actor, { ...input, force: true }, '1'.repeat(32)), /b2_unexpected_field/);
assert.equal(calls.length, 0);
assert.deepEqual(await service.execute(actor, input, '1'.repeat(32)), { deleted: true, id: input.integrationId });
assert.deepEqual(calls, [{ path: '/v2/management/applications/delete', body: { integration_id: input.integrationId } }]);
assert.equal(repo.writes.at(-1).values[1], 'b2.application-delete');
});