Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dcb0c76ac8 | ||
|
|
5200159d0b | ||
|
|
1b3001dfa1 | ||
|
|
f500d0af0f | ||
|
|
2851f10f0f | ||
|
|
d9911a336f | ||
|
|
d0e9acd7bc | ||
|
|
be30fafa95 | ||
|
|
dc9fe6e0fc | ||
|
|
010fab999e | ||
|
|
539c0a60b8 | ||
|
|
53dbd7483e | ||
|
|
19aa5e2796 | ||
|
|
1266b06f9b | ||
|
|
8941769b4c | ||
|
|
8031ed76a2 | ||
|
|
a860b00310 | ||
|
|
b3b0f900c5 | ||
|
|
b8d240a0a0 |
@@ -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`
|
The accepted Device Core policy is automatic deployment after a push to `main`
|
||||||
passes its checks. See [Continuous deployment](docs/CONTINUOUS_DEPLOYMENT.md)
|
passes its checks. See [Continuous deployment](docs/CONTINUOUS_DEPLOYMENT.md)
|
||||||
for the pinned source qualification workflow, Synology setup and activation
|
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
|
Artifact builders in `infra/deploy-runner` emit data-only tarballs. They never
|
||||||
orchestrate Docker or mutate a live host. Promotion remains the established
|
orchestrate Docker or mutate a live host. Promotion remains the established
|
||||||
|
|||||||
Binary file not shown.
@@ -0,0 +1,53 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { readB2Usb } from '../src/b2/usb.mjs';
|
||||||
|
function fixture({ model = 231, silence = false, change = false, incomplete = false } = {}) {
|
||||||
|
let stream, closed = false, identities = 0; const writes = [];
|
||||||
|
const port = {
|
||||||
|
getInfo: () => ({ usbVendorId: 0x2e3c, usbProductId: 0x5740 }),
|
||||||
|
async open(options) { assert.equal(options.flowControl, 'none'); },
|
||||||
|
async close() { closed = true; },
|
||||||
|
readable: new ReadableStream({ start(controller) { stream = controller; } }),
|
||||||
|
writable: new WritableStream({ write(bytes) {
|
||||||
|
const command = new TextDecoder().decode(bytes); writes.push(command);
|
||||||
|
if (silence) return;
|
||||||
|
let response;
|
||||||
|
if (command === '>I 7\r\n') {
|
||||||
|
identities++;
|
||||||
|
response = `>DI=${model};0;6\r\n>DN=300\r\n>MN=${change && identities > 1 ? '4' : '3'}23456789012345\r\n>SID0=0\r\n>SID1=0\r\n`;
|
||||||
|
} else { assert.equal(command, '>D 15;0\r\n'); response = '>SF=synthetic-config\r\n'; }
|
||||||
|
if (incomplete) response = response.slice(0, -2);
|
||||||
|
for (let i = 0; i < response.length; i += 7) stream.enqueue(new TextEncoder().encode(response.slice(i, i + 7)));
|
||||||
|
} }),
|
||||||
|
};
|
||||||
|
return { serial: { async requestPort(options) { assert.deepEqual(options.filters, [{ usbVendorId: 0x2e3c, usbProductId: 0x5740 }]); return port; } }, writes, closed: () => closed, stream: () => stream };
|
||||||
|
}
|
||||||
|
test('read-only USB protocol handles fragmented lines and releases port', async () => {
|
||||||
|
// Successful reads must not depend on CI scheduling within 50–100 ms.
|
||||||
|
// The dedicated timeout test below supplies its own short deadline.
|
||||||
|
const f = fixture(); const result = await readB2Usb({ serial: f.serial });
|
||||||
|
assert.equal(result.settings, 'synthetic-config'); assert.equal(result.before.MN, result.after.MN);
|
||||||
|
assert.deepEqual(f.writes, ['>I 7\r\n', '>D 15;0\r\n', '>I 7\r\n']); assert.ok(f.closed());
|
||||||
|
});
|
||||||
|
test('wrong model stops before requesting configuration', async () => {
|
||||||
|
const f = fixture({ model: 999 });
|
||||||
|
await assert.rejects(readB2Usb({ serial: f.serial }), /не распознано/);
|
||||||
|
assert.deepEqual(f.writes, ['>I 7\r\n']); assert.ok(f.closed());
|
||||||
|
});
|
||||||
|
test('identity change cannot produce a registration snapshot', async () => {
|
||||||
|
const f = fixture({ change: true }); await assert.rejects(readB2Usb({ serial: f.serial }), /изменилось устройство/); assert.ok(f.closed());
|
||||||
|
});
|
||||||
|
test('incomplete response and silence time out and close the port', async () => {
|
||||||
|
for (const options of [{ silence: true }, { incomplete: true }]) {
|
||||||
|
const f = fixture(options); await assert.rejects(readB2Usb({ serial: f.serial, timeoutMs: 15 }), /не ответил/); assert.ok(f.closed());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test('closing the form aborts a pending read and releases USB', async () => {
|
||||||
|
const f = fixture({ silence: true }), controller = new AbortController();
|
||||||
|
const promise = readB2Usb({ serial: f.serial, signal: controller.signal });
|
||||||
|
setTimeout(() => controller.abort(), 10); await assert.rejects(promise, { name: 'AbortError' }); assert.ok(f.closed());
|
||||||
|
});
|
||||||
|
test('disconnect does not turn a partial snapshot into success', async () => {
|
||||||
|
const f = fixture({ silence: true }); const promise = readB2Usb({ serial: f.serial });
|
||||||
|
setTimeout(() => f.stream().close(), 10); await assert.rejects(promise, /USB отключён/); assert.ok(f.closed());
|
||||||
|
});
|
||||||
@@ -122,7 +122,6 @@ test("host hardware monitoring retains the established geometry", async () => {
|
|||||||
".infrastructure-host-relations {",
|
".infrastructure-host-relations {",
|
||||||
"grid-template-columns: repeat(3, minmax(0, 1fr));",
|
"grid-template-columns: repeat(3, minmax(0, 1fr));",
|
||||||
"grid-template-columns: repeat(4, minmax(0, 1fr));",
|
"grid-template-columns: repeat(4, minmax(0, 1fr));",
|
||||||
"background: var(--infrastructure-panel-soft);",
|
|
||||||
".host-monitoring-series polyline {",
|
".host-monitoring-series polyline {",
|
||||||
"stroke: var(--nodedc-text-primary);",
|
"stroke: var(--nodedc-text-primary);",
|
||||||
".host-monitoring-hardware-facts {",
|
".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('title="Deployments и endpoints"'));
|
||||||
assert.ok(!infrastructureSource.includes("ceiling={100}"));
|
assert.ok(!infrastructureSource.includes("ceiling={100}"));
|
||||||
assert.ok(!infrastructureSource.includes("Канонический ontology catalog"));
|
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-metric,"));
|
||||||
assert.ok(!styles.includes(".host-telemetry-facts"));
|
assert.ok(!styles.includes(".host-telemetry-facts"));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ export function createDeviceManagerServer({
|
|||||||
}
|
}
|
||||||
const requestId = singleHeader(request.headers["idempotency-key"]);
|
const requestId = singleHeader(request.headers["idempotency-key"]);
|
||||||
if (!/^[a-f0-9]{32}$/.test(requestId)) throw serviceError("b2_request_id_invalid", 400);
|
if (!/^[a-f0-9]{32}$/.test(requestId)) throw serviceError("b2_request_id_invalid", 400);
|
||||||
const input = await readJsonBody(request, 64 * 1024);
|
const input = await readJsonBody(request, 128 * 1024);
|
||||||
const result = await coreClient.b2Infrastructure(context.actor, input, requestId);
|
const result = await coreClient.b2Infrastructure(context.actor, input, requestId);
|
||||||
return sendJson(response, 200, { ok: true, result });
|
return sendJson(response, 200, { ok: true, result });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -233,3 +233,18 @@ test('B2 key management rejects cross-origin requests and never caches returned
|
|||||||
assert.equal(calls.length, 1);
|
assert.equal(calls.length, 1);
|
||||||
assert.equal(calls[0].actor.userRef, 'user:local-device-admin');
|
assert.equal(calls[0].actor.userRef, 'user:local-device-admin');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('B2 USB envelope fits the bounded route while oversized requests are rejected', async (t) => {
|
||||||
|
const auth = createDeviceManagerAuth({ env: { NODEDC_DEVICE_MANAGER_AUTH_REQUIRED: 'false' } });
|
||||||
|
let calls = 0;
|
||||||
|
const coreClient = { ...createLocalPreviewDeviceCore(), async b2Infrastructure(actor, body) { calls++; return { bytes: body.request.usb.settings.length }; } };
|
||||||
|
const server = createDeviceManagerServer({ auth, coreClient });
|
||||||
|
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
||||||
|
t.after(() => new Promise(resolve => server.close(resolve)));
|
||||||
|
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||||
|
for (const [size, status] of [[88000, 200], [140000, 413]]) {
|
||||||
|
const response = await fetch(origin + '/api/device-manager/b2/infrastructure', { method: 'POST', headers: { origin, 'content-type': 'application/json', 'idempotency-key': 'b'.repeat(32) }, body: JSON.stringify({ action: 'enrollment', request: { action: 'inspect', usb: { settings: 'A'.repeat(size) } } }) });
|
||||||
|
assert.equal(response.status, status); await response.arrayBuffer();
|
||||||
|
}
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
});
|
||||||
|
|||||||
@@ -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');
|
||||||
|
});
|
||||||
@@ -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 {
|
import {
|
||||||
Button,
|
Button,
|
||||||
ConfirmationModal,
|
ConfirmationModal,
|
||||||
ResourceList as CanonicalResourceList,
|
ResourceList as CanonicalResourceList,
|
||||||
ResourceRow as CanonicalResourceRow,
|
ResourceRow as CanonicalResourceRow,
|
||||||
GlassSurface,
|
|
||||||
Icon,
|
Icon,
|
||||||
IconButton,
|
IconButton,
|
||||||
Select,
|
Select,
|
||||||
@@ -20,7 +20,6 @@ import { useB2Inventory } from "./b2/useB2Inventory";
|
|||||||
import { B2HostSettings } from "./b2/B2HostSettings";
|
import { B2HostSettings } from "./b2/B2HostSettings";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
archiveHost,
|
|
||||||
createConfigurationRevision,
|
createConfigurationRevision,
|
||||||
closeAssetBinding,
|
closeAssetBinding,
|
||||||
ensureAsset,
|
ensureAsset,
|
||||||
@@ -30,7 +29,6 @@ import {
|
|||||||
ensureEdge,
|
ensureEdge,
|
||||||
ensureInfrastructureDeployment,
|
ensureInfrastructureDeployment,
|
||||||
ensureInfrastructureEndpoint,
|
ensureInfrastructureEndpoint,
|
||||||
ensureInfrastructureHost,
|
|
||||||
ensureInfrastructureServiceInstance,
|
ensureInfrastructureServiceInstance,
|
||||||
ensureRoute,
|
ensureRoute,
|
||||||
registerAdapterVersion,
|
registerAdapterVersion,
|
||||||
@@ -84,8 +82,6 @@ type DialogId =
|
|||||||
| null;
|
| null;
|
||||||
|
|
||||||
export function DeviceControlView({
|
export function DeviceControlView({
|
||||||
selectedHostRef,
|
|
||||||
onSelectHost,
|
|
||||||
view,
|
view,
|
||||||
workspace,
|
workspace,
|
||||||
session,
|
session,
|
||||||
@@ -93,8 +89,6 @@ export function DeviceControlView({
|
|||||||
onPoll,
|
onPoll,
|
||||||
onError,
|
onError,
|
||||||
}: {
|
}: {
|
||||||
selectedHostRef: string | null;
|
|
||||||
onSelectHost: (hostRef: string | null) => void;
|
|
||||||
view: ControlViewId;
|
view: ControlViewId;
|
||||||
workspace: ProjectWorkspace;
|
workspace: ProjectWorkspace;
|
||||||
session: DeviceManagerSession;
|
session: DeviceManagerSession;
|
||||||
@@ -181,13 +175,10 @@ export function DeviceControlView({
|
|||||||
) : null}
|
) : null}
|
||||||
{view === "hosts" ? (
|
{view === "hosts" ? (
|
||||||
<HostsView
|
<HostsView
|
||||||
selectedHostRef={selectedHostRef}
|
|
||||||
onSelectHost={onSelectHost}
|
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
canManageInfrastructure={capabilities.has("infrastructure.manage")}
|
canManageInfrastructure={capabilities.has("infrastructure.manage")}
|
||||||
canManageAssets={capabilities.has("asset.manage")}
|
canManageAssets={capabilities.has("asset.manage")}
|
||||||
canManageBindings={capabilities.has("binding.manage")}
|
canManageBindings={capabilities.has("binding.manage")}
|
||||||
onCreateHost={() => setDialog("host")}
|
|
||||||
onCreateEndpoint={(hostRef) => { setDialogHostRef(hostRef); setDialog("endpoint"); }}
|
onCreateEndpoint={(hostRef) => { setDialogHostRef(hostRef); setDialog("endpoint"); }}
|
||||||
onCreateDeployment={(hostRef) => { setDialogHostRef(hostRef); setDialog("deployment"); }}
|
onCreateDeployment={(hostRef) => { setDialogHostRef(hostRef); setDialog("deployment"); }}
|
||||||
onCreateService={(hostRef) => { setDialogHostRef(hostRef); setDialog("service-instance"); }}
|
onCreateService={(hostRef) => { setDialogHostRef(hostRef); setDialog("service-instance"); }}
|
||||||
@@ -308,15 +299,8 @@ export function DeviceControlView({
|
|||||||
onCreated={completed}
|
onCreated={completed}
|
||||||
onError={onError}
|
onError={onError}
|
||||||
/>
|
/>
|
||||||
<HostDialog
|
|
||||||
open={dialog === "host"}
|
|
||||||
projectRef={workspace.project.projectRef}
|
|
||||||
onClose={close}
|
|
||||||
onCreated={completed}
|
|
||||||
onError={onError}
|
|
||||||
/>
|
|
||||||
<EndpointDialog
|
<EndpointDialog
|
||||||
key={`${dialogHostRef}:${dialog}`}
|
key={`EndpointDialog:${dialogHostRef}:${dialog}`}
|
||||||
initialHostRef={dialogHostRef}
|
initialHostRef={dialogHostRef}
|
||||||
open={dialog === "endpoint"}
|
open={dialog === "endpoint"}
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
@@ -325,7 +309,7 @@ export function DeviceControlView({
|
|||||||
onError={onError}
|
onError={onError}
|
||||||
/>
|
/>
|
||||||
<DeploymentDialog
|
<DeploymentDialog
|
||||||
key={`${dialogHostRef}:${dialog}`}
|
key={`DeploymentDialog:${dialogHostRef}:${dialog}`}
|
||||||
initialHostRef={dialogHostRef}
|
initialHostRef={dialogHostRef}
|
||||||
open={dialog === "deployment"}
|
open={dialog === "deployment"}
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
@@ -334,7 +318,7 @@ export function DeviceControlView({
|
|||||||
onError={onError}
|
onError={onError}
|
||||||
/>
|
/>
|
||||||
<ServiceInstanceDialog
|
<ServiceInstanceDialog
|
||||||
key={`${dialogHostRef}:${dialog}`}
|
key={`ServiceInstanceDialog:${dialogHostRef}:${dialog}`}
|
||||||
initialHostRef={dialogHostRef}
|
initialHostRef={dialogHostRef}
|
||||||
open={dialog === "service-instance"}
|
open={dialog === "service-instance"}
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
@@ -365,15 +349,15 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
|
|||||||
return (
|
return (
|
||||||
<ControlStack>
|
<ControlStack>
|
||||||
<ControlToolbar
|
<ControlToolbar
|
||||||
copy="Adapter packages и model profiles — глобальный versioned каталог. B2 здесь не является отдельным продуктом."
|
copy="Модели устройств и версии адаптеров."
|
||||||
actions={canManage ? <>
|
actions={canManage ? <>
|
||||||
<Button size="compact" onClick={onCreatePackage}>Пакет</Button>
|
<Button size="compact" onClick={onCreatePackage}>Пакет</Button>
|
||||||
<Button size="compact" onClick={onCreateVersion} disabled={!workspace.adapterPackages.length}>Версия</Button>
|
<Button size="compact" onClick={onCreateVersion} disabled={!workspace.adapterPackages.length}>Версия</Button>
|
||||||
<Button size="compact" variant="primary" onClick={onCreateProfile} disabled={!workspace.adapterVersions.length}>Профиль</Button>
|
<Button size="compact" variant="primary" onClick={onCreateProfile} disabled={!workspace.adapterVersions.length}>Профиль</Button>
|
||||||
</> : null}
|
</> : null}
|
||||||
/>
|
/>
|
||||||
<ControlSection title="Model profiles" count={workspace.modelProfiles.length}>
|
<ControlSection title="Модели устройств" count={workspace.modelProfiles.length}>
|
||||||
<ResourceGrid empty="В доступном каталоге пока нет model profiles.">
|
<ResourceGrid empty="Модели устройств пока не добавлены.">
|
||||||
{workspace.modelProfiles.map((profile) => (
|
{workspace.modelProfiles.map((profile) => (
|
||||||
<ResourceCard
|
<ResourceCard
|
||||||
key={profile.modelProfileRef}
|
key={profile.modelProfileRef}
|
||||||
@@ -389,7 +373,7 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
|
|||||||
))}
|
))}
|
||||||
</ResourceGrid>
|
</ResourceGrid>
|
||||||
</ControlSection>
|
</ControlSection>
|
||||||
<ControlSection title="Adapter versions" count={workspace.adapterVersions.length}>
|
<ControlSection title="Версии адаптеров" count={workspace.adapterVersions.length}>
|
||||||
<ResourceGrid empty="Версии адаптеров не зарегистрированы.">
|
<ResourceGrid empty="Версии адаптеров не зарегистрированы.">
|
||||||
{workspace.adapterVersions.map((version) => (
|
{workspace.adapterVersions.map((version) => (
|
||||||
<ResourceCard
|
<ResourceCard
|
||||||
@@ -406,8 +390,8 @@ function CatalogView({ workspace, canManage, onCreatePackage, onCreateVersion, o
|
|||||||
))}
|
))}
|
||||||
</ResourceGrid>
|
</ResourceGrid>
|
||||||
</ControlSection>
|
</ControlSection>
|
||||||
<ControlSection title="Adapter packages" count={workspace.adapterPackages.length}>
|
<ControlSection title="Адаптеры" count={workspace.adapterPackages.length}>
|
||||||
<ResourceGrid empty="Adapter packages не зарегистрированы.">
|
<ResourceGrid empty="Адаптеры пока не добавлены.">
|
||||||
{workspace.adapterPackages.map((adapterPackage) => (
|
{workspace.adapterPackages.map((adapterPackage) => (
|
||||||
<ResourceCard
|
<ResourceCard
|
||||||
key={adapterPackage.adapterPackageRef}
|
key={adapterPackage.adapterPackageRef}
|
||||||
@@ -438,13 +422,13 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
|
|||||||
return (
|
return (
|
||||||
<ControlStack>
|
<ControlStack>
|
||||||
<ControlToolbar
|
<ControlToolbar
|
||||||
copy="Edge — зарегистрированная внешняя роль. Route связывает проект, Edge, profile и логический listener без credentials."
|
copy="Узлы приёма данных и маршруты устройств."
|
||||||
actions={<>
|
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}
|
{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="Маршрутов в проекте пока нет.">
|
<ResourceGrid empty="Маршрутов в проекте пока нет.">
|
||||||
{workspace.routes.map((route) => (
|
{workspace.routes.map((route) => (
|
||||||
<ResourceCard
|
<ResourceCard
|
||||||
@@ -464,12 +448,12 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
|
|||||||
))}
|
))}
|
||||||
</ResourceGrid>
|
</ResourceGrid>
|
||||||
</ControlSection>
|
</ControlSection>
|
||||||
<ControlSection title="Edges" count={workspace.edges.length}>
|
<ControlSection title="Узлы приёма данных" count={workspace.edges.length}>
|
||||||
<ResourceGrid empty="Доступных Edge registrations нет.">
|
<ResourceGrid empty="Узлы пока не добавлены.">
|
||||||
{workspace.edges.map((edge) => (
|
{workspace.edges.map((edge) => (
|
||||||
<ResourceCard
|
<ResourceCard
|
||||||
key={edge.edgeRef}
|
key={edge.edgeRef}
|
||||||
eyebrow="DEVICE GATEWAY EDGE"
|
eyebrow="Узел приёма данных"
|
||||||
title={edge.displayName}
|
title={edge.displayName}
|
||||||
description={edge.edgeKey}
|
description={edge.edgeKey}
|
||||||
status={edge.lifecycleState}
|
status={edge.lifecycleState}
|
||||||
@@ -486,12 +470,10 @@ function InfrastructureView({ workspace, canManageCatalog, canManageRoutes, onCr
|
|||||||
}
|
}
|
||||||
|
|
||||||
function HostsView({
|
function HostsView({
|
||||||
selectedHostRef, onSelectHost,
|
|
||||||
workspace,
|
workspace,
|
||||||
canManageInfrastructure,
|
canManageInfrastructure,
|
||||||
canManageAssets,
|
canManageAssets,
|
||||||
canManageBindings,
|
canManageBindings,
|
||||||
onCreateHost,
|
|
||||||
onCreateEndpoint,
|
onCreateEndpoint,
|
||||||
onCreateDeployment,
|
onCreateDeployment,
|
||||||
onCreateService,
|
onCreateService,
|
||||||
@@ -502,13 +484,10 @@ function HostsView({
|
|||||||
onPoll,
|
onPoll,
|
||||||
onError,
|
onError,
|
||||||
}: {
|
}: {
|
||||||
selectedHostRef: string | null;
|
|
||||||
onSelectHost: (hostRef: string | null) => void;
|
|
||||||
workspace: ProjectWorkspace;
|
workspace: ProjectWorkspace;
|
||||||
canManageInfrastructure: boolean;
|
canManageInfrastructure: boolean;
|
||||||
canManageAssets: boolean;
|
canManageAssets: boolean;
|
||||||
canManageBindings: boolean;
|
canManageBindings: boolean;
|
||||||
onCreateHost: () => void;
|
|
||||||
onCreateEndpoint: (hostRef: string) => void;
|
onCreateEndpoint: (hostRef: string) => void;
|
||||||
onCreateDeployment: (hostRef: string) => void;
|
onCreateDeployment: (hostRef: string) => void;
|
||||||
onCreateService: (hostRef: string) => void;
|
onCreateService: (hostRef: string) => void;
|
||||||
@@ -523,41 +502,14 @@ function HostsView({
|
|||||||
const [expandedHost, setExpandedHost] = useState<string | null>(null);
|
const [expandedHost, setExpandedHost] = useState<string | null>(null);
|
||||||
const [showArchive, setShowArchive] = useState(false);
|
const [showArchive, setShowArchive] = useState(false);
|
||||||
const [showAssets, setShowAssets] = useState(false);
|
const [showAssets, setShowAssets] = useState(false);
|
||||||
const [archiveTarget, setArchiveTarget] = useState<InfrastructureHostView | null>(null);
|
|
||||||
const [archiving, setArchiving] = useState(false);
|
|
||||||
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
|
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
|
||||||
const topology = workspace.ontology;
|
const topology = workspace.ontology;
|
||||||
const hosts = topology.hosts.filter((host) => showArchive ? host.lifecycleState === 'suspended' : !['suspended', 'retired'].includes(host.lifecycleState));
|
const hosts = topology.hosts.filter((host) => showArchive ? host.lifecycleState === 'suspended' : !['suspended', 'retired'].includes(host.lifecycleState));
|
||||||
const selectedHost = topology.hosts.find((host) => host.hostRef === selectedHostRef);
|
|
||||||
const source = b2.data?.hosts.find((host) => host.hostRef === selectedHostRef);
|
|
||||||
const isB2 = (host: InfrastructureHostView) => Boolean(b2.data?.hosts.some((item) => item.hostRef === host.hostRef)) || host.hostKey.startsWith('b2-');
|
const isB2 = (host: InfrastructureHostView) => Boolean(b2.data?.hosts.some((item) => item.hostRef === host.hostRef)) || host.hostKey.startsWith('b2-');
|
||||||
const settings = settingsHost ? <B2HostSettings key={settingsHost.hostRef} host={settingsHost} workspace={workspace} onClose={() => setSettingsHost(null)} onChanged={onPoll} onError={onError} /> : null;
|
const settings = settingsHost ? <B2HostSettings key={settingsHost.hostRef} host={settingsHost} workspace={workspace} onClose={() => setSettingsHost(null)} onChanged={onPoll} onError={onError} /> : null;
|
||||||
if (selectedHost) {
|
|
||||||
if (isB2(selectedHost)) return <div className="b2-settings">
|
|
||||||
{settings}
|
|
||||||
<SettingsCard title={selectedHost.displayName} actions={canManageInfrastructure ? <IconButton label={`Настройки ${selectedHost.displayName}`} onClick={() => setSettingsHost(selectedHost)}><Icon name="settings" /></IconButton> : undefined}>
|
|
||||||
<CanonicalResourceList>
|
|
||||||
<li><CanonicalResourceRow title="API ARNavi" description={source?.endpoint} metadata={source ? `Проверено: ${formatDate(source.checkedAt)}` : undefined} status={<StatusBadge tone={source?.reachable ? 'success' : source ? 'warning' : 'neutral'}>{source?.reachable ? 'Доступен' : source ? 'Нет связи' : 'Проверка…'}</StatusBadge>} /></li>
|
|
||||||
<li><CanonicalResourceRow title="Контуры проекта" status={String(source?.contours ?? '—')} /></li>
|
|
||||||
<li><CanonicalResourceRow title="Трекеры проекта" status={String(source?.devices ?? '—')} /></li>
|
|
||||||
<li><CanonicalResourceRow title="Метрики оборудования" status={<StatusBadge>Не подключены</StatusBadge>} /></li>
|
|
||||||
</CanonicalResourceList>
|
|
||||||
</SettingsCard>
|
|
||||||
{b2.error ? <p role="alert">{b2.error}</p> : null}
|
|
||||||
</div>;
|
|
||||||
return <HostTelemetryWorkspace host={selectedHost} services={topology.serviceInstances.filter((item) => item.hostRef === selectedHost.hostRef)} onPoll={onPoll} onError={onError} />;
|
|
||||||
}
|
|
||||||
return <div className="b2-settings">
|
return <div className="b2-settings">
|
||||||
{settings}
|
{settings}
|
||||||
<ConfirmationModal open={Boolean(archiveTarget)} title={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить хост?' : 'Перенести хост в архив?'} description={archiveTarget?.displayName} confirmLabel={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => {
|
{topology.hosts.some((host) => host.lifecycleState === 'suspended') ? <div className="b2-actions"><Button variant="ghost" onClick={() => setShowArchive(!showArchive)}>{showArchive ? 'К действующим хостам' : 'Архив'}</Button></div> : null}
|
||||||
if (!archiveTarget || archiving) return;
|
|
||||||
setArchiving(true);
|
|
||||||
try { await archiveHost(workspace.project.projectRef, archiveTarget.hostRef, archiveTarget.lifecycleState !== 'suspended'); setArchiveTarget(null); await onPoll(); } catch (reason) { onError(reason); } finally { setArchiving(false); }
|
|
||||||
}} />
|
|
||||||
<div className="b2-actions">
|
|
||||||
{topology.hosts.some((host) => host.lifecycleState === 'suspended') ? <Button variant="ghost" onClick={() => setShowArchive(!showArchive)}>{showArchive ? 'К действующим хостам' : 'Архив'}</Button> : null}
|
|
||||||
{canManageInfrastructure ? <IconButton label="Добавить VPS" onClick={onCreateHost}><Icon name="plus" /></IconButton> : null}
|
|
||||||
</div>
|
|
||||||
{b2.error ? <p role="alert">{b2.error}</p> : null}
|
{b2.error ? <p role="alert">{b2.error}</p> : null}
|
||||||
<CanonicalResourceList>{hosts.map((host) => {
|
<CanonicalResourceList>{hosts.map((host) => {
|
||||||
const remote = b2.data?.hosts.find((item) => item.hostRef === host.hostRef);
|
const remote = b2.data?.hosts.find((item) => item.hostRef === host.hostRef);
|
||||||
@@ -567,17 +519,19 @@ function HostsView({
|
|||||||
status={<StatusBadge tone={remote ? remote.reachable ? 'success' : 'warning' : freshnessTone(host.telemetry.freshness)}>{remote ? remote.reachable ? 'Подключён' : 'Нет связи' : host.lifecycleState === 'suspended' ? 'В архиве' : freshnessLabel(host.telemetry.freshness)}</StatusBadge>}
|
status={<StatusBadge tone={remote ? remote.reachable ? 'success' : 'warning' : freshnessTone(host.telemetry.freshness)}>{remote ? remote.reachable ? 'Подключён' : 'Нет связи' : host.lifecycleState === 'suspended' ? 'В архиве' : freshnessLabel(host.telemetry.freshness)}</StatusBadge>}
|
||||||
actions={<>
|
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}
|
{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={expanded ? "chevron-up" : "chevron-down"} /></IconButton>
|
||||||
<IconButton label={`Сведения ${host.displayName}`} aria-expanded={expanded} onClick={() => setExpandedHost(expanded ? null : host.hostRef)}><Icon name="chevron-down" /></IconButton>
|
|
||||||
</>} />
|
</>} />
|
||||||
{expanded ? <SettingsCard title="Сведения о хосте">
|
{expanded ? <div className="b2-disclosure__body">
|
||||||
<CanonicalResourceList>
|
{isB2(host) ? <CanonicalResourceList>
|
||||||
{topology.endpoints.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.endpointRef}><CanonicalResourceRow title="Адрес подключения" description={item.endpointUri} /></li>)}
|
<li><CanonicalResourceRow title="API ARNavi" description={remote?.endpoint} metadata={remote ? `Проверено: ${formatDate(remote.checkedAt)}` : undefined} status={<StatusBadge tone={remote?.reachable ? 'success' : remote ? 'warning' : 'neutral'}>{remote?.reachable ? 'Доступен' : remote ? 'Нет связи' : 'Проверка…'}</StatusBadge>} /></li>
|
||||||
{topology.deployments.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.deploymentRef}><CanonicalResourceRow title={item.displayName} metadata="Развёртывание" /></li>)}
|
<li><CanonicalResourceRow title="Контуры проекта" status={String(remote?.contours ?? '—')} /></li>
|
||||||
{topology.serviceInstances.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.serviceInstanceRef}><CanonicalResourceRow title={item.displayName} metadata="Сервис" /></li>)}
|
<li><CanonicalResourceRow title="Трекеры проекта" status={String(remote?.devices ?? '—')} /></li>
|
||||||
</CanonicalResourceList>
|
<li><CanonicalResourceRow title="Метрики оборудования" status={<StatusBadge>Не подключены</StatusBadge>} /></li>
|
||||||
{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}
|
</CanonicalResourceList> : <>
|
||||||
</SettingsCard> : null}
|
<HostTelemetryWorkspace host={host} services={topology.serviceInstances.filter(item => item.hostRef === host.hostRef)} onPoll={onPoll} onError={onError} />
|
||||||
|
{canManageInfrastructure ? <div className="b2-actions"><Button onClick={() => onCreateEndpoint(host.hostRef)}>Адрес</Button><Button onClick={() => onCreateDeployment(host.hostRef)}>Развёртывание</Button><Button onClick={() => onCreateService(host.hostRef)} disabled={!topology.deployments.some(item => item.hostRef === host.hostRef)}>Сервис</Button></div> : null}
|
||||||
|
</>}
|
||||||
|
</div> : null}
|
||||||
</li>;
|
</li>;
|
||||||
})}</CanonicalResourceList>
|
})}</CanonicalResourceList>
|
||||||
{!hosts.length ? <p>{showArchive ? 'Архив пуст' : 'Нет подключённых VPS'}</p> : null}
|
{!hosts.length ? <p>{showArchive ? 'Архив пуст' : 'Нет подключённых VPS'}</p> : null}
|
||||||
@@ -650,7 +604,7 @@ function HostTelemetryWorkspace({
|
|||||||
<HostTelemetrySeries label="NETWORK TX" value={formatRate(networkRate.sent)} resource={networkRate.sent == null ? "нет данных" : "исходящий трафик"} values={sendHistory} />
|
<HostTelemetrySeries label="NETWORK TX" value={formatRate(networkRate.sent)} resource={networkRate.sent == null ? "нет данных" : "исходящий трафик"} values={sendHistory} />
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<GlassSurface className="host-monitoring-hardware" padding="lg">
|
<div className="host-monitoring-hardware">
|
||||||
<InfrastructureSectionHeading
|
<InfrastructureSectionHeading
|
||||||
eyebrow="HARDWARE"
|
eyebrow="HARDWARE"
|
||||||
title={current?.hardware.hostname ?? host.hostKey}
|
title={current?.hardware.hostname ?? host.hostKey}
|
||||||
@@ -681,7 +635,7 @@ function HostTelemetryWorkspace({
|
|||||||
))}
|
))}
|
||||||
{!current?.disks.length ? <div className="infrastructure-empty">Данные о дисках ещё не поступили.</div> : null}
|
{!current?.disks.length ? <div className="infrastructure-empty">Данные о дисках ещё не поступили.</div> : null}
|
||||||
</div>
|
</div>
|
||||||
</GlassSurface>
|
</div>
|
||||||
|
|
||||||
<section className="infrastructure-section">
|
<section className="infrastructure-section">
|
||||||
<InfrastructureSectionHeading
|
<InfrastructureSectionHeading
|
||||||
@@ -693,7 +647,7 @@ function HostTelemetryWorkspace({
|
|||||||
{networkInterfaces.length ? (
|
{networkInterfaces.length ? (
|
||||||
<div className="host-monitoring-network-grid">
|
<div className="host-monitoring-network-grid">
|
||||||
{networkInterfaces.map((item, index) => (
|
{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>
|
<header><strong>{item.interface ?? "Интерфейс"}</strong><small>{formatPackets(item.packetsReceived, item.packetsSent)}</small></header>
|
||||||
<dl>
|
<dl>
|
||||||
<div><dt>Получено</dt><dd>{formatMetricBytes(item.bytesReceived)}</dd></div>
|
<div><dt>Получено</dt><dd>{formatMetricBytes(item.bytesReceived)}</dd></div>
|
||||||
@@ -701,7 +655,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.errorsReceived)} / {formatNullable(item.errorsSent)}</dd></div>
|
||||||
<div><dt>Потери RX / TX</dt><dd>{formatNullable(item.droppedReceived)} / {formatNullable(item.droppedSent)}</dd></div>
|
<div><dt>Потери RX / TX</dt><dd>{formatNullable(item.droppedReceived)} / {formatNullable(item.droppedSent)}</dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
</GlassSurface>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : <div className="infrastructure-empty">Сетевые счётчики ещё не поступили.</div>}
|
) : <div className="infrastructure-empty">Сетевые счётчики ещё не поступили.</div>}
|
||||||
@@ -718,7 +672,7 @@ function HostTelemetryWorkspace({
|
|||||||
{runtimeServices.length ? (
|
{runtimeServices.length ? (
|
||||||
<div className="infrastructure-runtime-grid">
|
<div className="infrastructure-runtime-grid">
|
||||||
{runtimeServices.map((service, index) => (
|
{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>
|
<header>
|
||||||
<div><span className="infrastructure-eyebrow">SYSTEMD UNIT</span><h3>{service.name ?? "systemd unit"}</h3><code>{service.subState ?? "—"}</code></div>
|
<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>
|
<StatusBadge tone={service.activeState === "active" ? "success" : service.activeState === "failed" ? "danger" : "warning"}>{service.activeState ?? "unknown"}</StatusBadge>
|
||||||
@@ -729,7 +683,7 @@ function HostTelemetryWorkspace({
|
|||||||
<div><dt>Перезапуски</dt><dd>{formatNullable(service.restarts)}</dd></div>
|
<div><dt>Перезапуски</dt><dd>{formatNullable(service.restarts)}</dd></div>
|
||||||
<div><dt>PID</dt><dd>{formatNullable(service.pid)}</dd></div>
|
<div><dt>PID</dt><dd>{formatNullable(service.pid)}</dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
</GlassSurface>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : <div className="infrastructure-empty">Состояние сервисов ещё не поступило.</div>}
|
) : <div className="infrastructure-empty">Состояние сервисов ещё не поступило.</div>}
|
||||||
@@ -964,8 +918,8 @@ function formatPackets(received: number | null | undefined, sent: number | null
|
|||||||
function SessionsView({ workspace }: { workspace: ProjectWorkspace }) {
|
function SessionsView({ workspace }: { workspace: ProjectWorkspace }) {
|
||||||
return (
|
return (
|
||||||
<ControlStack>
|
<ControlStack>
|
||||||
<ControlToolbar copy="Сессии принадлежат Gateway runtime. Device Manager только читает bounded presence/counter projection." />
|
<ControlToolbar copy="Подключения устройств" />
|
||||||
<ResourceList empty="Gateway sessions пока не наблюдались.">
|
<ResourceList empty="Нет подключений">
|
||||||
{workspace.sessions.map((session) => (
|
{workspace.sessions.map((session) => (
|
||||||
<ResourceRow
|
<ResourceRow
|
||||||
key={session.sessionRef}
|
key={session.sessionRef}
|
||||||
@@ -989,10 +943,10 @@ function BindingsView({ workspace, canManage, onCreate, onRevoke }: {
|
|||||||
return (
|
return (
|
||||||
<ControlStack>
|
<ControlStack>
|
||||||
<ControlToolbar
|
<ControlToolbar
|
||||||
copy="Binding создаёт только source approval. Active появится лишь после отдельного external proof от целевой системы."
|
copy="Передача данных в приложения"
|
||||||
actions={canManage ? <Button variant="primary" onClick={onCreate} disabled={!workspace.collections.length && !workspace.devices.length}>Новый binding</Button> : null}
|
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) => (
|
{workspace.bindings.map((binding) => (
|
||||||
<ResourceRow
|
<ResourceRow
|
||||||
key={binding.bindingRef}
|
key={binding.bindingRef}
|
||||||
@@ -1049,18 +1003,17 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
|
|||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
<ControlStack>
|
<ControlStack>
|
||||||
<GlassSurface className="device-control-command-policy" padding="md" tone="soft">
|
<div className="device-control-command-policy">
|
||||||
<Icon name={enabled ? "check" : "lock"} />
|
<Icon name={enabled ? "check" : "lock"} />
|
||||||
<div>
|
<div>
|
||||||
<strong>{enabled ? "Типизированный командный канал активен" : "Command transport выключен"}</strong>
|
<strong>{enabled ? "Проверка сервиса устройства" : "Команды для этого канала недоступны"}</strong>
|
||||||
<p>{enabled
|
<p>{enabled
|
||||||
? "Доступна только безопасная проверка сервиса. Произвольные команды, прошивка, очистка памяти и перезагрузка отсутствуют. Код устройства существует только в памяти Core до отправки или истечения TTL."
|
? "Выберите устройство и введите его шестизначный код."
|
||||||
: "Ни UI, ни BFF не имеют raw command builder. acknowledged означает подтверждение протокола, verified — отдельное доказательство состояния."}</p>
|
: "Для этого подключения отправка команд ещё не настроена."}</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<StatusBadge tone={enabled ? "success" : "warning"}>{workspace.policies.commandTransport}</StatusBadge>
|
|
||||||
</GlassSurface>
|
|
||||||
{enabled ? (
|
{enabled ? (
|
||||||
<GlassSurface padding="md" tone="soft">
|
<div>
|
||||||
<form className="device-control-command-form" onSubmit={submit}>
|
<form className="device-control-command-form" onSubmit={submit}>
|
||||||
<Select
|
<Select
|
||||||
label="B2 трекер"
|
label="B2 трекер"
|
||||||
@@ -1095,14 +1048,14 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
|
|||||||
{submitting ? "Ставим в очередь…" : "Проверить сервис"}
|
{submitting ? "Ставим в очередь…" : "Проверить сервис"}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</GlassSurface>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
<ResourceList empty="Command intents отсутствуют. Это не означает, что транспорт доступен.">
|
<ResourceList empty="Команд пока нет">
|
||||||
{workspace.commands.map((command) => (
|
{workspace.commands.map((command) => (
|
||||||
<ResourceRow
|
<ResourceRow
|
||||||
key={command.commandRef}
|
key={command.commandRef}
|
||||||
title={`${command.commandType} · ${command.deviceName}`}
|
title={`${command.commandType} · ${command.deviceName}`}
|
||||||
description={`${command.riskClass} · expires ${formatDate(command.expiresAt)}`}
|
description={`${command.riskClass} · до ${formatDate(command.expiresAt)}`}
|
||||||
status={command.lifecycleState}
|
status={command.lifecycleState}
|
||||||
trailing={command.terminalReasonCode || command.commandKey}
|
trailing={command.terminalReasonCode || command.commandKey}
|
||||||
/>
|
/>
|
||||||
@@ -1115,15 +1068,15 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
|
|||||||
function AuditView({ workspace }: { workspace: ProjectWorkspace }) {
|
function AuditView({ workspace }: { workspace: ProjectWorkspace }) {
|
||||||
return (
|
return (
|
||||||
<ControlStack>
|
<ControlStack>
|
||||||
<ControlToolbar copy="Показывается immutable metadata projection. Audit payload намеренно не выдаётся в браузер." />
|
<ControlToolbar copy="История действий в проекте" />
|
||||||
<ResourceList empty="Audit events для проекта отсутствуют.">
|
<ResourceList empty="Действий пока нет">
|
||||||
{workspace.auditEvents.map((event) => (
|
{workspace.auditEvents.map((event) => (
|
||||||
<ResourceRow
|
<ResourceRow
|
||||||
key={event.auditEventRef}
|
key={event.auditEventRef}
|
||||||
title={event.eventType}
|
title={auditEventLabel(event.eventType)}
|
||||||
description={`${event.actorRef} · ${formatDate(event.occurredAt)}`}
|
description={`${event.actorRef} · ${formatDate(event.occurredAt)}`}
|
||||||
status="recorded"
|
status="recorded"
|
||||||
trailing={event.deviceRef || event.discoveryRef || "project"}
|
trailing={event.deviceRef || event.discoveryRef || "Проект"}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</ResourceList>
|
</ResourceList>
|
||||||
@@ -1139,17 +1092,17 @@ function AccessView({ workspace, canManage, onCreate }: {
|
|||||||
return (
|
return (
|
||||||
<ControlStack>
|
<ControlStack>
|
||||||
<ControlToolbar
|
<ControlToolbar
|
||||||
copy="Hub задаёт потолок, а Device Project grant — конкретную роль. Direct user grant имеет приоритет над group grants."
|
copy="Доступ к проекту"
|
||||||
actions={canManage ? <Button variant="primary" onClick={onCreate}>Добавить доступ</Button> : null}
|
actions={canManage ? <Button variant="primary" onClick={onCreate}>Добавить доступ</Button> : null}
|
||||||
/>
|
/>
|
||||||
<ResourceList empty="Project grants недоступны или ещё не созданы.">
|
<ResourceList empty="Доступ пока не назначен">
|
||||||
{workspace.grants.map((grant) => (
|
{workspace.grants.map((grant) => (
|
||||||
<ResourceRow
|
<ResourceRow
|
||||||
key={grant.grantRef}
|
key={grant.grantRef}
|
||||||
title={grant.principalRef}
|
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}
|
status={grant.lifecycleState}
|
||||||
trailing={grant.capabilityDeny.length ? `deny: ${grant.capabilityDeny.join(", ")}` : "role capabilities"}
|
trailing={grant.capabilityDeny.length ? `Исключения: ${grant.capabilityDeny.map(capabilityLabel).join(", ")}` : "Права роли"}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</ResourceList>
|
</ResourceList>
|
||||||
@@ -1164,32 +1117,27 @@ function SettingsView({ workspace, canConfigure, onCreateConfiguration }: {
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<ControlStack>
|
<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
|
<ControlToolbar
|
||||||
copy="Configuration revisions immutable. Desired и applied — разные указатели; создание desired не означает применение устройством."
|
copy="Настройки устройств"
|
||||||
actions={canConfigure ? <Button variant="primary" onClick={onCreateConfiguration} disabled={!workspace.devices.length}>Новая desired revision</Button> : null}
|
actions={canConfigure ? <Button variant="primary" onClick={onCreateConfiguration} disabled={!workspace.devices.length}>Новая версия настроек</Button> : null}
|
||||||
/>
|
/>
|
||||||
<ResourceList empty="Configuration state пока отсутствует.">
|
<ResourceList empty="Сохранённых настроек пока нет">
|
||||||
{workspace.configurationStates.map((state) => (
|
{workspace.configurationStates.map((state) => (
|
||||||
<ResourceRow
|
<ResourceRow
|
||||||
key={state.deviceRef}
|
key={state.deviceRef}
|
||||||
title={state.deviceName}
|
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"}
|
status={state.appliedConfigurationRevisionRef === state.desiredConfigurationRevisionRef ? "applied" : "pending"}
|
||||||
trailing={formatDate(state.updatedAt)}
|
trailing={formatDate(state.updatedAt)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</ResourceList>
|
</ResourceList>
|
||||||
<ControlSection title="Immutable revisions" count={workspace.configurationRevisions.length}>
|
<ControlSection title="История настроек" count={workspace.configurationRevisions.length}>
|
||||||
<ResourceList empty="Configuration revisions отсутствуют.">
|
<ResourceList empty="Версий пока нет">
|
||||||
{workspace.configurationRevisions.map((revision) => (
|
{workspace.configurationRevisions.map((revision) => (
|
||||||
<ResourceRow
|
<ResourceRow
|
||||||
key={revision.configurationRevisionRef}
|
key={revision.configurationRevisionRef}
|
||||||
title={`${revision.deviceName} · revision ${revision.revisionNumber}`}
|
title={`${revision.deviceName} · Версия ${revision.revisionNumber}`}
|
||||||
description={revision.changeSummary || revision.modelProfileRef}
|
description={revision.changeSummary || revision.modelProfileRef}
|
||||||
status="immutable"
|
status="immutable"
|
||||||
trailing={shortDigest(revision.configurationDigest)}
|
trailing={shortDigest(revision.configurationDigest)}
|
||||||
@@ -1205,12 +1153,12 @@ function AdapterPackageDialog(props: DialogBaseProps) {
|
|||||||
const [packageKey, setPackageKey] = useState("");
|
const [packageKey, setPackageKey] = useState("");
|
||||||
const [displayName, setDisplayName] = useState("");
|
const [displayName, setDisplayName] = useState("");
|
||||||
const [publisherRef, setPublisherRef] = 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" });
|
await ensureAdapterPackage({ packageKey, displayName, publisherRef, lifecycleState: "active" });
|
||||||
}}>
|
}}>
|
||||||
<KeyField label="Ключ пакета" value={packageKey} onChange={setPackageKey} />
|
<KeyField label="Ключ пакета" value={packageKey} onChange={setPackageKey} />
|
||||||
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
|
<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>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1237,12 +1185,12 @@ function AdapterVersionDialog({ packages, ...props }: DialogBaseProps & { packag
|
|||||||
lifecycleState: "draft",
|
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="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="Файл адаптера" 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="Контрольная сумма" 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="Версия контракта" value={contractVersion} onChange={(event) => setContractVersion(event.target.value)} required />
|
||||||
<TextField label="Capabilities" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} description="Через запятую" />
|
<TextField label="Возможности" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} description="Через запятую" />
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1262,7 +1210,7 @@ function ModelProfileDialog({ versions, ...props }: DialogBaseProps & { versions
|
|||||||
setVersionRef(versions[0]?.adapterVersionRef ?? "");
|
setVersionRef(versions[0]?.adapterVersionRef ?? "");
|
||||||
}
|
}
|
||||||
}, [versionRef, versions]);
|
}, [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({
|
await registerModelProfile({
|
||||||
adapterVersionRef: versionRef,
|
adapterVersionRef: versionRef,
|
||||||
profileRef,
|
profileRef,
|
||||||
@@ -1277,16 +1225,16 @@ function ModelProfileDialog({ versions, ...props }: DialogBaseProps & { versions
|
|||||||
lifecycleState: "draft",
|
lifecycleState: "draft",
|
||||||
});
|
});
|
||||||
}}>
|
}}>
|
||||||
<Select label="Adapter version" value={versionRef} onChange={setVersionRef} options={versions.map((item) => ({ value: item.adapterVersionRef, label: item.version, description: item.runtimePackageRef }))} />
|
<Select label="Версия адаптера" 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="Идентификатор профиля" value={profileRef} onChange={(event) => setProfileRef(event.target.value)} required />
|
||||||
<TextField label="Schema version" value={schemaVersion} onChange={(event) => setSchemaVersion(event.target.value)} required />
|
<TextField label="Версия схемы" value={schemaVersion} onChange={(event) => setSchemaVersion(event.target.value)} required />
|
||||||
<TextField label="Vendor" value={vendor} onChange={(event) => setVendor(event.target.value)} required />
|
<TextField label="Производитель" value={vendor} onChange={(event) => setVendor(event.target.value)} required />
|
||||||
<TextField label="Model" value={model} onChange={(event) => setModel(event.target.value)} required />
|
<TextField label="Модель" value={model} onChange={(event) => setModel(event.target.value)} required />
|
||||||
<KeyField label="Device type" value={deviceType} onChange={setDeviceType} />
|
<KeyField label="Тип устройства" value={deviceType} onChange={setDeviceType} />
|
||||||
<TextField label="Protocol" value={protocol} onChange={(event) => setProtocol(event.target.value)} required />
|
<TextField label="Протокол" 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="Файл схемы" 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="Контрольная сумма профиля" value={digest} onChange={(event) => setDigest(event.target.value)} required placeholder="sha256:…" />
|
||||||
<TextField label="Capabilities" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} />
|
<TextField label="Возможности" value={capabilities} onChange={(event) => setCapabilities(event.target.value)} />
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1294,7 +1242,7 @@ function AssetDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: s
|
|||||||
const [assetKey, setAssetKey] = useState("");
|
const [assetKey, setAssetKey] = useState("");
|
||||||
const [displayName, setDisplayName] = useState("");
|
const [displayName, setDisplayName] = useState("");
|
||||||
const [assetTypeRef, setAssetTypeRef] = useState("asset-type:delivery-trike");
|
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({
|
await ensureAsset({
|
||||||
projectRef,
|
projectRef,
|
||||||
assetKey,
|
assetKey,
|
||||||
@@ -1303,9 +1251,9 @@ function AssetDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: s
|
|||||||
lifecycleState: "active",
|
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="Название" 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>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1323,7 +1271,7 @@ function AssetBindingDialog({ workspace, ...props }: DialogBaseProps & { workspa
|
|||||||
setAssetRef(workspace.ontology.assets[0]?.assetRef ?? "");
|
setAssetRef(workspace.ontology.assets[0]?.assetRef ?? "");
|
||||||
}
|
}
|
||||||
}, [assetRef, deviceRef, workspace]);
|
}, [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({
|
await ensureAssetBinding({
|
||||||
projectRef: workspace.project.projectRef,
|
projectRef: workspace.project.projectRef,
|
||||||
bindingKey,
|
bindingKey,
|
||||||
@@ -1334,44 +1282,15 @@ function AssetBindingDialog({ workspace, ...props }: DialogBaseProps & { workspa
|
|||||||
provenanceRef,
|
provenanceRef,
|
||||||
});
|
});
|
||||||
}}>
|
}}>
|
||||||
<Select label="Device" value={deviceRef} onChange={setDeviceRef} options={workspace.devices.map((item) => ({ value: item.deviceRef, label: item.displayName, description: item.modelProfileRef }))} />
|
<Select label="Устройство" 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 }))} />
|
<Select label="Объект" 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} />
|
<KeyField label="Код связи" value={bindingKey} onChange={setBindingKey} />
|
||||||
<Select label="Relation" value={bindingKind} onChange={setBindingKind} options={[
|
<Select label="Тип связи" value={bindingKind} onChange={setBindingKind} options={[
|
||||||
{ value: "tracking", label: "Tracking" },
|
{ value: "tracking", label: "Tracking" },
|
||||||
{ value: "installed", label: "Installed" },
|
{ value: "installed", label: "Installed" },
|
||||||
{ value: "assigned", label: "Assigned" },
|
{ value: "assigned", label: "Assigned" },
|
||||||
]} />
|
]} />
|
||||||
<TextField label="Provenance ref" value={provenanceRef} onChange={(event) => setProvenanceRef(event.target.value)} required />
|
<TextField label="Источник сведений" 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}
|
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1401,7 +1320,7 @@ function EndpointDialog({ workspace, initialHostRef, ...props }: DialogBaseProps
|
|||||||
{ value: "monitoring", label: "Monitoring" },
|
{ value: "monitoring", label: "Monitoring" },
|
||||||
{ value: "service", label: "Service" },
|
{ 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>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1427,10 +1346,10 @@ function DeploymentDialog({ workspace, initialHostRef, ...props }: DialogBasePro
|
|||||||
});
|
});
|
||||||
}}>
|
}}>
|
||||||
<Select label="VPS" value={hostRef} onChange={setHostRef} options={hosts.map((item) => ({ value: item.hostRef, label: item.displayName }))} />
|
<Select label="VPS" value={hostRef} onChange={setHostRef} options={hosts.map((item) => ({ value: item.hostRef, label: item.displayName }))} />
|
||||||
<KeyField label="Deployment key" value={deploymentKey} onChange={setDeploymentKey} />
|
<KeyField label="Код развёртывания" value={deploymentKey} onChange={setDeploymentKey} />
|
||||||
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
|
<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="Файл сборки" 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={artifactDigest} onChange={(event) => setArtifactDigest(event.target.value)} required placeholder="sha256:…" />
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1462,21 +1381,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="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="Развёртывание" value={deploymentRef} onChange={setDeploymentRef} options={matchingDeployments.map((item) => ({ value: item.deploymentRef, label: item.displayName }))} />
|
||||||
<Select label="Edge role" value={edgeRef} onChange={setEdgeRef} options={[
|
<Select label="Узел приёма данных" value={edgeRef} onChange={setEdgeRef} options={[
|
||||||
{ value: "", label: "Без Edge registration" },
|
{ value: "", label: "Без привязки к узлу" },
|
||||||
...workspace.edges.map((item) => ({ value: item.edgeRef, label: item.displayName, description: item.channel.runtimeState })),
|
...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="Название" 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>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function HealthObservationDialog({ workspace, ...props }: DialogBaseProps & { workspace: ProjectWorkspace }) {
|
function HealthObservationDialog({ workspace, ...props }: DialogBaseProps & { workspace: ProjectWorkspace }) {
|
||||||
const targets = [
|
const targets = [
|
||||||
...workspace.ontology.hosts.map((item) => ({ value: `host|${item.hostRef}`, label: item.displayName, description: "Host" })),
|
...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: "Service instance" })),
|
...workspace.ontology.serviceInstances.map((item) => ({ value: `service-instance|${item.serviceInstanceRef}`, label: item.displayName, description: "Сервис" })),
|
||||||
];
|
];
|
||||||
const [target, setTarget] = useState(targets[0]?.value ?? "");
|
const [target, setTarget] = useState(targets[0]?.value ?? "");
|
||||||
const [observedState, setObservedState] = useState<"reachable" | "degraded" | "unreachable">("reachable");
|
const [observedState, setObservedState] = useState<"reachable" | "degraded" | "unreachable">("reachable");
|
||||||
@@ -1485,7 +1404,7 @@ function HealthObservationDialog({ workspace, ...props }: DialogBaseProps & { wo
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!targets.some((item) => item.value === target)) setTarget(targets[0]?.value ?? "");
|
if (!targets.some((item) => item.value === target)) setTarget(targets[0]?.value ?? "");
|
||||||
}, [target, targets]);
|
}, [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 [subjectKind, subjectRef] = target.split("|");
|
||||||
const observedAt = new Date();
|
const observedAt = new Date();
|
||||||
const ttl = Number(ttlMinutes);
|
const ttl = Number(ttlMinutes);
|
||||||
@@ -1502,15 +1421,15 @@ function HealthObservationDialog({ workspace, ...props }: DialogBaseProps & { wo
|
|||||||
expiresAt: new Date(observedAt.valueOf() + ttl * 60_000).toISOString(),
|
expiresAt: new Date(observedAt.valueOf() + ttl * 60_000).toISOString(),
|
||||||
});
|
});
|
||||||
}}>
|
}}>
|
||||||
<Select label="Subject" value={target} onChange={setTarget} options={targets} />
|
<Select label="Объект" value={target} onChange={setTarget} options={targets} />
|
||||||
<Select label="Observed state" value={observedState} onChange={setObservedState} options={[
|
<Select label="Состояние" value={observedState} onChange={setObservedState} options={[
|
||||||
{ value: "reachable", label: "Reachable" },
|
{ value: "reachable", label: "Доступен" },
|
||||||
{ value: "degraded", label: "Degraded" },
|
{ value: "degraded", label: "Работает с ошибками" },
|
||||||
{ value: "unreachable", label: "Unreachable" },
|
{ value: "unreachable", label: "Недоступен" },
|
||||||
]} />
|
]} />
|
||||||
<TextField label="TTL, минут" value={ttlMinutes} onChange={(event) => setTtlMinutes(event.target.value)} required inputMode="numeric" />
|
<TextField label="Действует, минут" 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 />
|
<TextAreaField label="Данные наблюдения JSON" value={evidence} onChange={(event) => setEvidence(event.target.value)} required />
|
||||||
<p className="device-manager-card-copy">Это ручное наблюдение с TTL. Автоматический probe должен писать тот же canonical contract от собственного source ref.</p>
|
<p className="device-manager-card-copy">Состояние действует до указанного срока.</p>
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1518,12 +1437,12 @@ function EdgeDialog(props: DialogBaseProps) {
|
|||||||
const [edgeKey, setEdgeKey] = useState("");
|
const [edgeKey, setEdgeKey] = useState("");
|
||||||
const [displayName, setDisplayName] = useState("");
|
const [displayName, setDisplayName] = useState("");
|
||||||
const [deploymentRef, setDeploymentRef] = 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" });
|
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="Название" 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>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1555,12 +1474,12 @@ function RouteDialog({ workspace, ...props }: DialogBaseProps & { workspace: Pro
|
|||||||
lifecycleState: "draft",
|
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 />
|
<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="Узел приёма данных" 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 }))} />
|
<Select label="Профиль модели" 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 />
|
<TextField label="Канал приёма" value={listenerRef} onChange={(event) => setListenerRef(event.target.value)} required />
|
||||||
<p className="device-manager-card-copy">Маршрут создаётся draft. Его activation остаётся отдельным осознанным изменением данных.</p>
|
<p className="device-manager-card-copy">После создания маршрут можно активировать в списке.</p>
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1580,7 +1499,7 @@ function BindingDialog({ workspace, ...props }: DialogBaseProps & { workspace: P
|
|||||||
setSourceValue(sources[0]?.value ?? "");
|
setSourceValue(sources[0]?.value ?? "");
|
||||||
}
|
}
|
||||||
}, [sourceValue, sources]);
|
}, [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("|");
|
const [kind, ref] = sourceValue.split("|");
|
||||||
await ensureDeviceBinding({
|
await ensureDeviceBinding({
|
||||||
projectRef: workspace.project.projectRef,
|
projectRef: workspace.project.projectRef,
|
||||||
@@ -1592,12 +1511,12 @@ function BindingDialog({ workspace, ...props }: DialogBaseProps & { workspace: P
|
|||||||
capabilities: commaList(capabilities),
|
capabilities: commaList(capabilities),
|
||||||
});
|
});
|
||||||
}}>
|
}}>
|
||||||
<Select label="Source" value={sourceValue} onChange={setSourceValue} options={sources} />
|
<Select label="Источник" value={sourceValue} onChange={setSourceValue} options={sources} />
|
||||||
<KeyField label="Binding key" value={bindingKey} onChange={setBindingKey} />
|
<KeyField label="Код связи" value={bindingKey} onChange={setBindingKey} />
|
||||||
<TextField label="Название" value={displayName} onChange={(event) => setDisplayName(event.target.value)} required />
|
<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="Тип приложения" 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="Идентификатор приложения" 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={capabilities} onChange={(event) => setCapabilities(event.target.value)} description="observe, inspect, configure, command" required />
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1607,7 +1526,7 @@ function GrantDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: s
|
|||||||
const [role, setRole] = useState("viewer");
|
const [role, setRole] = useState("viewer");
|
||||||
const [allow, setAllow] = useState("");
|
const [allow, setAllow] = useState("");
|
||||||
const [deny, setDeny] = 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({
|
await upsertProjectGrant({
|
||||||
projectRef,
|
projectRef,
|
||||||
principalKind,
|
principalKind,
|
||||||
@@ -1618,11 +1537,11 @@ function GrantDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: s
|
|||||||
lifecycleState: "active",
|
lifecycleState: "active",
|
||||||
});
|
});
|
||||||
}}>
|
}}>
|
||||||
<Select label="Principal type" value={principalKind} onChange={setPrincipalKind} options={[{ value: "user", label: "User" }, { value: "group", label: "Group" }]} />
|
<Select label="Кому предоставить доступ" value={principalKind} onChange={setPrincipalKind} options={[{ value: "user", label: "Пользователь" }, { value: "group", label: "Группа" }]} />
|
||||||
<TextField label="Principal ref" value={principalRef} onChange={(event) => setPrincipalRef(event.target.value)} required />
|
<TextField label="Идентификатор пользователя или группы" 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" }))} />
|
<Select label="Роль в проекте" 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="Дополнительные разрешения" value={allow} onChange={(event) => setAllow(event.target.value)} description="Опциональные точечные добавления" />
|
||||||
<TextField label="Capability deny" value={deny} onChange={(event) => setDeny(event.target.value)} description="Deny имеет приоритет" />
|
<TextField label="Запреты" value={deny} onChange={(event) => setDeny(event.target.value)} description="Запреты имеют приоритет" />
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1635,7 +1554,7 @@ function ConfigurationDialog({ workspace, ...props }: DialogBaseProps & { worksp
|
|||||||
setDeviceRef(workspace.devices[0]?.deviceRef ?? "");
|
setDeviceRef(workspace.devices[0]?.deviceRef ?? "");
|
||||||
}
|
}
|
||||||
}, [deviceRef, workspace.devices]);
|
}, [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 parsed = JSON.parse(configuration) as Record<string, unknown>;
|
||||||
const created = await createConfigurationRevision({
|
const created = await createConfigurationRevision({
|
||||||
projectRef: workspace.project.projectRef,
|
projectRef: workspace.project.projectRef,
|
||||||
@@ -1649,10 +1568,10 @@ function ConfigurationDialog({ workspace, ...props }: DialogBaseProps & { worksp
|
|||||||
configurationRevisionRef: created.result.configurationRevision.configurationRevisionRef,
|
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 }))} />
|
<Select label="Устройство" 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="Параметры JSON" value={configuration} onChange={(event) => setConfiguration(event.target.value)} required />
|
||||||
<TextAreaField label="Change summary" value={summary} onChange={(event) => setSummary(event.target.value)} />
|
<TextAreaField label="Описание изменений" value={summary} onChange={(event) => setSummary(event.target.value)} />
|
||||||
<p className="device-manager-card-copy">Secret-like keys и значения будут отклонены Core. Сохранение desired не выставляет applied.</p>
|
<p className="device-manager-card-copy">После сохранения конфигурация ожидает подтверждения устройства.</p>
|
||||||
</FormWindow>;
|
</FormWindow>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1713,36 +1632,39 @@ function ControlSection({ title, count, children }: { title: string; count: numb
|
|||||||
|
|
||||||
function ResourceGrid({ children, empty }: { children: ReactNode; empty: string }) {
|
function ResourceGrid({ children, empty }: { children: ReactNode; empty: string }) {
|
||||||
const hasChildren = Array.isArray(children) ? children.length > 0 : Boolean(children);
|
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 }) {
|
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}</>}>
|
const [expanded, setExpanded] = useState(false);
|
||||||
{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>}
|
return <div className="device-control-disclosure">
|
||||||
</SettingsCard>;
|
<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 }) {
|
function ResourceList({ children, empty }: { children: ReactNode; empty: string }) {
|
||||||
const hasChildren = Array.isArray(children) ? children.length > 0 : Boolean(children);
|
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 }) {
|
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">
|
return <CanonicalResourceRow title={title} description={description}
|
||||||
<span className="device-manager-entity__icon"><Icon name="circle" /></span>
|
status={<StatusBadge variant="indicator" tone={statusTone(status)} aria-label={statusLabel(status)} title={statusLabel(status)} />} statusPlacement="leading"
|
||||||
<span className="device-manager-entity__body"><strong>{title}</strong><small>{description}</small></span>
|
metadata={[statusLabel(status), typeof trailing === "string" ? trailing : null].filter(Boolean).join(" · ")}
|
||||||
<span className="device-control-row__status"><StatusBadge tone={statusTone(status)}>{status}</StatusBadge>{typeof trailing === "string" ? <small>{trailing}</small> : trailing}</span>
|
actions={typeof trailing === "string" ? undefined : trailing} />;
|
||||||
</GlassSurface>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function PolicyCard({ label, value }: { label: string; value: string }) {
|
|
||||||
return <GlassSurface padding="md" tone="soft"><small>{label}</small><strong>{value}</strong></GlassSurface>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function commaList(value: string) {
|
function commaList(value: string) {
|
||||||
return [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))].sort();
|
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" {
|
function statusTone(status: string): "neutral" | "success" | "warning" | "danger" {
|
||||||
if (["active", "accepted", "online", "verified", "applied", "recorded", "immutable"].includes(status)) return "success";
|
if (["active", "accepted", "online", "verified", "applied", "recorded", "immutable"].includes(status)) return "success";
|
||||||
if (["absent", "failed", "rejected", "revoked", "retired"].includes(status)) return "danger";
|
if (["absent", "failed", "rejected", "revoked", "retired"].includes(status)) return "danger";
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
|
FeatureSettingsWindow,
|
||||||
ConfirmationModal,
|
ConfirmationModal,
|
||||||
ResourceList,
|
ResourceList,
|
||||||
ResourceRow,
|
ResourceRow,
|
||||||
GlassSurface,
|
|
||||||
Icon,
|
Icon,
|
||||||
IconButton,
|
IconButton,
|
||||||
Select,
|
Select,
|
||||||
@@ -31,6 +31,8 @@ import type {
|
|||||||
SessionView,
|
SessionView,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
|
import { B2TrackerSettings } from "./b2/B2TrackerSettings";
|
||||||
|
import type { TrackerRef } from "./b2/tracker";
|
||||||
import { useB2Inventory } from "./b2/useB2Inventory";
|
import { useB2Inventory } from "./b2/useB2Inventory";
|
||||||
|
|
||||||
export type DeviceInventoryDetailState = {
|
export type DeviceInventoryDetailState = {
|
||||||
@@ -39,52 +41,6 @@ export type DeviceInventoryDetailState = {
|
|||||||
editing: boolean;
|
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({
|
export function DeviceInventoryView({
|
||||||
workspace,
|
workspace,
|
||||||
canClaim,
|
canClaim,
|
||||||
@@ -106,6 +62,7 @@ export function DeviceInventoryView({
|
|||||||
onError: (reason: unknown) => void;
|
onError: (reason: unknown) => void;
|
||||||
onDetailChange: (detail: DeviceInventoryDetailState | null) => 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 b2 = useB2Inventory(workspace.project.projectRef, workspace);
|
||||||
const [typeFilter, setTypeFilter] = useState("all");
|
const [typeFilter, setTypeFilter] = useState("all");
|
||||||
const [archiveTarget, setArchiveTarget] = useState<DeviceView | null>(null);
|
const [archiveTarget, setArchiveTarget] = useState<DeviceView | null>(null);
|
||||||
@@ -155,27 +112,15 @@ export function DeviceInventoryView({
|
|||||||
return () => window.clearInterval(timer);
|
return () => window.clearInterval(timer);
|
||||||
}, [detail?.deviceRef, onError, onPoll]);
|
}, [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))
|
const remoteRows = (b2.data?.items || []).filter(() => !['pending', 'archived', 'active', 'inactive'].includes(statusFilter))
|
||||||
.sort((a, b) => a.name.localeCompare(b.name, 'ru'));
|
.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);
|
const count = workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + (b2.data?.items.length || 0);
|
||||||
return (
|
return (
|
||||||
<div className="device-inventory">
|
<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 () => {
|
<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;
|
if (!archiveTarget || archiving) return;
|
||||||
setArchiving(true);
|
setArchiving(true);
|
||||||
@@ -220,15 +165,15 @@ export function DeviceInventoryView({
|
|||||||
{statusFilter !== 'pending' ? <ResourceList>
|
{statusFilter !== 'pending' ? <ResourceList>
|
||||||
{remoteRows.map((device) => <li key={`${device.hostRef}:${device.id}`}><ResourceRow
|
{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}
|
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
|
{deviceRows.map(({ device, online, lastSeenAt }) => <li key={device.deviceRef}><ResourceRow
|
||||||
icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`}
|
icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`}
|
||||||
description={lastSeenAt ? formatDate(lastSeenAt) : undefined}
|
description={lastSeenAt ? formatDate(lastSeenAt) : undefined}
|
||||||
status={<StatusBadge tone={online ? 'success' : 'neutral'}>{device.lifecycleState === 'suspended' ? 'В архиве' : online ? 'Онлайн' : 'Не в сети'}</StatusBadge>}
|
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>)}
|
{canManageProject && !online ? <Button size="compact" disabled={archiving} onClick={() => setArchiveTarget(device)}>{device.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button> : null}</>} /></li>)}
|
||||||
</ResourceList> : null}
|
</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) ? (
|
{(statusFilter === "pending" || statusFilter === "all" && pendingEnrollments.length > 0) ? (
|
||||||
<section className="device-inventory__pending" aria-label="Ожидают подключения">
|
<section className="device-inventory__pending" aria-label="Ожидают подключения">
|
||||||
@@ -254,9 +199,9 @@ export function DeviceInventoryView({
|
|||||||
<p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p>
|
<p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p>
|
||||||
</SettingsCard>
|
</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>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -407,35 +352,21 @@ function DeviceDetailView({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
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 ref={detailRef} className="device-detail">
|
||||||
<div className="device-detail__header">
|
<div className="device-detail__connection">
|
||||||
<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><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div>
|
<div><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div>
|
||||||
<div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div>
|
<div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div>
|
||||||
<div><span>Протокол</span><strong>{session?.protocol || profile?.protocol || "Нет данных"}</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>{formatDate(session?.lastSeenAt || device.session?.lastSeenAt)}</strong></div>
|
||||||
<div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div>
|
<div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div>
|
||||||
<div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div>
|
<div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div>
|
||||||
</GlassSurface>
|
</div>
|
||||||
|
|
||||||
<div className="device-detail__layout">
|
<div className="device-detail__layout">
|
||||||
<section className="device-detail-section">
|
<section className="device-detail-section">
|
||||||
@@ -465,7 +396,7 @@ function DeviceDetailView({
|
|||||||
? draftValues[item.path]
|
? draftValues[item.path]
|
||||||
: readPath(context, item.path);
|
: readPath(context, item.path);
|
||||||
return (
|
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" ? (
|
{editable && item.valueKind === "boolean" ? (
|
||||||
<Switch
|
<Switch
|
||||||
checked={Boolean(value)}
|
checked={Boolean(value)}
|
||||||
@@ -493,7 +424,7 @@ function DeviceDetailView({
|
|||||||
{item.description ? <small>{item.description}</small> : null}
|
{item.description ? <small>{item.description}</small> : null}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</GlassSurface>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
@@ -524,14 +455,15 @@ function DeviceDetailView({
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<div className="device-detail-section__state">
|
<div className="device-detail-section__state">
|
||||||
<span>Desired</span>
|
<span>Запрошенная конфигурация</span>
|
||||||
<strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong>
|
<strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong>
|
||||||
<span>Applied</span>
|
<span>Подтверждена устройством</span>
|
||||||
<strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong>
|
<strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</FeatureSettingsWindow>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -604,12 +536,12 @@ function AccessNotice({
|
|||||||
commandTransport: ProjectWorkspace["policies"]["commandTransport"];
|
commandTransport: ProjectWorkspace["policies"]["commandTransport"];
|
||||||
}) {
|
}) {
|
||||||
if (access === "read-only") {
|
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") {
|
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 {
|
function latestSession(workspace: ProjectWorkspace, device: DeviceView): SessionView | null {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import {
|
|||||||
Dropdown,
|
Dropdown,
|
||||||
FeatureSettingsWindow,
|
FeatureSettingsWindow,
|
||||||
GlassSurface,
|
GlassSurface,
|
||||||
|
ResourceList,
|
||||||
|
ResourceRow,
|
||||||
HeaderNavigation,
|
HeaderNavigation,
|
||||||
HeaderProfile,
|
HeaderProfile,
|
||||||
HeaderWorkspace,
|
HeaderWorkspace,
|
||||||
@@ -56,12 +58,14 @@ import type {
|
|||||||
ProjectWorkspace,
|
ProjectWorkspace,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
|
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
|
||||||
|
import { B2AddDevice } from "./b2/B2AddDevice";
|
||||||
|
import { B2AddHost } from "./b2/B2AddHost";
|
||||||
|
import { useB2Inventory } from "./b2/useB2Inventory";
|
||||||
import {
|
import {
|
||||||
DeviceControlView,
|
DeviceControlView,
|
||||||
type ControlViewId,
|
type ControlViewId,
|
||||||
} from "./DeviceControlViews";
|
} from "./DeviceControlViews";
|
||||||
import {
|
import {
|
||||||
DeviceDetailHeaderTools,
|
|
||||||
DeviceInventoryView,
|
DeviceInventoryView,
|
||||||
type DeviceInventoryDetailState,
|
type DeviceInventoryDetailState,
|
||||||
} from "./DeviceInventoryView";
|
} from "./DeviceInventoryView";
|
||||||
@@ -99,13 +103,9 @@ const sectionNavigation: Record<PrimarySection, NavigationItem[]> = {
|
|||||||
],
|
],
|
||||||
infrastructure: [
|
infrastructure: [
|
||||||
{ id: "hosts", label: "VPS и хосты", icon: "building", capability: "telemetry.observe" },
|
{ id: "hosts", label: "VPS и хосты", icon: "building", capability: "telemetry.observe" },
|
||||||
{ id: "infrastructure", label: "Edges и маршруты", icon: "globe", capability: "telemetry.observe" },
|
|
||||||
{ id: "catalog", label: "Модели и адаптеры", icon: "database", capability: "project.read" },
|
|
||||||
],
|
],
|
||||||
management: [
|
management: [
|
||||||
{ id: "bindings", label: "Связи с Foundry", icon: "external", capability: "binding.manage" },
|
{ id: "bindings", label: "Связи с Foundry", icon: "external", capability: "binding.manage" },
|
||||||
{ id: "commands", label: "Команды", icon: "target", capability: "command.plan" },
|
|
||||||
{ id: "settings", label: "Конфигурации", icon: "settings", capability: "configuration.read" },
|
|
||||||
],
|
],
|
||||||
administration: [
|
administration: [
|
||||||
{ id: "audit", label: "Аудит", icon: "clipboard", capability: "audit.read" },
|
{ id: "audit", label: "Аудит", icon: "clipboard", capability: "audit.read" },
|
||||||
@@ -190,11 +190,12 @@ export function DeviceManagerApp() {
|
|||||||
const [activeProjectRef, setActiveProjectRef] = useState("");
|
const [activeProjectRef, setActiveProjectRef] = useState("");
|
||||||
const projectRefCurrent = useRef(activeProjectRef);
|
const projectRefCurrent = useRef(activeProjectRef);
|
||||||
projectRefCurrent.current = activeProjectRef;
|
projectRefCurrent.current = activeProjectRef;
|
||||||
const [selectedHostRef, setSelectedHostRef] = useState<string | null>(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [projectDialogOpen, setProjectDialogOpen] = useState(false);
|
const [projectDialogOpen, setProjectDialogOpen] = useState(false);
|
||||||
const [collectionDialogOpen, setCollectionDialogOpen] = useState(false);
|
const [collectionDialogOpen, setCollectionDialogOpen] = useState(false);
|
||||||
|
const [addHostOpen, setAddHostOpen] = useState(false);
|
||||||
|
const [addDeviceOpen, setAddDeviceOpen] = useState(false);
|
||||||
const [enrollmentDialogOpen, setEnrollmentDialogOpen] = useState(false);
|
const [enrollmentDialogOpen, setEnrollmentDialogOpen] = useState(false);
|
||||||
const [claimEnrollment, setClaimEnrollment] = useState<EnrollmentView | null>(null);
|
const [claimEnrollment, setClaimEnrollment] = useState<EnrollmentView | null>(null);
|
||||||
const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);
|
const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);
|
||||||
@@ -234,6 +235,7 @@ export function DeviceManagerApp() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
applyNodedcTheme(document.documentElement, {
|
applyNodedcTheme(document.documentElement, {
|
||||||
theme: presentation.environment.theme,
|
theme: presentation.environment.theme,
|
||||||
|
appearance: "mission",
|
||||||
accent: hexToRgb(presentation.environment.accentHex),
|
accent: hexToRgb(presentation.environment.accentHex),
|
||||||
});
|
});
|
||||||
}, [presentation.environment.accentHex, presentation.environment.theme]);
|
}, [presentation.environment.accentHex, presentation.environment.theme]);
|
||||||
@@ -293,7 +295,6 @@ export function DeviceManagerApp() {
|
|||||||
setInventoryDetail(null);
|
setInventoryDetail(null);
|
||||||
projectRefCurrent.current = projectRef;
|
projectRefCurrent.current = projectRef;
|
||||||
setWorkspace(null);
|
setWorkspace(null);
|
||||||
setSelectedHostRef(null);
|
|
||||||
setActiveProjectRef(projectRef);
|
setActiveProjectRef(projectRef);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -314,7 +315,6 @@ export function DeviceManagerApp() {
|
|||||||
if (ownerRef === activeOwnerRef) return;
|
if (ownerRef === activeOwnerRef) return;
|
||||||
setActiveOwnerRef(ownerRef);
|
setActiveOwnerRef(ownerRef);
|
||||||
setInventoryDetail(null);
|
setInventoryDetail(null);
|
||||||
setSelectedHostRef(null);
|
|
||||||
setWorkspace(null);
|
setWorkspace(null);
|
||||||
const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef);
|
const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef);
|
||||||
if (nextProject) {
|
if (nextProject) {
|
||||||
@@ -348,9 +348,6 @@ export function DeviceManagerApp() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const activeView = visibleNavigationItems.some((item) => item.id === shell.activeView) ? shell.activeView : null;
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<ApplicationShell
|
<ApplicationShell
|
||||||
@@ -416,8 +413,8 @@ export function DeviceManagerApp() {
|
|||||||
{activeSection === "devices" && activeProject ? (
|
{activeSection === "devices" && activeProject ? (
|
||||||
<IconButton
|
<IconButton
|
||||||
label="Подключить устройство"
|
label="Подключить устройство"
|
||||||
disabled={!canEnroll || !workspace?.routes.some((route) => route.lifecycleState === "active")}
|
disabled={!canEnroll}
|
||||||
onClick={() => setEnrollmentDialogOpen(true)}
|
onClick={() => setAddDeviceOpen(true)}
|
||||||
>
|
>
|
||||||
<Icon name="plus" size={16} />
|
<Icon name="plus" size={16} />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
@@ -493,16 +490,10 @@ export function DeviceManagerApp() {
|
|||||||
expanded={shell.contentExpanded}
|
expanded={shell.contentExpanded}
|
||||||
onExpandedChange={shell.setContentExpanded}
|
onExpandedChange={shell.setContentExpanded}
|
||||||
onClose={shell.closeView}
|
onClose={shell.closeView}
|
||||||
headerTools={activeView === "inventory" && selectedInventoryDevice && inventoryDetail ? (
|
utilityActions={[...(activeView === 'inventory' && canEnroll ? [{
|
||||||
<DeviceDetailHeaderTools
|
label: 'Добавить устройство', icon: 'plus' as const, onClick: () => setAddDeviceOpen(true),
|
||||||
device={selectedInventoryDevice}
|
}] : []), ...(activeView === 'hosts' && capabilities.has('infrastructure.manage') ? [{
|
||||||
detail={inventoryDetail}
|
label: 'Добавить VPS', icon: 'plus' as const, onClick: () => setAddHostOpen(true),
|
||||||
canEdit={canConfigure || canManageProject}
|
|
||||||
onDetailChange={setInventoryDetail}
|
|
||||||
/>
|
|
||||||
) : undefined}
|
|
||||||
utilityActions={[...(activeView === "hosts" && selectedHostRef ? [{
|
|
||||||
label: "Вернуться к VPS и хостам", icon: "chevron-left" as const, onClick: () => setSelectedHostRef(null),
|
|
||||||
}] : []), {
|
}] : []), {
|
||||||
label: "Обновить данные",
|
label: "Обновить данные",
|
||||||
icon: "refresh",
|
icon: "refresh",
|
||||||
@@ -511,8 +502,6 @@ export function DeviceManagerApp() {
|
|||||||
>
|
>
|
||||||
<ProjectView
|
<ProjectView
|
||||||
key={activeProjectRef}
|
key={activeProjectRef}
|
||||||
selectedHostRef={selectedHostRef}
|
|
||||||
onSelectHost={setSelectedHostRef}
|
|
||||||
view={activeView}
|
view={activeView}
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
canManageCollections={canManageCollections}
|
canManageCollections={canManageCollections}
|
||||||
@@ -564,6 +553,8 @@ export function DeviceManagerApp() {
|
|||||||
}}
|
}}
|
||||||
onError={(reason) => setError(errorText(reason))}
|
onError={(reason) => setError(errorText(reason))}
|
||||||
/>
|
/>
|
||||||
|
{addDeviceOpen && workspace ? <B2AddDevice key={activeProjectRef} workspace={workspace} onClose={() => setAddDeviceOpen(false)} onCreated={async () => { setAddDeviceOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} onLegacy={workspace.routes.some(route => route.lifecycleState === 'active') ? () => { setAddDeviceOpen(false); setEnrollmentDialogOpen(true); } : undefined} /> : null}
|
||||||
|
{addHostOpen && activeProject ? <B2AddHost key={activeProjectRef} open projectRef={activeProjectRef} onClose={() => setAddHostOpen(false)} onCreated={async () => { setAddHostOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} /> : null}
|
||||||
<EnrollmentDialog
|
<EnrollmentDialog
|
||||||
open={enrollmentDialogOpen}
|
open={enrollmentDialogOpen}
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
@@ -789,19 +780,7 @@ function EnvironmentBackdrop({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Metric({ label, value, detail, tone = "neutral" }: { label: string; value: number; detail: string; tone?: "neutral" | "success" | "warning" }) {
|
function ProjectView({ view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: {
|
||||||
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;
|
|
||||||
view: ViewId;
|
view: ViewId;
|
||||||
workspace: ProjectWorkspace | null;
|
workspace: ProjectWorkspace | null;
|
||||||
canManageCollections: boolean;
|
canManageCollections: boolean;
|
||||||
@@ -820,8 +799,6 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
|
|||||||
if (!workspace) return <div className="device-manager-panel-empty">Загружаем проект…</div>;
|
if (!workspace) return <div className="device-manager-panel-empty">Загружаем проект…</div>;
|
||||||
if (["catalog", "hosts", "infrastructure", "sessions", "bindings", "commands", "audit", "access", "settings"].includes(view)) {
|
if (["catalog", "hosts", "infrastructure", "sessions", "bindings", "commands", "audit", "access", "settings"].includes(view)) {
|
||||||
return <DeviceControlView
|
return <DeviceControlView
|
||||||
selectedHostRef={selectedHostRef}
|
|
||||||
onSelectHost={onSelectHost}
|
|
||||||
view={view as ControlViewId}
|
view={view as ControlViewId}
|
||||||
workspace={workspace}
|
workspace={workspace}
|
||||||
session={session}
|
session={session}
|
||||||
@@ -846,7 +823,7 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
|
|||||||
if (view === "collections") return (
|
if (view === "collections") return (
|
||||||
<div className="device-manager-stack">
|
<div className="device-manager-stack">
|
||||||
<div className="device-manager-panel-toolbar">
|
<div className="device-manager-panel-toolbar">
|
||||||
<p>Коллекции группируют устройства для последующих bindings и задач.</p>
|
<p>Группы устройств проекта.</p>
|
||||||
<Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button>
|
<Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button>
|
||||||
</div>
|
</div>
|
||||||
<EntityList
|
<EntityList
|
||||||
@@ -861,17 +838,27 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
return <ProjectOverview key={workspace.project.projectRef} workspace={workspace} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) {
|
||||||
|
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
|
||||||
|
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 (
|
return (
|
||||||
<div className="device-manager-overview-grid">
|
<ResourceList>
|
||||||
<Metric label="Устройства" value={workspace.devices.length} detail="inventory" />
|
{metrics.map((metric) => (
|
||||||
<Metric label="Quarantine" value={workspace.discoveries.filter((item) => item.lifecycleState === "quarantine").length} detail="safe projection" />
|
<li key={metric.label}>
|
||||||
<Metric label="Коллекции" value={workspace.collections.length} detail="bindings ready" />
|
<ResourceRow title={metric.label} metadata={metric.detail} status={<StatusBadge>{metric.value ?? '—'}</StatusBadge>} />
|
||||||
<SettingsCard title="Права проекта" description={workspace.project.access.projectRole || "read"}>
|
</li>
|
||||||
<div className="device-manager-capabilities">
|
))}
|
||||||
{workspace.project.access.capabilities.map((capability) => <StatusBadge key={capability}>{capability}</StatusBadge>)}
|
</ResourceList>
|
||||||
</div>
|
|
||||||
</SettingsCard>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -954,7 +941,7 @@ function ProjectSettingsDialog({ open, workspace, presentation, onClose, onSaved
|
|||||||
avatarUrl: iconPreview ?? undefined,
|
avatarUrl: iconPreview ?? undefined,
|
||||||
}}
|
}}
|
||||||
sections={[
|
sections={[
|
||||||
{ id: "identity", label: "Идентичность", icon: "profile", group: "Проект" },
|
{ id: "identity", label: "Основное", icon: "profile", group: "Проект" },
|
||||||
{ id: "media", label: "Медиа", icon: "image", group: "Оформление" },
|
{ id: "media", label: "Медиа", icon: "image", group: "Оформление" },
|
||||||
]}
|
]}
|
||||||
activeSection={section}
|
activeSection={section}
|
||||||
@@ -1253,13 +1240,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 }) {
|
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>;
|
if (!items.length) return <div className="device-manager-panel-empty">{empty}</div>;
|
||||||
return <div className="device-manager-entity-list">{items.map((item) => (
|
return <ResourceList>{items.map((item) => <li key={item.id}><ResourceRow
|
||||||
<GlassSurface key={item.id} className="device-manager-entity" padding="md" tone="soft">
|
icon={<Icon name="folder" />} title={item.title} description={item.subtitle}
|
||||||
<span className="device-manager-entity__icon"><Icon name="circle" /></span>
|
status={<StatusBadge tone={item.tone}>{item.status}</StatusBadge>} /></li>)}</ResourceList>;
|
||||||
<span className="device-manager-entity__body"><strong>{item.title}</strong><small>{item.subtitle}</small></span>
|
|
||||||
<StatusBadge tone={item.tone}>{item.status}</StatusBadge>
|
|
||||||
</GlassSurface>
|
|
||||||
))}</div>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: {
|
function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: {
|
||||||
@@ -1299,17 +1282,17 @@ function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated,
|
|||||||
await onCreated();
|
await onCreated();
|
||||||
} catch (reason) { onError(reason); } finally { setPending(false); }
|
} 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>
|
<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}>
|
<form id="device-project-form" className="device-manager-form" onSubmit={submit}>
|
||||||
<Select
|
<Select
|
||||||
label="Контур проекта"
|
label="Владелец проекта"
|
||||||
value={ownerRef}
|
value={ownerRef}
|
||||||
options={ownerScopes.map((scope) => ({
|
options={ownerScopes.map((scope) => ({
|
||||||
value: scope.ownerRef,
|
value: scope.ownerRef,
|
||||||
label: scope.displayName,
|
label: scope.displayName,
|
||||||
description: scope.scopeKind === "company" ? "Коммерческий контур" : "Личный контур",
|
description: scope.scopeKind === "company" ? "Компания" : "Личное пространство",
|
||||||
}))}
|
}))}
|
||||||
onChange={setOwnerRef}
|
onChange={setOwnerRef}
|
||||||
/>
|
/>
|
||||||
@@ -1373,7 +1356,6 @@ function ClaimDialog({ enrollment, project, onClose, onClaimed, onError }: {
|
|||||||
<form id="device-claim-form" className="device-manager-form" onSubmit={submit}>
|
<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={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}" />
|
<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>
|
</form>
|
||||||
</Window>;
|
</Window>;
|
||||||
}
|
}
|
||||||
@@ -1452,7 +1434,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="Ключ 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="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." />
|
<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>
|
</form>
|
||||||
</Window>;
|
</Window>;
|
||||||
}
|
}
|
||||||
@@ -1478,11 +1459,11 @@ function viewTitle(view: ViewId) {
|
|||||||
collections: "Коллекции",
|
collections: "Коллекции",
|
||||||
catalog: "Модели и адаптеры",
|
catalog: "Модели и адаптеры",
|
||||||
hosts: "VPS и хосты",
|
hosts: "VPS и хосты",
|
||||||
infrastructure: "Edges и маршруты",
|
infrastructure: "Узлы и маршруты",
|
||||||
sessions: "Gateway sessions",
|
sessions: "Подключения устройств",
|
||||||
bindings: "Data bindings",
|
bindings: "Связи с Foundry",
|
||||||
commands: "Command ledger",
|
commands: "Команды",
|
||||||
audit: "Immutable audit",
|
audit: "Аудит",
|
||||||
access: "Доступ к проекту",
|
access: "Доступ к проекту",
|
||||||
settings: "Настройки и конфигурации",
|
settings: "Настройки и конфигурации",
|
||||||
})[view];
|
})[view];
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { Button, Icon, Select, SettingsCard, StatusBadge, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
|
||||||
|
import type { ProjectWorkspace } from '../types';
|
||||||
|
import { b2Request } from './api';
|
||||||
|
import { readB2Usb, supportsB2Usb, type UsbSnapshot } from './usb.mjs';
|
||||||
|
import './b2.css';
|
||||||
|
|
||||||
|
type Host = { hostRef: string; name: string; reachable: boolean; contours: Array<{ id: string; name: string }> };
|
||||||
|
type Preview = { number: number; identifier: string; firmware: string; configuration: { record_count: number }; parameters: Record<string, number> };
|
||||||
|
export function B2AddDevice({ workspace, onClose, onCreated, onLegacy }: {
|
||||||
|
workspace: ProjectWorkspace; onClose: () => void; onCreated: () => Promise<void>;
|
||||||
|
onError: (error: unknown) => void; onLegacy?: () => void;
|
||||||
|
}) {
|
||||||
|
const projectRef = workspace.project.projectRef;
|
||||||
|
const [hosts, setHosts] = useState<Host[]>([]), [hostRef, setHostRef] = useState(''), [contourId, setContourId] = useState('');
|
||||||
|
const [name, setName] = useState(''), [method, setMethod] = useState(supportsB2Usb() ? 'usb' : 'manual');
|
||||||
|
const [imei, setImei] = useState(''), [number, setNumber] = useState('');
|
||||||
|
const [profile, setProfile] = useState(''), [profiles, setProfiles] = useState<Array<{ id: string; name: string }>>([]);
|
||||||
|
const [snapshot, setSnapshot] = useState<UsbSnapshot | null>(null), [preview, setPreview] = useState<Preview | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true), [catalogReady, setCatalogReady] = useState(false), [retry, setRetry] = useState(0);
|
||||||
|
const [reading, setReading] = useState(false), [pending, setPending] = useState(false), [error, setError] = useState('');
|
||||||
|
const controller = useRef<AbortController | null>(null), mounted = useRef(true);
|
||||||
|
useEffect(() => { mounted.current = true; return () => { mounted.current = false; controller.current?.abort(); }; }, []);
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true; setLoading(true); setError('');
|
||||||
|
b2Request<{ hosts: Host[] }>(projectRef, '', 'enrollment-options').then(result => {
|
||||||
|
if (!active) return; setHosts(result.hosts);
|
||||||
|
const first = result.hosts.find(host => host.reachable && host.contours.length);
|
||||||
|
setHostRef(first?.hostRef || ''); setContourId(first?.contours[0]?.id || '');
|
||||||
|
}).catch(reason => { if (active) setError(reason.message); }).finally(() => { if (active) setLoading(false); });
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [projectRef, retry]);
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true; setProfiles([]); setProfile(''); setCatalogReady(false); setSnapshot(null); setPreview(null);
|
||||||
|
if (hostRef && contourId) b2Request<{ profiles: Array<{ id: string; name: string }> }>(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'catalog' } })
|
||||||
|
.then(result => { if (active) { setProfiles(result.profiles); setCatalogReady(true); } })
|
||||||
|
.catch(reason => { if (active) setError(reason.message); });
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [projectRef, hostRef, contourId, retry]);
|
||||||
|
const busy = pending || reading;
|
||||||
|
const host = hosts.find(item => item.hostRef === hostRef);
|
||||||
|
const canRegister = workspace.project.access.capabilities.includes('device.claim');
|
||||||
|
const valid = canRegister && catalogReady && Boolean(name.trim()) && (method === 'usb' ? Boolean(snapshot && preview) : /^\d{15}$/.test(imei) && /^\d{1,10}$/.test(number) && Number(number) > 0 && Number(number) <= 4294967295);
|
||||||
|
function close() { if (!pending) { controller.current?.abort(); onClose(); } }
|
||||||
|
async function readUsb() {
|
||||||
|
setError(''); setSnapshot(null); setPreview(null); setReading(true);
|
||||||
|
const abort = new AbortController(); controller.current = abort;
|
||||||
|
try {
|
||||||
|
const observed = await readB2Usb({ signal: abort.signal });
|
||||||
|
if (abort.signal.aborted) return;
|
||||||
|
const result = await b2Request<Preview>(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'inspect', usb: observed } });
|
||||||
|
if (!mounted.current || abort.signal.aborted) return;
|
||||||
|
setSnapshot(observed); setPreview(result); setName(current => current || `ARNavi B2 · ${result.number}`);
|
||||||
|
} catch (reason) { if (mounted.current && !abort.signal.aborted) setError(reason instanceof Error ? reason.message : 'Не удалось прочитать USB.'); }
|
||||||
|
finally { if (mounted.current) setReading(false); }
|
||||||
|
}
|
||||||
|
return <Window open title="Добавить устройство" subtitle={workspace.project.name} size="md" onClose={close} footer={
|
||||||
|
<WindowFooterActions><Button disabled={pending} onClick={close}>Отмена</Button><Button form="b2-add-device" type="submit" disabled={!valid || busy} loading={pending}>Добавить устройство</Button></WindowFooterActions>
|
||||||
|
}>
|
||||||
|
<form id="b2-add-device" className="b2-settings" onSubmit={async event => {
|
||||||
|
event.preventDefault(); if (!valid || busy) return; setPending(true); setError('');
|
||||||
|
try {
|
||||||
|
await b2Request(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'register', name: name.trim(),
|
||||||
|
...(method === 'usb' ? { usb: snapshot } : { imei, number: Number(number) }), ...(profile ? { profile_id: profile } : {}) } });
|
||||||
|
setSnapshot(null); await onCreated();
|
||||||
|
} catch (reason) { setError(reason instanceof Error ? reason.message : 'Не удалось добавить устройство.'); }
|
||||||
|
finally { if (mounted.current) setPending(false); }
|
||||||
|
}}>
|
||||||
|
<Select label="Тип устройства" value="arnavi-b2" disabled={busy} onChange={event => { if (event === 'edge') onLegacy?.(); }} options={[{ value: 'arnavi-b2', label: 'ARNavi B2' }, ...(onLegacy ? [{ value: 'edge', label: 'Устройство через Edge' }] : [])]} />
|
||||||
|
<TextField label="Название" value={name} maxLength={160} required disabled={busy} onChange={event => setName(event.target.value)} />
|
||||||
|
{loading ? <p role="status">Загрузка подключённых VPS…</p> : hosts.some(item => item.reachable && item.contours.length) ? <>
|
||||||
|
<Select label="VPS" value={hostRef} disabled={busy} options={hosts.filter(item => item.reachable && item.contours.length).map(item => ({ value: item.hostRef, label: item.name }))} onChange={event => {
|
||||||
|
setHostRef(event); setContourId(hosts.find(item => item.hostRef === event)?.contours[0]?.id || ''); setError('');
|
||||||
|
}} />
|
||||||
|
{(host?.contours.length || 0) > 1 ? <Select label="Контур проекта" value={contourId} disabled={busy} options={host!.contours.map(item => ({ value: item.id, label: item.name }))} onChange={event => setContourId(event)} /> : null}
|
||||||
|
<Select label="Добавление" value={method} disabled={busy} options={[{ value: 'usb', label: 'Прочитать настройки трекера по USB' }, { value: 'manual', label: 'Ввести IMEI и ID вручную' }]} onChange={event => { setMethod(event); setError(''); }} />
|
||||||
|
<Select label="Профиль настроек" value={profile} disabled={busy || !catalogReady} options={[{ value: '', label: method === 'usb' ? 'Сохранить настройки трекера' : 'Настроить после добавления' }, ...profiles.map(item => ({ value: item.id, label: item.name }))]} onChange={event => setProfile(event)} />
|
||||||
|
{method === 'usb' ? <SettingsCard title="USB на этом компьютере">
|
||||||
|
<div className="b2-settings">
|
||||||
|
<p>{supportsB2Usb() ? 'Подключите один ARNavi B2 и выберите его USB-порт.' : 'Откройте Device Core в Chrome или Edge для чтения USB. Здесь доступен ручной ввод.'}</p>
|
||||||
|
{preview ? <><StatusBadge tone="success">Настройки прочитаны</StatusBadge><p>ARNavi B2 · {preview.number} · IMEI {preview.identifier}<br />Прошивка {preview.firmware} · {preview.configuration.record_count} параметров</p></> : null}
|
||||||
|
<Button disabled={!catalogReady || busy || !supportsB2Usb()} loading={reading} onClick={readUsb}><Icon name="refresh" />{preview ? 'Прочитать повторно' : 'Прочитать настройки по USB'}</Button>
|
||||||
|
</div>
|
||||||
|
</SettingsCard> : <><TextField label="IMEI" value={imei} inputMode="numeric" maxLength={15} required disabled={busy} onChange={event => setImei(event.target.value.trim())} /><TextField label="ID трекера" value={number} inputMode="numeric" maxLength={10} required disabled={busy} onChange={event => setNumber(event.target.value.trim())} /></>}
|
||||||
|
{profile ? <p>Профиль сохранится на VPS. Отправка настроек трекеру — в настройках устройства.</p> : null}
|
||||||
|
</> : <SettingsCard title="Нет VPS для этого проекта"><p>{hosts.some(item => !item.reachable) ? 'Проверьте доступность VPS и связь контура с этим проектом.' : 'Подключите VPS и свяжите контур с этим проектом в разделе «Инфраструктура».'}</p></SettingsCard>}
|
||||||
|
{!canRegister ? <p>Для регистрации устройства нужно право «Принятие устройства» в этом проекте.</p> : null}
|
||||||
|
{error ? <p role="alert">{error}</p> : null}
|
||||||
|
{!loading && (!catalogReady || error) ? <Button disabled={busy} onClick={() => setRetry(value => value + 1)}>Обновить подключения</Button> : null}
|
||||||
|
</form>
|
||||||
|
</Window>;
|
||||||
|
}
|
||||||
@@ -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>;
|
||||||
|
}
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
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, GlassSurface, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
|
||||||
import { loadProjects } from '../api';
|
import { archiveHost, loadProjects } from '../api';
|
||||||
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
|
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
|
||||||
import { b2Request, type B2Status } from './api';
|
import { b2Request, type B2Status, type B2Application } from './api';
|
||||||
import './b2.css';
|
import './b2.css';
|
||||||
|
|
||||||
type Section = 'connection' | 'contours';
|
type Section = 'connection' | 'contours';
|
||||||
type Form = 'contour' | 'application' | 'project' | null;
|
|
||||||
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
|
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
|
||||||
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
|
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
|
||||||
onChanged: () => Promise<void>; onError: (error: unknown) => void;
|
onChanged: () => Promise<void>; onError: (error: unknown) => void;
|
||||||
@@ -15,119 +14,213 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
|||||||
const [section, setSection] = useState<Section>('contours');
|
const [section, setSection] = useState<Section>('contours');
|
||||||
const [status, setStatus] = useState<B2Status | null>(null);
|
const [status, setStatus] = useState<B2Status | null>(null);
|
||||||
const [pending, setPending] = useState('load');
|
const [pending, setPending] = useState('load');
|
||||||
const [connection, setConnection] = useState('');
|
const [connection, setConnection] = useState(''), [importOpen, setImportOpen] = useState(false);
|
||||||
const connectionFile = useRef<HTMLInputElement>(null);
|
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 [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 [access, setAccess] = useState('read');
|
||||||
|
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string; access: string } | null>(null);
|
||||||
|
const [newContour, setNewContour] = useState(false), [contourName, setContourName] = useState('');
|
||||||
|
const [targetProject, setTargetProject] = useState(project.projectRef);
|
||||||
|
const [contourIntent, setContourIntent] = useState<{ id: string; name: string; projectRef: string } | null>(null);
|
||||||
|
const [syncError, setSyncError] = useState('');
|
||||||
|
const [archiveConfirm, setArchiveConfirm] = useState(false);
|
||||||
|
const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null);
|
||||||
|
const [credentialRows, setCredentialRows] = useState<string[]>([]);
|
||||||
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
|
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);
|
const refresh = async () => { const value = await request<B2Status>('status'); setStatus(value); setSyncError(''); return value; };
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let active = true;
|
let active = true;
|
||||||
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
|
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
|
||||||
if (!active) return;
|
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));
|
setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef));
|
||||||
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
|
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
|
||||||
return () => { active = false; };
|
return () => { active = false; };
|
||||||
}, [host.hostRef, project.projectRef]);
|
}, [host.hostRef, project.projectRef]);
|
||||||
async function run(action: string, data: Record<string, unknown> = {}) {
|
useEffect(() => {
|
||||||
|
if (pending) return;
|
||||||
|
let active = true, timer: number;
|
||||||
|
async function sync() {
|
||||||
|
try {
|
||||||
|
if (document.visibilityState === 'visible') {
|
||||||
|
const value = await request<B2Status>('status');
|
||||||
|
if (active) { setStatus(value); setSyncError(''); }
|
||||||
|
}
|
||||||
|
} catch { if (active) setSyncError('Не удалось обновить список VPS. Показаны последние полученные сведения.'); }
|
||||||
|
finally { if (active) timer = window.setTimeout(sync, 30000); }
|
||||||
|
}
|
||||||
|
timer = window.setTimeout(sync, 30000);
|
||||||
|
return () => { active = false; window.clearTimeout(timer); };
|
||||||
|
}, [host.hostRef, project.projectRef, pending]);
|
||||||
|
async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) {
|
||||||
setPending(action);
|
setPending(action);
|
||||||
try {
|
try {
|
||||||
const result = await request<{ connection?: unknown; id?: string }>(action, data);
|
const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string; contourId?: string }>(action, data, requestId);
|
||||||
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2));
|
if (result.connection) {
|
||||||
if (action === 'connect') { setConnection(''); setSection('contours'); }
|
const { integration_id: applicationId, client_id: clientId } = result.connection;
|
||||||
if (action === 'contour-create' && result.id) { setContourId(result.id); setApplicationId(''); }
|
setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) });
|
||||||
if (action === 'application-create' && result.id) setApplicationId(result.id);
|
setKeyRows((rows) => [...new Set([...rows, applicationId])]);
|
||||||
setForm(null); setName(''); setKey('');
|
setCredentialRows((rows) => [...new Set([...rows, clientId])]);
|
||||||
// A successful mutation must not be presented as failed if a subsequent read fails.
|
}
|
||||||
|
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'); }
|
||||||
|
if (action === 'contour-connect') {
|
||||||
|
setNewContour(false); setContourName(''); setContourIntent(null);
|
||||||
|
if (result.contourId) setExpanded(rows => [...new Set([...rows, result.contourId!])]);
|
||||||
|
}
|
||||||
|
setCreating(''); setName(''); setCreationIntent(null);
|
||||||
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
|
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
|
||||||
return true;
|
return true;
|
||||||
} catch (error) { onError(error); return false; } finally { setPending(''); }
|
} catch (error) {
|
||||||
|
const value = await refresh().catch(() => null);
|
||||||
|
const recovered = action === 'application-connect' && requestId
|
||||||
|
? value?.applications?.find(app => app.key === 'app-' + requestId) : null;
|
||||||
|
if (recovered) {
|
||||||
|
setCreating(''); setName(''); setCreationIntent(null);
|
||||||
|
setKeyRows(rows => [...new Set([...rows, recovered.id])]);
|
||||||
|
onError(new Error('Приложение создано, но ключ не получен. Откройте его ключи и выпустите новый. Секрет повторно не показывается.'));
|
||||||
|
} else onError(error);
|
||||||
|
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 busy = Boolean(pending), canManage = status?.authority === 'host';
|
||||||
const begin = (value: Form) => { setForm(value); setName(''); setKey(''); setTargetProject(project.projectRef); };
|
const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id];
|
||||||
const back = () => {
|
|
||||||
setIssued(''); setShowHistory(false);
|
|
||||||
if (form) setForm(null); else if (applicationId) setApplicationId(''); else { setContourId(''); setShowInactive(false); }
|
|
||||||
};
|
|
||||||
function downloadIssuedKey() {
|
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';
|
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);
|
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 ? <>
|
||||||
|
{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>
|
||||||
|
</> : <>
|
||||||
|
<dl className="b2-tracker-facts"><dt>Доступ приложения</dt><dd>{Object.entries(app.grants).map(([contourId, grant]) => `${status?.contours?.find(contour => contour.id === contourId)?.name || contourId}: ${{ read: 'чтение', control: 'чтение и команды', manage: 'управление устройствами' }[grant] || grant}`).join('; ')}</dd></dl>
|
||||||
|
<ResourceList>{app.credentials.map((item) => {
|
||||||
|
const keyOpen = credentialRows.includes(item.client_id);
|
||||||
|
const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null;
|
||||||
|
return <li key={item.client_id} className="b2-disclosure">
|
||||||
|
<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 <>
|
return <>
|
||||||
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
|
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
|
||||||
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
|
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 }]}
|
sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]}
|
||||||
activeSection={section} onSectionChange={(value) => { setSection(value); setForm(null); setIssued(''); }} onClose={onClose}
|
activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||||
footer={<WindowFooterActions>
|
headerActions={<>
|
||||||
{section === 'contours' && (selected || form) ? <IconButton label={form ? 'Отменить создание' : application ? 'К приложениям контура' : 'К списку контуров'} disabled={busy} onClick={back}><Icon name="chevron-left" /></IconButton> : null}
|
{section === 'contours' && canManage ? <IconButton label="Создать контур VPS" disabled={busy} onClick={() => { setNewContour(true); setContourName(''); setTargetProject(project.projectRef); setContourIntent(null); }}><Icon name="plus" /></IconButton> : null}
|
||||||
|
{project.access.capabilities.includes('infrastructure.manage') ? <IconButton label={host.lifecycleState === 'suspended' ? 'Восстановить VPS' : 'Перенести VPS в архив'} disabled={busy} onClick={() => setArchiveConfirm(true)}><Icon name={host.lifecycleState === 'suspended' ? 'refresh' : 'trash'} /></IconButton> : null}
|
||||||
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
|
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
|
||||||
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
|
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
|
||||||
}}><Icon name="refresh" /></IconButton>
|
}}><Icon name="refresh" /></IconButton></>}>
|
||||||
</WindowFooterActions>}>
|
|
||||||
<div className="b2-settings" aria-busy={busy}>
|
<div className="b2-settings" aria-busy={busy}>
|
||||||
|
{syncError ? <p role="status">{syncError}</p> : null}
|
||||||
{section === 'connection' ? <>
|
{section === 'connection' ? <>
|
||||||
<ResourceRow title={host.displayName} description={status?.endpoint} status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Подключение…' : 'Не подключён'}</StatusBadge>} />
|
<ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
|
||||||
<SettingsCard title={status?.connected ? 'Заменить ключ сервера' : 'Подключить сервер'}>
|
status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>}
|
||||||
<div className="b2-settings">
|
actions={<IconButton label="Импортировать ключ доступа Device Core" aria-expanded={importOpen} onClick={() => setImportOpen(!importOpen)}><Icon name="key" /></IconButton>} />
|
||||||
<Button disabled={busy} onClick={() => connectionFile.current?.click()}><Icon name="upload" />Загрузить файл ключа</Button>
|
{importOpen ? <SettingsCard title="Доступ Device Core к VPS" description="Файл доступа выдаёт администратор этого VPS."><div className="b2-settings">
|
||||||
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл ключа подключения VPS" disabled={busy} onChange={async (event) => {
|
<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');
|
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); }
|
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} />
|
<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 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>
|
</div></SettingsCard> : null}
|
||||||
</SettingsCard>
|
|
||||||
</> : null}
|
</> : null}
|
||||||
{section === 'contours' ? <>
|
{section === 'contours' ? <>
|
||||||
<div className="b2-path" aria-label="Текущий раздел">{[host.displayName, selected?.name, application?.name].filter(Boolean).join(' / ')}</div>
|
<h3 id="b2-contours-heading" className="b2-section-heading b2-contours-heading">Контуры</h3>
|
||||||
{form === 'contour' || form === 'application' ? <SettingsCard title={form === 'contour' ? 'Новый контур' : 'Новое приложение'}>
|
{newContour ? <SettingsCard title="Новый контур VPS" description="Создаётся на этом VPS и связывается с выбранным проектом Device Core."><div className="b2-settings">
|
||||||
<div className="b2-settings">
|
<TextField label="Название контура" value={contourName} disabled={busy || Boolean(contourIntent)} maxLength={160} autoFocus onChange={event => setContourName(event.target.value)} />
|
||||||
{form === 'application' ? <ResourceRow title={selected?.name} metadata="Контур" /> : null}
|
<Select label="Проект Device Core" value={targetProject} disabled={busy || Boolean(contourIntent)} options={projects.filter(item => item.access.capabilities.includes('infrastructure.manage')).map(item => ({ value: item.projectRef, label: item.name }))} onChange={setTargetProject} />
|
||||||
<TextField label="Название" value={name} maxLength={160} onChange={(e) => setName(e.target.value)} />
|
<div className="b2-actions"><Button disabled={busy} onClick={() => { setNewContour(false); setContourIntent(null); }}>Отмена</Button><Button disabled={busy || !contourName.trim() || !targetProject} loading={pending === 'contour-connect'} onClick={() => {
|
||||||
<TextField label="Код" value={key} placeholder={form === 'contour' ? 'robot2b' : 'delivery-app'} onChange={(e) => setKey(e.target.value.toLowerCase())} />
|
const intent = contourIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: contourName.trim(), projectRef: targetProject };
|
||||||
<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>
|
setContourIntent(intent); void run('contour-connect', { name: intent.name, targetProjectRef: intent.projectRef }, intent.id);
|
||||||
</div>
|
}}>{contourIntent ? 'Уточнить создание' : 'Создать контур'}</Button></div>
|
||||||
</SettingsCard> : form === 'project' ? <SettingsCard title="Проект Device Core"><div className="b2-settings">
|
</div></SettingsCard> : null}
|
||||||
<ResourceRow title={selected?.name} metadata="Контур VPS" /><Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((p) => ({ value: p.projectRef, label: p.name }))} />
|
{!status?.contours?.length && !busy ? <p>На VPS ещё нет контуров. Создайте первый кнопкой «+» в шапке настроек.</p> : null}
|
||||||
<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>
|
<ResourceList className="b2-contours" aria-labelledby="b2-contours-heading">{(status?.contours || []).map(contour => {
|
||||||
</div></SettingsCard> : !selected ? <SettingsCard title="Контуры" actions={canManage ? <IconButton label="Создать контур" disabled={busy} onClick={() => begin('contour')}><Icon name="plus" /></IconButton> : undefined}>
|
const links = (status?.links || []).filter(link => link.contourId === contour.id);
|
||||||
<ResourceList>{contours.map((item) => {
|
const open = expanded.includes(contour.id);
|
||||||
const link = status?.links?.find((value) => value.contourId === item.id), projectName = projects.find((p) => p.projectRef === link?.projectRef)?.name;
|
const apps = (status?.applications || []).filter(app => app.authority !== 'host' && app.grants[contour.id]);
|
||||||
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>;
|
const available = projects.filter(item => item.access.capabilities.includes('infrastructure.manage') && !links.some(link => link.projectRef === item.projectRef));
|
||||||
})}</ResourceList>{!contours.length ? <p>{pending === 'load' ? 'Загрузка контуров…' : status ? 'Контуров пока нет' : 'Контуры недоступны'}</p> : null}
|
const projectNames = links.map(link => projects.find(item => item.projectRef === link.projectRef)?.name || 'Недоступный проект');
|
||||||
</SettingsCard> : !application ? <>
|
return <li key={contour.id}>
|
||||||
<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>
|
<GlassSurface className="b2-contour" data-expanded={open} materialRim={false}>
|
||||||
<SettingsCard title="Приложения" actions={canManage ? <IconButton label={`Добавить приложение в ${selected.name}`} disabled={busy} onClick={() => begin('application')}><Icon name="plus" /></IconButton> : undefined}>
|
<ResourceRow className="b2-contour__header" title={contour.name} metadata={links.length ? `Проекты: ${projectNames.join(', ')}` : 'Не связан с проектами Device Core'} actions={<>
|
||||||
<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>
|
{open && canManage ? <IconButton label={`Добавить приложение в ${contour.name}`} disabled={busy} onClick={() => { setCreating(contour.id); setName(''); setAccess('read'); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : null}
|
||||||
{!applications.filter((app) => showInactive || !inactive(app)).length ? <p>Нет подключённых приложений</p> : null}
|
<IconButton label={`Контур ${contour.name}`} aria-expanded={open} aria-controls={`contour-${contour.id}`} onClick={() => setExpanded(toggle(expanded, contour.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>
|
||||||
{applications.some(inactive) ? <Button variant="ghost" onClick={() => setShowInactive(!showInactive)}>{showInactive ? 'Скрыть отключённые' : `Отключённые приложения · ${applications.filter(inactive).length}`}</Button> : null}
|
</>} />
|
||||||
</SettingsCard>
|
{open ? <div id={`contour-${contour.id}`} className="b2-disclosure__body">
|
||||||
</> : <>
|
<div className="b2-section-heading"><strong>Проекты Device Core</strong></div>
|
||||||
{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}
|
<p>Связанные проекты видят один реестр устройств этого контура. Ключи внешних приложений управляются отдельно.</p>
|
||||||
<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>}>
|
{links.length ? <ResourceList>{links.map(link => {
|
||||||
<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>
|
const item = projects.find(value => value.projectRef === link.projectRef);
|
||||||
{!application.credentials.some((c) => c.enabled) ? <p>Нет активного ключа</p> : null}
|
return <li key={link.projectRef}><ResourceRow title={item?.name || 'Недоступный проект'} actions={item?.access.capabilities.includes('infrastructure.manage') ? <IconButton label={`Отвязать проект ${item.name}`} disabled={busy} onClick={() => setConfirm({ action: 'unlink', fields: { contourId: contour.id, targetProjectRef: link.projectRef }, text: `Отвязать «${item.name}» от «${contour.name}»? Устройства перестанут отображаться в этом проекте. Контур, устройства и ключи внешних приложений сохранятся.` })}><Icon name="trash" /></IconButton> : undefined} /></li>;
|
||||||
{application.credentials.some((c) => !c.enabled) ? <Button variant="ghost" onClick={() => setShowHistory(!showHistory)}>{showHistory ? 'Скрыть историю' : `История ключей · ${application.credentials.filter((c) => !c.enabled).length}`}</Button> : null}
|
})}</ResourceList> : null}
|
||||||
</SettingsCard>
|
{available.length ? <Select label="Подключить проект к контуру" value="" disabled={busy || (links.length > 0 && !status?.sharedProjects)} options={[{ value: '', label: 'Выбрать проект Device Core' }, ...available.map(item => ({ value: item.projectRef, label: item.name }))]} onChange={projectRef => {
|
||||||
</>}
|
if (projectRef) setConfirm({ action: 'link', fields: { contourId: contour.id, targetProjectRef: projectRef }, text: `Подключить «${projects.find(item => item.projectRef === projectRef)?.name}» к «${contour.name}»? Участники проекта получат доступ к устройствам контура в пределах своих прав проекта.` });
|
||||||
|
}} /> : null}
|
||||||
|
{links.length > 0 && available.length > 0 && !status?.sharedProjects ? <p>Для подключения второго проекта нужна миграция общих контуров на сервере Device Core.</p> : null}
|
||||||
|
<div className="b2-section-heading"><strong>Приложения и ключи</strong></div>
|
||||||
|
<ResourceList>{apps.map(applicationRow)}</ResourceList>
|
||||||
|
{!apps.length && creating !== contour.id ? <p>Ключи приложений ещё не выданы</p> : null}
|
||||||
|
{creating === contour.id ? <div className="b2-settings">
|
||||||
|
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={event => setName(event.target.value)} />
|
||||||
|
<Select label="Доступ приложения" value={access} disabled={busy || Boolean(creationIntent)} options={[{ value: 'read', label: 'Чтение устройств и данных' }, { value: 'control', label: 'Чтение и команды' }, { value: 'manage', label: 'Управление устройствами контура' }]} onChange={setAccess} />
|
||||||
|
<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(), access };
|
||||||
|
setCreationIntent(intent);
|
||||||
|
void run('application-connect', { name: intent.name, contourId: contour.id, access: intent.access }, intent.id);
|
||||||
|
}}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div>
|
||||||
|
</div> : null}
|
||||||
|
</div> : null}
|
||||||
|
</GlassSurface>
|
||||||
|
</li>;
|
||||||
|
})}</ResourceList>
|
||||||
</> : null}
|
</> : null}
|
||||||
</div>
|
</div>
|
||||||
</FeatureSettingsWindow>
|
</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={archiveConfirm} title={host.lifecycleState === 'suspended' ? 'Восстановить VPS?' : 'Перенести VPS в архив?'} description={`${host.displayName}. Изменится только запись в этом проекте. Сервер, устройства и подключения других проектов сохранятся.`} confirmLabel={host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => setArchiveConfirm(false)} onConfirm={async () => {
|
||||||
|
if (busy) return; setPending('archive');
|
||||||
|
try { await archiveHost(project.projectRef, host.hostRef, host.lifecycleState !== 'suspended'); setArchiveConfirm(false); await onChanged(); onClose(); } catch (error) { onError(error); } finally { setPending(''); }
|
||||||
|
}} />
|
||||||
|
<ConfirmationModal open={Boolean(confirm)} title={confirm?.action === 'application-delete' ? 'Удалить приложение' : ['link', 'unlink'].includes(confirm?.action || '') ? 'Связь проекта и контура' : 'Ключ приложения'} 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,145 @@
|
|||||||
|
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),[commandRefresh,setCommandRefresh]=useState(0);
|
||||||
|
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} 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={section==='commands'?'Обновить журнал команд':'Обновить сведения о трекере'} disabled={Boolean(busy)} loading={busy==='refresh'} onClick={()=>void run('refresh',async()=>{if(section==='commands')setCommandRefresh(value=>value+1);await refresh();})}><Icon name="refresh" /></IconButton>}
|
||||||
|
footer={section!=='commands'&§ion!=='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&§ion!=='commands'&§ion!=='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}
|
||||||
|
<B2CommandPanel projectRef={projectRef} device={device} data={data} canCommand={canCommand} active={section==='commands'} refreshKey={commandRefresh} onError={onError} />
|
||||||
|
{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>
|
||||||
|
<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 B2CommandPanel({projectRef,device,data,canCommand,active,refreshKey,onError}:{projectRef:string;device:TrackerRef;data:TrackerState|null;canCommand:boolean;active:boolean;refreshKey:number;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;return()=>{alive.current=false;};},[]);
|
||||||
|
useEffect(()=>{if(active)void refresh().catch(onError);},[active,refreshKey]);
|
||||||
|
useEffect(()=>{if(!active||!rows.some(row=>['queued','dispatched'].includes(row.state)))return;const timer=setTimeout(()=>void refresh().catch(onError),3000);return()=>clearTimeout(timer);},[active,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);}}
|
||||||
|
// Keep the panel mounted across tabs so an uncertain send retains its intent ID.
|
||||||
|
return <div hidden={!active}>
|
||||||
|
<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>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
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; }
|
||||||
@@ -2,17 +2,24 @@ export type B2Contour = { id: string; key: string; name: string; access?: string
|
|||||||
export type B2Application = { id: string; key: string; name: string; authority: 'host' | 'contours';
|
export type B2Application = { id: string; key: string; name: string; authority: 'host' | 'contours';
|
||||||
grants: Record<string, string>; credentials: Array<{ client_id: string; enabled: boolean }> };
|
grants: Record<string, string>; credentials: Array<{ client_id: string; enabled: boolean }> };
|
||||||
export type B2Status = { connected: boolean; endpoint?: string; authority?: 'host' | 'contours';
|
export type B2Status = { connected: boolean; endpoint?: string; authority?: 'host' | 'contours';
|
||||||
|
sharedProjects?: boolean;
|
||||||
contours?: B2Contour[]; applications?: B2Application[];
|
contours?: B2Contour[]; applications?: B2Application[];
|
||||||
links?: Array<{ contourId: string; projectRef: string }> };
|
links?: Array<{ contourId: string; projectRef: string }> };
|
||||||
export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string };
|
export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string };
|
||||||
const messages: Record<string, 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_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.',
|
||||||
b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.',
|
b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.',
|
||||||
|
b2_host_management_required: 'Нужен ключ администратора VPS из установщика. Ключ приложения подходит только для доступа к его контуру.',
|
||||||
|
b2_host_identity_mismatch: 'Сервер не совпадает с идентификатором в файле подключения.',
|
||||||
b2_host_not_connected: 'Сначала подключите VPS.',
|
b2_host_not_connected: 'Сначала подключите VPS.',
|
||||||
b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.',
|
b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.',
|
||||||
b2_key_rejected: 'VPS не принял ключ подключения.',
|
b2_key_rejected: 'VPS не принял ключ подключения.',
|
||||||
b2_conflict: 'На VPS уже есть запись с такими данными. Обновите список и проверьте результат.',
|
b2_conflict: 'На VPS уже есть запись с такими данными. Обновите список и проверьте результат.',
|
||||||
b2_contour_already_linked: 'Этот контур уже связан с другим проектом.',
|
b2_shared_projects_migration_required: 'На сервере Device Core ещё не установлена миграция общих контуров. До её установки контур можно связать только с одним проектом.',
|
||||||
b2_connection_identity_conflict: 'Этот хост уже подключён другим приложением или ключом сервера.',
|
b2_connection_identity_conflict: 'Этот хост уже подключён другим приложением или ключом сервера.',
|
||||||
b2_certificate_mismatch: 'Сертификат VPS не соответствует ключу подключения.',
|
b2_certificate_mismatch: 'Сертификат VPS не соответствует ключу подключения.',
|
||||||
b2_private_storage_unavailable: 'Закрытое хранилище ключей ещё не настроено на Device Core.',
|
b2_private_storage_unavailable: 'Закрытое хранилище ключей ещё не настроено на Device Core.',
|
||||||
@@ -20,13 +27,16 @@ const messages: Record<string, string> = {
|
|||||||
b2_company_mismatch: 'Выберите проект той же компании.',
|
b2_company_mismatch: 'Выберите проект той же компании.',
|
||||||
device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.',
|
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', {
|
const response = await fetch('/api/device-manager/b2/infrastructure', {
|
||||||
method: 'POST', credentials: 'same-origin',
|
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 }),
|
body: JSON.stringify({ projectRef, hostRef, action, ...fields }),
|
||||||
});
|
});
|
||||||
const body = await response.json().catch(() => null);
|
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;
|
return body.result as T;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,3 +3,19 @@
|
|||||||
.b2-path { overflow-wrap: anywhere; }
|
.b2-path { overflow-wrap: anywhere; }
|
||||||
.b2-actions { display: flex; gap: var(--nodedc-space-2); flex-wrap: wrap; justify-content: flex-end; }
|
.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-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-contours-heading { margin: 0; padding-inline: var(--nodedc-space-3); font-weight: var(--nodedc-font-weight-strong); }
|
||||||
|
.b2-contours { gap: var(--nodedc-space-4); }
|
||||||
|
.b2-contour { display: grid; gap: var(--nodedc-space-2); }
|
||||||
|
.b2-contour[data-expanded="false"] { background: transparent; box-shadow: none; }
|
||||||
|
.b2-contour[data-expanded="true"] > .b2-contour__header { background: transparent; }
|
||||||
|
|
||||||
|
.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.5",
|
||||||
|
"filename": "nodedc-arnavi-vps-0.2.5.pyz",
|
||||||
|
"sha256": "d9a822ca7c2498841a6fd13fddac27da4fc22366931ba8980b97c66c159a383f",
|
||||||
|
"bytes": 16129246,
|
||||||
|
"sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git",
|
||||||
|
"sourceCommit": "193253dd48a1c6390ea4c5e500693123b88ce2ea",
|
||||||
|
"manifestSha256": "139a3c1d7f3e8266e2154586783133078311aa9dae76d74ed229aab16f816197",
|
||||||
|
"environment": "ubuntu-24.04-amd64"
|
||||||
|
}
|
||||||
@@ -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') : '—';
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export type UsbSnapshot = { before: Record<string, string>; settings: string; after: Record<string, string> };
|
||||||
|
export function supportsB2Usb(): boolean;
|
||||||
|
export function readB2Usb(options?: { signal?: AbortSignal }): Promise<UsbSnapshot>;
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
/** Read-only B2 transport. The VPS validates the vendor CRC and configuration schema. */
|
||||||
|
export function supportsB2Usb(serial = globalThis.navigator?.serial) {
|
||||||
|
return Boolean(serial?.requestPort);
|
||||||
|
}
|
||||||
|
export async function readB2Usb({ serial = globalThis.navigator?.serial, signal, timeoutMs = 10000 } = {}) {
|
||||||
|
if (!supportsB2Usb(serial)) throw new Error('Чтение USB доступно в Chrome или Edge на этом компьютере. Можно добавить устройство по IMEI и ID.');
|
||||||
|
signal?.throwIfAborted();
|
||||||
|
// Keep the browser chooser in the initiating user gesture.
|
||||||
|
const port = await serial.requestPort({ filters: [{ usbVendorId: 0x2e3c, usbProductId: 0x5740 }] });
|
||||||
|
signal?.throwIfAborted();
|
||||||
|
const info = port.getInfo();
|
||||||
|
if (info.usbVendorId !== 0x2e3c || info.usbProductId !== 0x5740) throw new Error('Выберите USB-порт ARNavi B2.');
|
||||||
|
let reader, writer, pump, opened = false, buffer = '', failure, wake;
|
||||||
|
const encoder = new TextEncoder(), decoder = new TextDecoder('ascii');
|
||||||
|
const notify = () => { wake?.(); wake = undefined; };
|
||||||
|
const abort = () => { failure = new DOMException('Чтение отменено', 'AbortError'); notify(); };
|
||||||
|
signal?.addEventListener('abort', abort, { once: true });
|
||||||
|
try {
|
||||||
|
await port.open({ baudRate: 9600, dataBits: 8, stopBits: 1, parity: 'none', flowControl: 'none' });
|
||||||
|
opened = true; signal?.throwIfAborted();
|
||||||
|
reader = port.readable.getReader(); writer = port.writable.getWriter();
|
||||||
|
pump = (async () => {
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) throw new Error('USB отключён до завершения чтения.');
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
if (buffer.length > 262144) throw new Error('Ответ USB превышает допустимый размер.');
|
||||||
|
notify();
|
||||||
|
}
|
||||||
|
} catch (error) { failure = error; notify(); }
|
||||||
|
})();
|
||||||
|
async function command(bytes, required) {
|
||||||
|
if (failure) throw failure;
|
||||||
|
const offset = buffer.length;
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
// The transport has no configuration-write or physical-control operation.
|
||||||
|
let writeTimer;
|
||||||
|
try {
|
||||||
|
await Promise.race([writer.write(encoder.encode(bytes)), new Promise((_, reject) => {
|
||||||
|
writeTimer = setTimeout(() => reject(new Error('USB-порт не принял запрос.')), timeoutMs);
|
||||||
|
})]);
|
||||||
|
} finally { clearTimeout(writeTimer); }
|
||||||
|
while (true) {
|
||||||
|
if (failure) throw failure;
|
||||||
|
const fields = Object.fromEntries([...buffer.slice(offset).matchAll(/^(?:> )?>([A-Z][A-Z0-9]*)=([^\r\n]*)\r?\n/gm)].map(m => [m[1], m[2]]));
|
||||||
|
if (required.every(key => Object.hasOwn(fields, key))) return Object.fromEntries(required.map(key => [key, fields[key]]));
|
||||||
|
const remaining = deadline - Date.now();
|
||||||
|
if (remaining <= 0) throw new Error('Трекер не ответил по USB. Проверьте кабель и закройте другие программы, использующие этот порт.');
|
||||||
|
await new Promise(resolve => { const timer = setTimeout(() => { wake = undefined; resolve(); }, remaining); wake = () => { clearTimeout(timer); resolve(); }; });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const keys = ['DI', 'DN', 'MN', 'SID0', 'SID1'];
|
||||||
|
const before = await command('>I 7\r\n', keys);
|
||||||
|
if (!/^231;[0-9]{1,5};[0-9]{1,5}(;[0-9]{1,5})?$/.test(before.DI) || !/^\d{15}$/.test(before.MN) || !/^\d{1,10}$/.test(before.DN)) throw new Error('Подключённое устройство не распознано как ARNavi B2.');
|
||||||
|
const settings = (await command('>D 15;0\r\n', ['SF'])).SF;
|
||||||
|
const after = await command('>I 7\r\n', keys);
|
||||||
|
if (keys.some(key => before[key] !== after[key])) throw new Error('Во время чтения изменилось устройство. Повторите чтение USB.');
|
||||||
|
return { before, settings, after };
|
||||||
|
} catch (error) {
|
||||||
|
if (error?.name === 'NotFoundError') throw new Error('USB-порт не выбран.');
|
||||||
|
if (error?.name === 'NetworkError') throw new Error('USB-порт недоступен. Закройте конфигуратор и повторите чтение.');
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
signal?.removeEventListener('abort', abort);
|
||||||
|
if (reader) { await reader.cancel().catch(() => {}); await pump; reader.releaseLock(); }
|
||||||
|
writer?.releaseLock();
|
||||||
|
if (opened) await port.close().catch(() => {});
|
||||||
|
buffer = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 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 type B2Inventory = { items: Array<B2Device & { hostRef: string; hostName: string }>; hosts: B2HostState[] };
|
||||||
export function useB2Inventory(projectRef: string, refreshSignal: unknown) {
|
export function useB2Inventory(projectRef: string, refreshSignal: unknown) {
|
||||||
const [data, setData] = useState<B2Inventory | null>(null);
|
const [snapshot, setSnapshot] = useState<{ projectRef: string; data: B2Inventory | null; error: string } | null>(null);
|
||||||
const [error, setError] = useState('');
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let active = true, timer: ReturnType<typeof setTimeout>;
|
let active = true, timer: ReturnType<typeof setTimeout>;
|
||||||
async function load() {
|
async function load() {
|
||||||
try {
|
try {
|
||||||
const next = await b2Request<B2Inventory>(projectRef, '', 'inventory');
|
const next = await b2Request<B2Inventory>(projectRef, '', 'inventory');
|
||||||
if (active) { setData(next); setError(''); }
|
if (active) setSnapshot({ projectRef, data: next, error: '' });
|
||||||
} catch (reason) {
|
} 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); }
|
} finally { if (active) timer = setTimeout(load, 30_000); }
|
||||||
}
|
}
|
||||||
void load();
|
void load();
|
||||||
return () => { active = false; clearTimeout(timer); };
|
return () => { active = false; clearTimeout(timer); };
|
||||||
}, [projectRef, refreshSignal]);
|
}, [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;
|
||||||
|
}
|
||||||
@@ -5,7 +5,6 @@
|
|||||||
.device-control-toolbar {
|
.device-control-toolbar {
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: 2px 0 14px;
|
padding: 2px 0 14px;
|
||||||
border-bottom: 1px solid var(--nodedc-glass-outline);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-control-toolbar > p {
|
.device-control-toolbar > p {
|
||||||
@@ -42,8 +41,8 @@
|
|||||||
|
|
||||||
.device-control-resource-grid {
|
.device-control-resource-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
gap: var(--nodedc-space-3);
|
||||||
gap: 12px;
|
grid-template-columns: minmax(0, 1fr);
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-control-row {
|
.device-control-row {
|
||||||
@@ -122,9 +121,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.device-control-form {
|
.device-control-form {
|
||||||
max-height: min(62vh, 680px);
|
min-width: 0;
|
||||||
overflow-y: auto;
|
|
||||||
padding-right: 3px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.infrastructure-system-workspace {
|
.infrastructure-system-workspace {
|
||||||
@@ -142,55 +139,9 @@
|
|||||||
.infrastructure-assets-block {
|
.infrastructure-assets-block {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
border-radius: var(--nodedc-radius-card);
|
border-radius: var(--nodedc-radius-card);
|
||||||
background: var(--infrastructure-panel-soft);
|
|
||||||
padding: 1rem;
|
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 {
|
.infrastructure-eyebrow {
|
||||||
display: block;
|
display: block;
|
||||||
color: var(--nodedc-text-muted);
|
color: var(--nodedc-text-muted);
|
||||||
@@ -264,7 +215,6 @@
|
|||||||
.host-monitoring-series {
|
.host-monitoring-series {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
border-radius: var(--nodedc-radius-card);
|
border-radius: var(--nodedc-radius-card);
|
||||||
background: var(--infrastructure-panel-soft);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.infrastructure-count-card {
|
.infrastructure-count-card {
|
||||||
@@ -425,7 +375,6 @@
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0.72rem;
|
padding: 0.72rem;
|
||||||
border-radius: var(--nodedc-radius-control);
|
border-radius: var(--nodedc-radius-control);
|
||||||
background: var(--infrastructure-panel-soft);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.infrastructure-host-card__facts > div {
|
.infrastructure-host-card__facts > div {
|
||||||
@@ -464,7 +413,6 @@
|
|||||||
gap: 0.55rem;
|
gap: 0.55rem;
|
||||||
padding: 0.72rem;
|
padding: 0.72rem;
|
||||||
border-radius: var(--nodedc-radius-control);
|
border-radius: var(--nodedc-radius-control);
|
||||||
background: var(--infrastructure-panel-soft);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.infrastructure-host-relations > section > header {
|
.infrastructure-host-relations > section > header {
|
||||||
@@ -573,7 +521,6 @@
|
|||||||
gap: 0.9rem;
|
gap: 0.9rem;
|
||||||
padding: 0.72rem 0.8rem;
|
padding: 0.72rem 0.8rem;
|
||||||
border-radius: var(--nodedc-radius-control);
|
border-radius: var(--nodedc-radius-control);
|
||||||
background: var(--infrastructure-panel-soft);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.infrastructure-registry-row > div,
|
.infrastructure-registry-row > div,
|
||||||
@@ -610,7 +557,6 @@
|
|||||||
.infrastructure-empty {
|
.infrastructure-empty {
|
||||||
padding: 0.8rem;
|
padding: 0.8rem;
|
||||||
border-radius: var(--nodedc-radius-control);
|
border-radius: var(--nodedc-radius-control);
|
||||||
background: var(--infrastructure-panel-soft);
|
|
||||||
color: var(--nodedc-text-muted);
|
color: var(--nodedc-text-muted);
|
||||||
font-size: 0.65rem;
|
font-size: 0.65rem;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
@@ -696,7 +642,6 @@
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
gap: 0;
|
gap: 0;
|
||||||
border-radius: var(--nodedc-radius-control);
|
border-radius: var(--nodedc-radius-control);
|
||||||
background: var(--infrastructure-panel-soft);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.host-monitoring-hardware-facts dl > div {
|
.host-monitoring-hardware-facts dl > div {
|
||||||
@@ -1277,16 +1222,6 @@ body {
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-manager-overview-grid {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
|
||||||
gap: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.device-manager-overview-grid .nodedc-settings-card {
|
|
||||||
grid-column: 1 / -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.device-manager-capabilities {
|
.device-manager-capabilities {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
@@ -1319,7 +1254,6 @@ body {
|
|||||||
gap: 0.75rem;
|
gap: 0.75rem;
|
||||||
margin-top: 0.45rem;
|
margin-top: 0.45rem;
|
||||||
padding-top: 1rem;
|
padding-top: 1rem;
|
||||||
border-top: 1px solid var(--nodedc-glass-border);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-inventory__section-heading {
|
.device-inventory__section-heading {
|
||||||
@@ -1441,7 +1375,6 @@ body {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.9rem;
|
gap: 0.9rem;
|
||||||
padding-bottom: 1rem;
|
padding-bottom: 1rem;
|
||||||
border-bottom: 1px solid var(--nodedc-glass-border);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-detail__identity {
|
.device-detail__identity {
|
||||||
@@ -1604,7 +1537,6 @@ body {
|
|||||||
display: flex;
|
display: flex;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
gap: 0.55rem;
|
gap: 0.55rem;
|
||||||
border-top: 1px solid var(--nodedc-glass-border);
|
|
||||||
padding-top: 0.85rem;
|
padding-top: 0.85rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1640,7 +1572,6 @@ body {
|
|||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: auto minmax(0, 1fr);
|
grid-template-columns: auto minmax(0, 1fr);
|
||||||
gap: 0.35rem 0.7rem;
|
gap: 0.35rem 0.7rem;
|
||||||
border-top: 1px solid var(--nodedc-glass-border);
|
|
||||||
padding-top: 0.85rem;
|
padding-top: 0.85rem;
|
||||||
color: var(--nodedc-text-secondary);
|
color: var(--nodedc-text-secondary);
|
||||||
font-size: 0.65rem;
|
font-size: 0.65rem;
|
||||||
@@ -1705,14 +1636,6 @@ body {
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
.device-manager-overview-grid {
|
|
||||||
grid-template-columns: 1fr;
|
|
||||||
}
|
|
||||||
|
|
||||||
.device-manager-overview-grid .nodedc-settings-card {
|
|
||||||
grid-column: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.device-inventory-table__head {
|
.device-inventory-table__head {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
@@ -1750,3 +1673,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; }
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"schemaVersion": "nodedc.device-b2-shared-contours.v1",
|
||||||
|
"releaseId": "device-b2-shared-contours-v1-20261001-001",
|
||||||
|
"baselineReleaseId": "device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718",
|
||||||
|
"baselineSha256": "fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe",
|
||||||
|
"files": {
|
||||||
|
"deployment/device-b2-shared-contours-v1.sql": "caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a",
|
||||||
|
"deployment/device-b2-shared-contours-v1.rollback.sql": "f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f"
|
||||||
|
},
|
||||||
|
"transition": "one-contour-many-projects",
|
||||||
|
"services": [],
|
||||||
|
"rollback": "refuse-multiple-projects;preserve-all-rows"
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
begin;
|
||||||
|
set local lock_timeout = '5s';
|
||||||
|
set local statement_timeout = '30s';
|
||||||
|
lock table device_b2_contour_links in access exclusive mode;
|
||||||
|
do $$
|
||||||
|
begin
|
||||||
|
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-shared-contours/v1'
|
||||||
|
or (select pg_get_constraintdef(oid) from pg_constraint
|
||||||
|
where conrelid='device_b2_contour_links'::regclass and contype='p')
|
||||||
|
is distinct from 'PRIMARY KEY (source_id, contour_id, project_id)' then
|
||||||
|
raise exception 'device_b2_shared_contours_rollback_predecessor_mismatch';
|
||||||
|
end if;
|
||||||
|
if exists(select 1 from device_b2_contour_links group by source_id,contour_id having count(*)>1) then
|
||||||
|
raise exception 'device_b2_shared_contours_rollback_would_lose_links';
|
||||||
|
end if;
|
||||||
|
end $$;
|
||||||
|
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
|
||||||
|
alter table device_b2_contour_links add primary key (source_id, contour_id);
|
||||||
|
comment on table device_b2_contour_links is 'nodedc.device-b2-foundation/v1';
|
||||||
|
commit;
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
begin;
|
||||||
|
set local lock_timeout = '5s';
|
||||||
|
set local statement_timeout = '30s';
|
||||||
|
|
||||||
|
-- Separate, versioned foundation transition. Never run from application startup.
|
||||||
|
-- Preserve every assignment; only the identity of an assignment becomes a triple.
|
||||||
|
lock table device_b2_contour_links in access exclusive mode;
|
||||||
|
create temporary table device_b2_links_before on commit drop as
|
||||||
|
select * from device_b2_contour_links;
|
||||||
|
do $$
|
||||||
|
begin
|
||||||
|
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-foundation/v1'
|
||||||
|
or (select pg_get_constraintdef(oid) from pg_constraint
|
||||||
|
where conrelid='device_b2_contour_links'::regclass and contype='p')
|
||||||
|
is distinct from 'PRIMARY KEY (source_id, contour_id)' then
|
||||||
|
raise exception 'device_b2_shared_contours_predecessor_mismatch';
|
||||||
|
end if;
|
||||||
|
end $$;
|
||||||
|
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
|
||||||
|
alter table device_b2_contour_links add primary key (source_id, contour_id, project_id);
|
||||||
|
comment on table device_b2_contour_links is 'nodedc.device-b2-shared-contours/v1';
|
||||||
|
do $$
|
||||||
|
begin
|
||||||
|
if exists(
|
||||||
|
(select * from device_b2_links_before except all select * from device_b2_contour_links)
|
||||||
|
union all
|
||||||
|
(select * from device_b2_contour_links except all select * from device_b2_links_before)
|
||||||
|
) then
|
||||||
|
raise exception 'device_b2_shared_contours_row_preservation_failed';
|
||||||
|
end if;
|
||||||
|
end $$;
|
||||||
|
commit;
|
||||||
@@ -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.
|
||||||
|
Работающее подключение не требует повторного импорта. Это отдельно от ключей
|
||||||
|
приложений внутри контуров; обновление доступа не устанавливает ПО на сервер.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# Device Core B2 user flow investigation
|
||||||
|
|
||||||
|
Date: 2026-10-01. Qualification of local sources, not a production release.
|
||||||
|
|
||||||
|
## Scope and conclusion
|
||||||
|
|
||||||
|
The requested flow is feasible after the local changes and the separately qualified
|
||||||
|
shared-contour schema transition: create a project, import a fresh VPS administrator
|
||||||
|
package, create a contour, issue independent application packages, register devices,
|
||||||
|
discover externally created contours, and bind multiple same-company projects to one
|
||||||
|
contour. Twenty bounded cross-system scenarios passed.
|
||||||
|
|
||||||
|
Two remaining delivery boundaries prevent describing the existing production product
|
||||||
|
as fully qualified from an empty Ubuntu machine to Mission Core:
|
||||||
|
|
||||||
|
1. The existing root deployment runner pins the B2 foundation schema. The new SQL
|
||||||
|
transition and rollback are local qualification inputs, **not registered deployment
|
||||||
|
artifacts**. A separate canonical runner extension, migration registration,
|
||||||
|
acceptance update and reviewed release are required. Never execute these SQL files
|
||||||
|
manually against production or from application startup.
|
||||||
|
2. Current Mission Core accepts the legacy MCV1 pairing format, not the new API v2
|
||||||
|
application JSON. The simulated external client exercises API v2; it does not prove
|
||||||
|
an existing Robot2B or Mission Core interface can import that file.
|
||||||
|
|
||||||
|
No production projects, contours, keys, devices, database migrations, VPS upgrades or
|
||||||
|
physical tracker commands were created or executed during this investigation.
|
||||||
|
|
||||||
|
## Findings and local corrections
|
||||||
|
|
||||||
|
- Settings previously rendered projects as contours and omitted unlinked external
|
||||||
|
VPS contours. They now render the authoritative VPS catalogue, display project
|
||||||
|
associations explicitly, and refresh every 30 seconds while the visible settings
|
||||||
|
window is open. A failed refresh identifies the displayed data as stale.
|
||||||
|
- A new contour can be created with a name and a selected Device Core project.
|
||||||
|
A stable request identity recovers uncertain responses without another contour.
|
||||||
|
- The old primary key `(source_id, contour_id)` and backend conflict rule prohibited
|
||||||
|
a second project. The separate forward transition uses
|
||||||
|
`(source_id, contour_id, project_id)` and preserves existing rows and foreign keys.
|
||||||
|
The old schema remains supported with an explicit migration-required error.
|
||||||
|
- Existing contours can be attached to another authorized project of the same owner
|
||||||
|
scope. A missing host view is created for that project. Unlink deletes only the
|
||||||
|
selected relationship. Cross-company assignment remains forbidden.
|
||||||
|
- Application creation selects the actual contour, no longer the first project link.
|
||||||
|
The UI offers read, control and manage, with read selected by default. An application
|
||||||
|
created before a lost key response is found by its stable identity; the UI directs
|
||||||
|
the operator to issue a replacement instead of pretending the secret is replayable.
|
||||||
|
- VPS v2 catalogue requests now reject a revoked domain client even if OAuth
|
||||||
|
introspection still accepts a cached access token. Previously the contour catalogue
|
||||||
|
could appear healthy but empty; protected fleet operations already denied access.
|
||||||
|
- Project creation calls the owning company/personal space “Владелец проекта”.
|
||||||
|
Device enrollment states that a stored profile still needs to be sent to hardware.
|
||||||
|
|
||||||
|
## Object and permission boundaries
|
||||||
|
|
||||||
|
A VPS contour is the device namespace on the server. A Device Core project is a local
|
||||||
|
workspace with its own members and capabilities. A v2 application is an independently
|
||||||
|
identified external consumer with contour grants and its own credentials/cursors.
|
||||||
|
|
||||||
|
External contours should appear in the administrative catalogue automatically, but
|
||||||
|
must not create Device Core projects, memberships or data grants automatically. Root
|
||||||
|
CLI or host-administrator credentials can create contours. An application's `manage`
|
||||||
|
grant manages devices inside its contour and does not confer VPS administration.
|
||||||
|
|
||||||
|
Multiple projects may share one contour after migration. They see the same device
|
||||||
|
identity, not copies. Project-local unlink/archive must not revoke external application
|
||||||
|
credentials or alter other projects. External applications can share a contour with
|
||||||
|
separate read/control/manage grants and independent event acknowledgments.
|
||||||
|
|
||||||
|
## Reproducible bounded qualification
|
||||||
|
|
||||||
|
From the Device Core repository:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node scripts/qualify-b2-user-flow.mjs \
|
||||||
|
/private/tmp/ndc-b2-sql-check/node_modules/@electric-sql/pglite/dist/index.js \
|
||||||
|
../NODEDC_MISSION_CORE_ARNAVI-VPS \
|
||||||
|
../outputs/device-flow-investigation-20261001/flow-report.json
|
||||||
|
```
|
||||||
|
|
||||||
|
PGlite 0.5.8 is an explicitly supplied test dependency outside the production
|
||||||
|
workspace. The VPS repository path is a qualification input, not a production
|
||||||
|
dependency. The script uses the existing VPS `.venv/bin/python3`.
|
||||||
|
|
||||||
|
Real components: PostgreSQL WASM SQL engine and all 17 Device Core migrations,
|
||||||
|
management repository, B2Infrastructure, private file vault, OAuth client library,
|
||||||
|
VPS SQLite Store, SharedAPI, management domain and CLI parser.
|
||||||
|
|
||||||
|
Simulated boundaries: OAuth provider, TLS network transport, root privilege and
|
||||||
|
hardware. No sockets are opened by the cross-system fixture. Three projects, three
|
||||||
|
external contours and two synthetic devices bound the scenario. Temporary database
|
||||||
|
and credential state is cleaned up; no exported secrets are written to the report.
|
||||||
|
|
||||||
|
The 20 cases include uncertain retries, old-schema rejection, migration preservation,
|
||||||
|
two-project visibility, unrelated-project denial, external CLI discovery, independent
|
||||||
|
applications and cursors, key rotation, lost issuance response, app deletion,
|
||||||
|
cross-company denial, project unlink, restart persistence, audit redaction, rollback
|
||||||
|
refusal when it would lose links, and lossless rollback/reapplication.
|
||||||
|
|
||||||
|
## Validation evidence
|
||||||
|
|
||||||
|
Evidence directory: `../outputs/device-flow-investigation-20261001/`.
|
||||||
|
|
||||||
|
- `flow-report.json`: 20/20 cross-system checks pass.
|
||||||
|
- `device-tests.log`: 303/303 Device Core tests pass.
|
||||||
|
- `vps-tests.log`: 317 VPS tests pass; one temporary loopback socket test is blocked
|
||||||
|
by the sandbox. `vps-network-check.log` confirms that test and the three new
|
||||||
|
revocation cases pass on the permitted rerun. All 318 cases are accounted for.
|
||||||
|
- Final TypeScript/Vite build passes. Node syntax check and `git diff --check` pass.
|
||||||
|
- Ruff passes on the modified VPS module and its new revocation tests.
|
||||||
|
- `ui-checks.txt`, `ui-contours.png`: real changed React settings component tested
|
||||||
|
in an isolated page with synthetic fetch responses. External discovery, shared
|
||||||
|
project labels, explicit linking, grant selection, nested key output, contour
|
||||||
|
creation and close behavior pass. This is not a production browser smoke test.
|
||||||
|
|
||||||
|
Base revisions before local changes:
|
||||||
|
|
||||||
|
- Device Core: `1b3001dfa12598af28882232336d837514502718`
|
||||||
|
- VPS: `5ff082144eb0d2b8ccb46d1d08ead6b52f1d2021`
|
||||||
|
- Mission Core, read only: `a78fdeae66287fa51f2888440d0f5abc0e70364b`
|
||||||
|
|
||||||
|
## Release and remaining acceptance
|
||||||
|
|
||||||
|
1. Register the new foundation transition and exact post-migration schema in the
|
||||||
|
canonical deployment runner; include plan/apply, backup, rollback and acceptance.
|
||||||
|
2. Release Device Core changes. Rebuild/version the VPS installer for the API
|
||||||
|
revocation fix; the currently advertised 0.2.4 installer does not contain it.
|
||||||
|
3. On an isolated Ubuntu Server 24.04 x86-64 host, qualify the actual installer,
|
||||||
|
OAuth service, certificate pinning, restart and uninstall/restore boundaries.
|
||||||
|
4. Repeat the browser flow against those released services and test an API v2
|
||||||
|
consumer. Keep legacy Mission Core MCV1 pairing until its v2 consumer is implemented.
|
||||||
|
|
||||||
|
The reverse schema transition deliberately refuses execution while a contour has
|
||||||
|
multiple project links. Do not delete assignments automatically to force rollback.
|
||||||
|
The private credential vault retains immutable historical files; cleanup of orphaned
|
||||||
|
or superseded secret files was not implemented in this investigation.
|
||||||
|
|
||||||
|
## Release preparation and partial activation, 2026-10-01
|
||||||
|
|
||||||
|
The shared-contour transition now has a fixed three-file descriptor, deterministic
|
||||||
|
builder, bounded SQL locks, transaction-local row-preservation proof, private table
|
||||||
|
backup, exact runtime/source acceptance and lossless automatic rollback in the
|
||||||
|
canonical Platform runner. It remains a separate administrative deployment; the
|
||||||
|
application does not migrate this schema at startup. The reverse transition refuses
|
||||||
|
to remove a second project binding. A table marker without its verified applied
|
||||||
|
archive is insufficient for subsequent application releases.
|
||||||
|
|
||||||
|
Runner source: Platform `27c1552`. Candidate 019 SHA-256:
|
||||||
|
`048b77d0ce97c2179f89bb1c64d4d9915525dfa5b1e71a63fae15450205efeb3`.
|
||||||
|
DCPLATFORM-21 design record: `c8f94c6a-7b57-4ae1-9463-425c5da5f3c6`.
|
||||||
|
At this checkpoint the Synology promotion/migration and Device Core UI release are
|
||||||
|
pending. Live r37 still has the old UI. Do not present the new UI as deployed.
|
||||||
|
|
||||||
|
The independent revocation fix is activated on ARNavi VPS **0.2.5**, source
|
||||||
|
`193253dd48a1c6390ea4c5e500693123b88ce2ea`, installer manifest
|
||||||
|
`139a3c1d7f3e8266e2154586783133078311aa9dae76d74ed229aab16f816197`.
|
||||||
|
The versioned installer returned healthy; read-only before/after proofs preserve
|
||||||
|
host, TLS, owner, devices, contours, applications and credentials. Packet count
|
||||||
|
advanced 5478→5482. The active legacy Mission Core consumer was updated for the
|
||||||
|
0.2.5 contract (`9761474`) through its canonical LaunchAgent; health accepted,
|
||||||
|
VPS state paired, version 0.2.5 and last_error null. No real device command or
|
||||||
|
production key mutation was used for acceptance.
|
||||||
|
|
||||||
|
New evidence directory: `../outputs/device-flow-release-20261001/`.
|
||||||
|
20/20 cross-system checks, 303/303 Device Core tests, 318/318 VPS tests, 75/75
|
||||||
|
Mission Core compatibility tests and production UI build pass. Platform regression
|
||||||
|
suite passed 173 cases; two additional backup/acceptance cases then passed in the
|
||||||
|
13-case focused shared-contour suite. Device artifact run reported 170 cases:
|
||||||
|
153 passed and 17 environment skips, plus one sandbox-blocked health fixture;
|
||||||
|
all four health fixture tests pass on the permitted local-listener rerun. New installer metadata
|
||||||
|
and SHA checks pass. This checkpoint does not add Mission Core API v2 import or
|
||||||
|
claim a clean Ubuntu installation/scale test.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Устройства и VPS: добавление из шапки
|
||||||
|
|
||||||
|
Кнопка в шапке «Устройства» открывает форму на общих компонентах Design Guideline:
|
||||||
|
тип, название, VPS, профиль, USB или ручные IMEI/ID. Эталон композиции — форма
|
||||||
|
добавления независимого устройства в Mission Core. Edge-подключение сохранено
|
||||||
|
отдельным типом там, где у проекта есть активный маршрут.
|
||||||
|
|
||||||
|
Прямое добавление B2 не зависит от Edge. Backend проверяет `device.enroll`,
|
||||||
|
активный хост, связь контура с проектом и идентичность удалённого VPS до передачи
|
||||||
|
запроса. VPS 0.2.4 атомарно сохраняет реестр, профиль и квитанцию; повтор запроса
|
||||||
|
не создаёт дубль. Назначение ранее зарегистрированного устройства не изменяется.
|
||||||
|
|
||||||
|
USB читает операторский браузер через Web Serial, доступный в Chrome/Edge.
|
||||||
|
Пользователь выбирает один порт ARNavi B2. Разрешены только чтения `>I 7` и
|
||||||
|
`>D 15;0`; ответы ограничены по времени и размеру, устройство сверяется до/после,
|
||||||
|
порт закрывается при завершении и отмене. CRC и параметры проверяются VPS тем же
|
||||||
|
кодеком, что использует сервер. Настройки сохраняются, физического применения при
|
||||||
|
добавлении нет. Не поддерживающий Web Serial браузер предлагает ручной ввод.
|
||||||
|
|
||||||
|
«VPS и хосты»: плюс находится в шапке; общие данные/мониторинг раскрываются
|
||||||
|
стрелкой в строке. Архивирование перенесено в круглую корзину настроек VPS,
|
||||||
|
восстановление остаётся доступно в архиве. История ключей раскрывается вместе
|
||||||
|
с приложением, отдельного глазика нет. Жёлтое видео и общие компоненты не менялись.
|
||||||
|
|
||||||
|
Проверки выпуска r32: 300 Node tests, TypeScript; 315 VPS tests (изолированный TCP отдельно
|
||||||
|
вне ограничения loopback песочницы), ruff; 74 теста совместимости Mission Core.
|
||||||
|
Реальная форма Mission Core прочитала B2 по USB: firmware 0.06. Пользователь
|
||||||
|
2026-10-01 подтвердил успешное чтение ARNavi по USB в новой форме Device Core
|
||||||
|
после выдачи браузеру разрешения на устройство. Агент сам этот Web Serial read
|
||||||
|
не выполнял. Установка на чистой Ubuntu остаётся непроверенной; обновление
|
||||||
|
действующего VPS прошло штатным plan/apply.
|
||||||
|
|
||||||
|
## Команды во вкладке настроек
|
||||||
|
|
||||||
|
Кнопка команд в строке трекера открывает единственное окно настроек сразу на
|
||||||
|
вкладке «Команды». В ней находятся выбор и отправка команды, фильтр журнала,
|
||||||
|
состояния, повтор, отмена, история попыток и подгрузка предыдущих записей.
|
||||||
|
Отдельного окна команд и промежуточной ссылки больше нет. Крестик и Escape
|
||||||
|
закрывают настройки целиком. Переключение вкладок сохраняет выбор команды,
|
||||||
|
фильтр и идентификатор незавершённой отправки; возврат обновляет журнал.
|
||||||
|
Кнопка обновления в шапке на вкладке команд обновляет журнал и состояние трекера.
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"NODEDC_DESIGN_GUIDELINE": {
|
"NODEDC_DESIGN_GUIDELINE": {
|
||||||
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
|
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
|
||||||
"commit": "1b63366d2e7a911e18a293d30cddb0c95e0ba653"
|
"commit": "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2"
|
||||||
},
|
},
|
||||||
"NODEDC_LAUNCHER": {
|
"NODEDC_LAUNCHER": {
|
||||||
"url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
|
"url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
},
|
},
|
||||||
"platform": {
|
"platform": {
|
||||||
"url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
|
"url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
|
||||||
"commit": "39a2239563de686d8a854627cae15339f1f2a4d9"
|
"commit": "27c155276a703dd4fd39385011fc5e3f86afcae4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Deterministic data-only, exact shared-contour schema transition."""
|
||||||
|
import argparse
|
||||||
|
import gzip
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import tarfile
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
IDENTITY = 'device-b2-shared-contours-v1-20261001-001'
|
||||||
|
COMPONENT = 'device-b2-shared-contours'
|
||||||
|
DESCRIPTOR = 'deployment/device-b2-shared-contours-v1.json'
|
||||||
|
SQL = 'deployment/device-b2-shared-contours-v1.sql'
|
||||||
|
REVERSE = 'deployment/device-b2-shared-contours-v1.rollback.sql'
|
||||||
|
ENTRIES = (DESCRIPTOR, SQL, REVERSE)
|
||||||
|
HASHES = {
|
||||||
|
SQL: 'caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a',
|
||||||
|
REVERSE: 'f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f',
|
||||||
|
}
|
||||||
|
EXPECTED = {
|
||||||
|
'schemaVersion': 'nodedc.device-b2-shared-contours.v1', 'releaseId': IDENTITY,
|
||||||
|
'baselineReleaseId': 'device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718',
|
||||||
|
'baselineSha256': 'fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe',
|
||||||
|
'files': HASHES, 'transition': 'one-contour-many-projects', 'services': [],
|
||||||
|
'rollback': 'refuse-multiple-projects;preserve-all-rows',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build(destination):
|
||||||
|
if any((ROOT / p).is_symlink() or not (ROOT / p).is_file() for p in ENTRIES):
|
||||||
|
raise ValueError('missing or unsafe transition source')
|
||||||
|
files = {p: (ROOT / p).read_bytes() for p in ENTRIES}
|
||||||
|
if json.loads(files[DESCRIPTOR]) != EXPECTED:
|
||||||
|
raise ValueError('shared contours descriptor mismatch')
|
||||||
|
if any(hashlib.sha256(files[p]).hexdigest() != sha for p, sha in HASHES.items()):
|
||||||
|
raise ValueError('shared contours SQL digest mismatch')
|
||||||
|
payload = {
|
||||||
|
'manifest.env': f'id={IDENTITY}\ncomponent={COMPONENT}\ntype=app-overlay\n'.encode(),
|
||||||
|
'files.txt': ('\n'.join(ENTRIES) + '\n').encode(),
|
||||||
|
**{'payload/' + p: value for p, value in files.items()},
|
||||||
|
}
|
||||||
|
destination = Path(destination)
|
||||||
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with destination.open('xb') as output:
|
||||||
|
with gzip.GzipFile(filename='', mode='wb', fileobj=output, mtime=0) as gz:
|
||||||
|
with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as archive:
|
||||||
|
for name, data in sorted(payload.items()):
|
||||||
|
member = tarfile.TarInfo(name)
|
||||||
|
member.size, member.mode, member.mtime = len(data), 0o644, 0
|
||||||
|
archive.addfile(member, io.BytesIO(data))
|
||||||
|
return {'component': COMPONENT, 'id': IDENTITY, 'artifact': str(destination),
|
||||||
|
'sha256': hashlib.sha256(destination.read_bytes()).hexdigest(), 'entries': ENTRIES,
|
||||||
|
'services': [], 'build': [], 'newPorts': False}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument('--output', required=True)
|
||||||
|
print(json.dumps(build(parser.parse_args().output), indent=2))
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location('shared_builder', Path(__file__).with_name('build_device_b2_shared_contours.py'))
|
||||||
|
B = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(B)
|
||||||
|
|
||||||
|
|
||||||
|
class SharedContoursArtifact(unittest.TestCase):
|
||||||
|
def test_deterministic_data_only_exact_payload_no_overwrite(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
first, second = Path(tmp)/'a.tgz', Path(tmp)/'b.tgz'
|
||||||
|
B.build(first); B.build(second)
|
||||||
|
self.assertEqual(first.read_bytes(), second.read_bytes())
|
||||||
|
with self.assertRaises(FileExistsError): B.build(first)
|
||||||
|
with tarfile.open(first) as archive:
|
||||||
|
self.assertEqual(set(archive.getnames()), {'manifest.env', 'files.txt', *('payload/'+p for p in B.ENTRIES)})
|
||||||
|
self.assertTrue(all(m.isfile() and m.mode == 0o644 for m in archive))
|
||||||
|
self.assertEqual(archive.extractfile('files.txt').read().decode().splitlines(), list(B.ENTRIES))
|
||||||
|
|
||||||
|
def test_mutated_forward_reverse_descriptor_and_symlink_rejected(self):
|
||||||
|
for name in B.ENTRIES:
|
||||||
|
for mode in ('changed', 'symlink'):
|
||||||
|
with self.subTest(name=name, mode=mode), tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root = Path(tmp)/'source'; (root/'deployment').mkdir(parents=True)
|
||||||
|
for p in B.ENTRIES: shutil.copyfile(B.ROOT/p, root/p)
|
||||||
|
if mode == 'symlink':
|
||||||
|
(root/name).unlink(); (root/name).symlink_to(B.ROOT/name)
|
||||||
|
elif name == B.DESCRIPTOR:
|
||||||
|
d = json.loads((root/name).read_text()); d['services'] = ['device-postgres']
|
||||||
|
(root/name).write_text(json.dumps(d))
|
||||||
|
else: (root/name).write_text('drop table device_b2_hosts;')
|
||||||
|
target = Path(tmp)/'bad.tgz'
|
||||||
|
with mock.patch.object(B, 'ROOT', root), self.assertRaises(ValueError): B.build(target)
|
||||||
|
self.assertFalse(target.exists())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__': unittest.main()
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
"""Isolated domain bridge for qualification, never a deployed server.
|
||||||
|
|
||||||
|
Actual VPS SQLite, SharedAPI, CLI and permission code. OAuth provider and root
|
||||||
|
privilege are simulated; no network socket, production state or hardware.
|
||||||
|
Pass the independently checked-out VPS repository as argv[1].
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
from urllib.parse import urlsplit, unquote_plus
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(sys.argv[1]).resolve() / "server"))
|
||||||
|
from ndc_vps import admin
|
||||||
|
from ndc_vps.access_admin import provision
|
||||||
|
from ndc_vps.contours import Conflict
|
||||||
|
from ndc_vps.host_management import HostManagement, bootstrap
|
||||||
|
from ndc_vps.service import Service
|
||||||
|
from ndc_vps.shared_api import SharedAPI
|
||||||
|
from ndc_vps.store import Store
|
||||||
|
|
||||||
|
|
||||||
|
class Provider:
|
||||||
|
def __init__(self):
|
||||||
|
self.clients, self.tokens = {}, {}
|
||||||
|
|
||||||
|
def create(self, client, *_):
|
||||||
|
secret = "synthetic-" + uuid.uuid4().hex
|
||||||
|
self.clients[client] = secret
|
||||||
|
return secret
|
||||||
|
|
||||||
|
def token(self, authorization):
|
||||||
|
client, secret = base64.b64decode(authorization.removeprefix("Basic ")).decode().split(":", 1)
|
||||||
|
client, secret = unquote_plus(client), unquote_plus(secret)
|
||||||
|
if self.clients.get(client) != secret:
|
||||||
|
raise ValueError(f"synthetic credential mismatch known={client in self.clients} secret_length={len(secret)}")
|
||||||
|
token = "synthetic-" + uuid.uuid4().hex
|
||||||
|
self.tokens[token] = client
|
||||||
|
return dict(access_token=token, token_type="Bearer", expires_in=300)
|
||||||
|
|
||||||
|
def authenticate(self, token):
|
||||||
|
if token not in self.tokens:
|
||||||
|
raise PermissionError
|
||||||
|
return self.tokens[token]
|
||||||
|
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory(prefix="b2-flow-vps-") as temporary:
|
||||||
|
root = Path(temporary)
|
||||||
|
state = root / "state"
|
||||||
|
state.mkdir(mode=0o700)
|
||||||
|
exports = root / "exports"
|
||||||
|
exports.mkdir(mode=0o700)
|
||||||
|
(state / "host.json").write_text(json.dumps(dict(
|
||||||
|
host_id="vps_synthetic_flow", fingerprint="a" * 64,
|
||||||
|
endpoint="https://vps.example.invalid:19443", api_port=19443,
|
||||||
|
tracker=dict(host="vps.example.invalid", port=9922))))
|
||||||
|
store = Store(state)
|
||||||
|
store.contours.enable_fresh()
|
||||||
|
with store.db(write=True) as db:
|
||||||
|
db.execute("INSERT INTO state VALUES('b2_authority_v1',?)", (json.dumps(dict(admin_port=4445, public_port=4444)),))
|
||||||
|
provider = Provider()
|
||||||
|
administrator = bootstrap(store, "device-core-admin", "Device Core")
|
||||||
|
package = provision(store, provider, administrator, issuer=store.config["endpoint"])
|
||||||
|
service = Service(store)
|
||||||
|
api = SharedAPI(service, provider, HostManagement(store, provider))
|
||||||
|
for line in sys.stdin:
|
||||||
|
request = json.loads(line)
|
||||||
|
try:
|
||||||
|
kind = request["kind"]
|
||||||
|
if kind == "bootstrap":
|
||||||
|
result = package
|
||||||
|
elif kind == "http":
|
||||||
|
route = urlsplit(request["url"])
|
||||||
|
headers = request.get("headers", {})
|
||||||
|
if route.path == "/oauth2/token":
|
||||||
|
result = provider.token(headers["authorization"])
|
||||||
|
else:
|
||||||
|
result = api.dispatch(request["method"], route, request.get("body"), headers.get("authorization", "").removeprefix("Bearer "))
|
||||||
|
elif kind == "cli":
|
||||||
|
output = io.StringIO()
|
||||||
|
# Exercise the real parser and domain calls, with local root simulated.
|
||||||
|
args = ["--state", str(state), *request["args"]]
|
||||||
|
if request["args"][0] == "key-issue":
|
||||||
|
args += ["--output", str(exports / (uuid.uuid4().hex + ".json"))]
|
||||||
|
with patch.object(admin.os, "geteuid", return_value=0), patch.object(admin, "HydraAdmin", return_value=provider), contextlib.redirect_stdout(output):
|
||||||
|
admin.main(args)
|
||||||
|
result = json.loads(output.getvalue())
|
||||||
|
if "saved" in result:
|
||||||
|
result = json.loads(Path(result["saved"]).read_text())
|
||||||
|
elif kind == "append":
|
||||||
|
result = store.append(request["imei"], b"synthetic", [])
|
||||||
|
elif kind == "restart":
|
||||||
|
store = Store(state)
|
||||||
|
service = Service(store)
|
||||||
|
api = SharedAPI(service, provider, HostManagement(store, provider))
|
||||||
|
result = dict(ok=True)
|
||||||
|
else:
|
||||||
|
raise ValueError("fixture request")
|
||||||
|
response = dict(ok=True, result=result)
|
||||||
|
except (PermissionError, Conflict, ValueError) as error:
|
||||||
|
response = dict(ok=False, status=403 if isinstance(error, PermissionError) else 409 if isinstance(error, Conflict) else 400, error=type(error).__name__)
|
||||||
|
except Exception as error:
|
||||||
|
response = dict(ok=False, status=500, error=type(error).__name__, detail=str(error))
|
||||||
|
print(json.dumps(response), flush=True)
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
// Bounded cross-repository qualification on private temporary data, no sockets.
|
||||||
|
// node scripts/qualify-b2-user-flow.mjs <pglite-index.js> <VPS-repository> <report.json>
|
||||||
|
// PostgreSQL WASM + real Device Core repository + real VPS SQLite/API/CLI.
|
||||||
|
// OAuth provider, TLS transport, root privilege and hardware are simulated.
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { createInterface } from 'node:readline';
|
||||||
|
import { readFile, readdir, writeFile, mkdtemp, rm } from 'node:fs/promises';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
import { resolve, join } from 'node:path';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { randomUUID, createHash } from 'node:crypto';
|
||||||
|
import { PostgresDeviceRepository } from '../services/device-control-core/src/postgres-repository.mjs';
|
||||||
|
import { normalizeManagementCommand } from '../services/device-control-core/src/project-management.mjs';
|
||||||
|
import { B2Infrastructure } from '../services/device-control-core/src/b2/infrastructure.mjs';
|
||||||
|
import { B2Secrets } from '../services/device-control-core/src/b2/vault.mjs';
|
||||||
|
import { createB2Client } from '../services/device-control-core/src/b2/connection.mjs';
|
||||||
|
|
||||||
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||||
|
const vps = resolve(process.argv[3]);
|
||||||
|
const { PGlite } = await import(pathToFileURL(resolve(process.argv[2])));
|
||||||
|
const db = new PGlite();
|
||||||
|
const child = spawn(join(vps, '.venv/bin/python3'), [join(root, 'scripts/b2-flow-vps-fixture.py'), vps], { stdio: ['pipe', 'pipe', 'pipe'] });
|
||||||
|
const waiting = [];
|
||||||
|
let childError = '';
|
||||||
|
child.stderr.on('data', data => { childError += data; });
|
||||||
|
createInterface({ input: child.stdout }).on('line', line => waiting.shift()?.resolve(JSON.parse(line)));
|
||||||
|
child.on('exit', code => { for (const item of waiting.splice(0)) item.reject(Error(`VPS fixture exited ${code}: ${childError}`)); });
|
||||||
|
const bridge = body => new Promise((resolve, reject) => { waiting.push({ resolve, reject }); child.stdin.write(JSON.stringify(body) + '\n'); });
|
||||||
|
async function command(body) {
|
||||||
|
const result = await bridge(body);
|
||||||
|
assert.equal(result.ok, true, JSON.stringify({ status: result.status, error: result.error, detail: result.detail }));
|
||||||
|
return result.result;
|
||||||
|
}
|
||||||
|
const secretsRoot = await mkdtemp(join(tmpdir(), 'b2-flow-secrets-'));
|
||||||
|
const checks = [];
|
||||||
|
async function check(name, action) { await action(); checks.push({ name, result: 'pass' }); console.log('PASS ' + name); }
|
||||||
|
const pool = { connect: async () => ({ query: (...args) => db.query(...args), release() {} }), query: (...args) => db.query(...args), end: async () => {} };
|
||||||
|
const repository = new PostgresDeviceRepository({ pool });
|
||||||
|
const owner = { scopeKind: 'company', ownerRef: 'company:flow-fixture' };
|
||||||
|
const actor = { userRef: 'user:flow-owner', hubRole: 'owner', groupRefs: [], ownerScopes: [owner] };
|
||||||
|
const clientFactory = pkg => createB2Client(pkg, { fetchImpl: async (url, init) => {
|
||||||
|
const headers = Object.fromEntries(new Headers(init.headers));
|
||||||
|
const body = String(url).includes('/oauth2/token') ? null : init.body ? JSON.parse(init.body) : null;
|
||||||
|
const response = await bridge({ kind: 'http', url: String(url), method: init.method || 'GET', headers, body });
|
||||||
|
return new Response(JSON.stringify(response.ok ? response.result : { error: response.error }), {
|
||||||
|
status: response.ok ? 200 : response.status, headers: { 'content-type': 'application/json' },
|
||||||
|
});
|
||||||
|
} });
|
||||||
|
const service = new B2Infrastructure({ pool, secrets: new B2Secrets(secretsRoot), clientFactory });
|
||||||
|
const requestId = () => randomUUID().replaceAll('-', '');
|
||||||
|
async function management(commandKind, input, as = actor) {
|
||||||
|
const command = normalizeManagementCommand(commandKind, input);
|
||||||
|
return (await repository.executeManagementCommand({ actor: as, commandKind, command,
|
||||||
|
idempotencyKey: requestId(), requestDigest: 'sha256:' + createHash('sha256').update(JSON.stringify(command)).digest('hex') })).result;
|
||||||
|
}
|
||||||
|
const execute = (common, action, fields = {}, id = requestId(), as = actor) => service.execute(as, { ...common, action, ...fields }, id);
|
||||||
|
const cli = args => command({ kind: 'cli', args });
|
||||||
|
let projectA, projectB, projectC, host, contour, pkg, appA, appB, appClientA, appClientB, device;
|
||||||
|
let common, second, third;
|
||||||
|
try {
|
||||||
|
await check('fresh schema and project creation use the real management repository', async () => {
|
||||||
|
for (const name of (await readdir(join(root, 'services/device-control-core/migrations'))).filter(name => name.endsWith('.sql')).sort()) {
|
||||||
|
await db.exec(await readFile(join(root, 'services/device-control-core/migrations', name), 'utf8'));
|
||||||
|
}
|
||||||
|
await db.exec(await readFile(join(root, 'deployment/device-b2-foundation-v1.sql'), 'utf8'));
|
||||||
|
await management('owner_scope.ensure', { ...owner, displayName: 'Flow fixture' });
|
||||||
|
for (const [key, name] of [['first', 'Project A'], ['second', 'Project B'], ['unlinked', 'Project C']]) {
|
||||||
|
const value = await management('project.ensure', { ...owner, projectKey: key, name });
|
||||||
|
if (key === 'first') projectA = value.project.projectRef;
|
||||||
|
if (key === 'second') projectB = value.project.projectRef;
|
||||||
|
if (key === 'unlinked') projectC = value.project.projectRef;
|
||||||
|
}
|
||||||
|
assert.equal((await repository.listAccessibleProjects(actor)).length, 3);
|
||||||
|
});
|
||||||
|
await check('empty VPS registers through onboarding and repeated import reuses host', async () => {
|
||||||
|
pkg = await command({ kind: 'bootstrap' });
|
||||||
|
host = await execute({ projectRef: projectA }, 'register-host', { name: 'New ARNavi VPS', connection: pkg });
|
||||||
|
const repeated = await execute({ projectRef: projectA }, 'register-host', { name: 'New ARNavi VPS', connection: pkg });
|
||||||
|
assert.equal(repeated.hostRef, host.hostRef);
|
||||||
|
common = { projectRef: projectA, hostRef: host.hostRef };
|
||||||
|
const status = await execute(common, 'status');
|
||||||
|
assert.deepEqual(status.contours, []);
|
||||||
|
assert.equal(status.sharedProjects, false);
|
||||||
|
});
|
||||||
|
await check('new contour creates and binds with stable retry identity', async () => {
|
||||||
|
const id = requestId();
|
||||||
|
contour = (await execute(common, 'contour-connect', { name: 'Shared fleet', targetProjectRef: projectA }, id)).contourId;
|
||||||
|
assert.equal((await execute(common, 'contour-connect', { name: 'Shared fleet', targetProjectRef: projectA }, id)).contourId, contour);
|
||||||
|
assert.equal((await execute(common, 'status')).contours.length, 1);
|
||||||
|
});
|
||||||
|
await check('old schema refuses sharing explicitly and forward migration preserves old links', async () => {
|
||||||
|
await assert.rejects(execute(common, 'link', { contourId: contour, targetProjectRef: projectB }), /b2_shared_projects_migration_required/);
|
||||||
|
const before = (await db.query('select * from device_b2_contour_links')).rows;
|
||||||
|
await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.sql'), 'utf8'));
|
||||||
|
assert.deepEqual((await db.query('select * from device_b2_contour_links')).rows, before);
|
||||||
|
assert.equal((await execute(common, 'status')).sharedProjects, true);
|
||||||
|
});
|
||||||
|
await check('one contour links to two projects with separate host views and idempotent edges', async () => {
|
||||||
|
await execute(common, 'link', { contourId: contour, targetProjectRef: projectB });
|
||||||
|
await execute(common, 'link', { contourId: contour, targetProjectRef: projectB });
|
||||||
|
const links = (await execute(common, 'status')).links;
|
||||||
|
assert.equal(links.length, 2);
|
||||||
|
const view = (await db.query('select host_id from device_b2_host_views where project_id=$1', [projectB.slice(8)])).rows[0];
|
||||||
|
second = { projectRef: projectB, hostRef: 'host:' + view.host_id };
|
||||||
|
assert.notEqual(second.hostRef, common.hostRef);
|
||||||
|
assert.equal((await db.query('select * from device_b2_hosts')).rows.length, 1);
|
||||||
|
});
|
||||||
|
await check('unlinked project can add the shared VPS without seeing another fleet', async () => {
|
||||||
|
const other = await execute({ projectRef: projectC }, 'register-host', { name: 'Same VPS', connection: pkg });
|
||||||
|
third = { projectRef: projectC, hostRef: other.hostRef };
|
||||||
|
assert.deepEqual((await execute(third, 'inventory')).items, []);
|
||||||
|
});
|
||||||
|
await check('two independent application packages connect to the same contour', async () => {
|
||||||
|
appA = await execute(common, 'application-connect', { name: 'Partner management', contourId: contour, access: 'manage' });
|
||||||
|
appB = await execute(common, 'application-connect', { name: 'Partner observer', contourId: contour, access: 'read' });
|
||||||
|
assert.notEqual(appA.connection.client_id, appB.connection.client_id);
|
||||||
|
assert.notEqual(appA.id, appB.id);
|
||||||
|
appClientA = clientFactory(appA.connection); appClientB = clientFactory(appB.connection);
|
||||||
|
assert.deepEqual((await appClientA.call('/v2/contours')).items.map(item => item.id), [contour]);
|
||||||
|
assert.deepEqual((await appClientB.call('/v2/contours')).items.map(item => item.id), [contour]);
|
||||||
|
await assert.rejects(appClientA.call('/v2/management'), /b2_access_denied/);
|
||||||
|
await assert.rejects(execute(third, 'register-host', { name: 'Wrong role', connection: appA.connection }), /b2_host_management_required/);
|
||||||
|
});
|
||||||
|
await check('manual device enrollment works and duplicate retry creates no second device', async () => {
|
||||||
|
const options = await execute(common, 'enrollment-options');
|
||||||
|
assert.equal(options.hosts[0].contours[0].id, contour);
|
||||||
|
const fields = { contourId: contour, request: { action: 'register', name: 'Synthetic ARNavi B2', imei: '123456789012345', number: 1001 } };
|
||||||
|
device = await execute(common, 'enrollment', fields);
|
||||||
|
assert.deepEqual(await execute(common, 'enrollment', fields), device);
|
||||||
|
await assert.rejects(appClientB.call(`/v2/contours/${contour}/enrollment`, fields.request), /b2_access_denied/);
|
||||||
|
assert.equal((await appClientA.call(`/v2/contours/${contour}/devices`)).items.length, 1);
|
||||||
|
});
|
||||||
|
await check('both projects see the same device while an unlinked project sees none', async () => {
|
||||||
|
const a = await execute(common, 'inventory'), b = await execute(second, 'inventory'), c = await execute(third, 'inventory');
|
||||||
|
assert.equal(a.items[0].id, b.items[0].id);
|
||||||
|
assert.equal(a.items.length, 1); assert.equal(b.items.length, 1); assert.equal(c.items.length, 0);
|
||||||
|
assert.equal(JSON.stringify(a).includes('123456789012345'), false);
|
||||||
|
await assert.rejects(execute(third, 'enrollment', { contourId: contour, request: { action: 'catalog' } }), /b2_access_denied/);
|
||||||
|
});
|
||||||
|
await check('independent application cursors cannot consume or acknowledge each other', async () => {
|
||||||
|
const base = `/v2/contours/${contour}/subscriptions`;
|
||||||
|
const a = await appClientA.call(base, { stream: 'registry' });
|
||||||
|
const b = await appClientB.call(base, { stream: 'registry' });
|
||||||
|
assert.notEqual(a.id, b.id);
|
||||||
|
const first = await appClientA.call(`${base}/${a.id}`);
|
||||||
|
assert.ok(first.items.length > 0);
|
||||||
|
await appClientA.call(`${base}/${a.id}/ack`, { through: first.through });
|
||||||
|
assert.equal((await appClientA.call(`${base}/${a.id}`)).items.length, 0);
|
||||||
|
assert.equal((await appClientB.call(`${base}/${b.id}`)).items.length, first.items.length);
|
||||||
|
await assert.rejects(appClientB.call(`${base}/${a.id}`), /b2_access_denied/);
|
||||||
|
});
|
||||||
|
await check('external CLI contours appear in catalogue without automatic local access grants', async () => {
|
||||||
|
const before = (await repository.listAccessibleProjects(actor)).length;
|
||||||
|
for (let n = 1; n <= 3; n++) await cli(['contour-create', `external-${n}`, '--name', `External ${n}`]);
|
||||||
|
const status = await execute(common, 'status');
|
||||||
|
assert.equal(status.contours.length, 4);
|
||||||
|
assert.equal(status.links.length, 2);
|
||||||
|
assert.equal((await repository.listAccessibleProjects(actor)).length, before);
|
||||||
|
const external = status.contours.find(item => item.key === 'external-1');
|
||||||
|
await assert.rejects(appClientA.call(`/v2/contours/${external.id}/devices`), /b2_access_denied/);
|
||||||
|
await execute(common, 'link', { contourId: external.id, targetProjectRef: projectA });
|
||||||
|
assert.equal((await execute(common, 'enrollment-options')).hosts[0].contours.length, 2);
|
||||||
|
const application = await cli(['app-create', 'external-client', '--name', 'External client', '--grant', `${external.id}:manage`]);
|
||||||
|
const connection = await cli(['key-issue', application.id]);
|
||||||
|
const client = clientFactory(connection);
|
||||||
|
await client.call(`/v2/contours/${external.id}/enrollment`, { action: 'register', name: 'External B2', imei: '123456789012346', number: 1002 });
|
||||||
|
assert.equal((await execute(common, 'inventory')).items.length, 2);
|
||||||
|
assert.equal((await execute(second, 'inventory')).items.length, 1);
|
||||||
|
});
|
||||||
|
await check('rotation invalidates the old key and preserves application identity and fleet', async () => {
|
||||||
|
const replacement = await execute(common, 'key-issue', { integrationId: appA.id, replace: true });
|
||||||
|
await assert.rejects(appClientA.call('/v2/contours'), /b2_access_denied/);
|
||||||
|
appClientA = clientFactory(replacement.connection);
|
||||||
|
assert.equal(replacement.connection.integration_id, appA.id);
|
||||||
|
assert.equal((await appClientA.call(`/v2/contours/${contour}/devices`)).items.length, 1);
|
||||||
|
assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1);
|
||||||
|
});
|
||||||
|
await check('lost key response is not replayed and explicit reissue recovers safely', async () => {
|
||||||
|
const id = requestId(), fields = { name: 'Lost response', contourId: contour, access: 'read' };
|
||||||
|
const first = await execute(common, 'application-connect', fields, id);
|
||||||
|
await assert.rejects(execute(common, 'application-connect', fields, id), /b2_conflict/);
|
||||||
|
const status = await execute(common, 'status');
|
||||||
|
assert.equal(status.applications.filter(app => app.id === first.id).length, 1);
|
||||||
|
const replacement = await execute(common, 'key-issue', { integrationId: first.id, replace: true });
|
||||||
|
await assert.rejects(clientFactory(first.connection).call('/v2/contours'), /b2_access_denied/);
|
||||||
|
assert.equal((await clientFactory(replacement.connection).call('/v2/contours')).items.length, 1);
|
||||||
|
});
|
||||||
|
await check('application deletion revokes access without deleting devices or other clients', async () => {
|
||||||
|
await execute(common, 'application-delete', { integrationId: appA.id });
|
||||||
|
await assert.rejects(appClientA.call('/v2/contours'), /b2_access_denied/);
|
||||||
|
assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1);
|
||||||
|
assert.equal((await execute(second, 'inventory')).items.length, 1);
|
||||||
|
});
|
||||||
|
await check('cross-company assignment is rejected and cannot leak a host view', async () => {
|
||||||
|
const otherOwner = { scopeKind: 'company', ownerRef: 'company:foreign-fixture' };
|
||||||
|
const otherActor = { ...actor, ownerScopes: [owner, otherOwner] };
|
||||||
|
await management('owner_scope.ensure', { ...otherOwner, displayName: 'Foreign' }, otherActor);
|
||||||
|
const value = await management('project.ensure', { ...otherOwner, projectKey: 'foreign', name: 'Foreign project' }, otherActor);
|
||||||
|
await assert.rejects(execute(common, 'link', { contourId: contour, targetProjectRef: value.project.projectRef }, requestId(), otherActor), /b2_company_mismatch/);
|
||||||
|
assert.equal((await db.query('select * from device_b2_host_views where project_id=$1', [value.project.projectRef.slice(8)])).rows.length, 0);
|
||||||
|
});
|
||||||
|
await check('rollback refuses to discard multiple project bindings', async () => {
|
||||||
|
await assert.rejects(db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.rollback.sql'), 'utf8')), /rollback_would_lose_links/);
|
||||||
|
await db.exec('rollback');
|
||||||
|
assert.equal((await execute(common, 'status')).links.filter(link => link.contourId === contour).length, 2);
|
||||||
|
});
|
||||||
|
await check('unlink is local to one project and leaves external keys and other project intact', async () => {
|
||||||
|
await execute(common, 'unlink', { contourId: contour, targetProjectRef: projectB });
|
||||||
|
await execute(common, 'unlink', { contourId: contour, targetProjectRef: projectB });
|
||||||
|
assert.equal((await execute(second, 'inventory')).items.length, 0);
|
||||||
|
assert.equal((await execute(common, 'inventory')).items.length, 2);
|
||||||
|
assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1);
|
||||||
|
});
|
||||||
|
await check('VPS restart preserves contours devices credentials and project mappings', async () => {
|
||||||
|
await command({ kind: 'restart' });
|
||||||
|
assert.equal((await execute(common, 'status')).contours.length, 4);
|
||||||
|
assert.equal((await execute(common, 'inventory')).items.length, 2);
|
||||||
|
assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1);
|
||||||
|
});
|
||||||
|
await check('audit and database metadata never contain exported credential secrets', async () => {
|
||||||
|
const audit = JSON.stringify((await db.query('select payload from device_audit_events')).rows);
|
||||||
|
const sources = JSON.stringify((await db.query('select * from device_b2_hosts')).rows);
|
||||||
|
for (const secret of [pkg.client_secret, appA.connection.client_secret, appB.connection.client_secret]) {
|
||||||
|
assert.equal(audit.includes(secret), false); assert.equal(sources.includes(secret), false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await check('lossless rollback and reapplication preserve remaining associations', async () => {
|
||||||
|
const before = (await db.query('select * from device_b2_contour_links order by contour_id,project_id')).rows;
|
||||||
|
await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.rollback.sql'), 'utf8'));
|
||||||
|
await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.sql'), 'utf8'));
|
||||||
|
assert.deepEqual((await db.query('select * from device_b2_contour_links order by contour_id,project_id')).rows, before);
|
||||||
|
});
|
||||||
|
const report = { ok: true, checkedAt: new Date().toISOString(), checks, engine: 'PGlite PostgreSQL WASM and VPS SQLite',
|
||||||
|
real: ['Device Core management repository', 'B2Infrastructure', 'OAuth client library', 'VPS SharedAPI', 'VPS CLI parser and domain', 'credential issue/revoke domain', 'private file vault'],
|
||||||
|
simulated: ['OAuth provider', 'TLS transport', 'CLI root privilege', 'hardware'],
|
||||||
|
productionMutation: false, cleanUbuntuInstallation: false, boundedDevices: 2, boundedExternalContours: 3 };
|
||||||
|
await writeFile(resolve(process.argv[4]), JSON.stringify(report, null, 2) + '\n');
|
||||||
|
console.log(JSON.stringify({ ok: true, checks: checks.length }));
|
||||||
|
} finally {
|
||||||
|
child.stdin.end();
|
||||||
|
await new Promise(resolve => child.once('exit', resolve));
|
||||||
|
await db.close(); await rm(secretsRoot, { recursive: true, force: true });
|
||||||
|
}
|
||||||
@@ -211,7 +211,7 @@ export function createControlCoreApp({
|
|||||||
const requestId = String(request.headers["idempotency-key"] || "");
|
const requestId = String(request.headers["idempotency-key"] || "");
|
||||||
if (!/^[a-f0-9]{32}$/.test(requestId)) throw new TypeError("b2_request_id_invalid");
|
if (!/^[a-f0-9]{32}$/.test(requestId)) throw new TypeError("b2_request_id_invalid");
|
||||||
const actor = managementActorFromHeaders(request.headers);
|
const actor = managementActorFromHeaders(request.headers);
|
||||||
const input = await readJsonBody(request, 64 * 1024);
|
const input = await readJsonBody(request, 128 * 1024);
|
||||||
const result = await b2Infrastructure.execute(actor, input, requestId);
|
const result = await b2Infrastructure.execute(actor, input, requestId);
|
||||||
return writeJson(response, 200, { ok: true, result });
|
return writeJson(response, 200, { ok: true, result });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -149,7 +149,9 @@ export function createB2Client(input, { fetchImpl } = {}) {
|
|||||||
const value = await res.json().catch(() => null);
|
const value = await res.json().catch(() => null);
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
if (res.status === 401 || res.status === 403) { token = null; throw b2Error('b2_access_denied', 403); }
|
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 === 409) throw b2Error('b2_conflict', 409);
|
||||||
|
if (res.status === 400) throw b2Error('b2_request_invalid', 400);
|
||||||
throw b2Error('b2_host_request_failed', 502);
|
throw b2Error('b2_host_request_failed', 502);
|
||||||
}
|
}
|
||||||
if (!value || typeof value !== 'object') throw b2Error('b2_response_invalid', 502);
|
if (!value || typeof value !== 'object') throw b2Error('b2_response_invalid', 502);
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ export class B2Infrastructure {
|
|||||||
this.pool = pool; this.secrets = secrets; this.clientFactory = clientFactory;
|
this.pool = pool; this.secrets = secrets; this.clientFactory = clientFactory;
|
||||||
this.clients = new Map();
|
this.clients = new Map();
|
||||||
}
|
}
|
||||||
|
async supportsSharedProjects(db) {
|
||||||
|
const row = (await db.query("select obj_description('device_b2_contour_links'::regclass) as marker")).rows[0];
|
||||||
|
return row?.marker === 'nodedc.device-b2-shared-contours/v1';
|
||||||
|
}
|
||||||
async clientFor(source) {
|
async clientFor(source) {
|
||||||
// Private file refs are immutable. Re-importing/replacing a key creates a
|
// Private file refs are immutable. Re-importing/replacing a key creates a
|
||||||
// new ref and therefore cannot reuse the previous OAuth token cache.
|
// new ref and therefore cannot reuse the previous OAuth token cache.
|
||||||
@@ -32,6 +36,66 @@ export class B2Infrastructure {
|
|||||||
this.clients.set(source.secret_ref, client);
|
this.clients.set(source.secret_ref, client);
|
||||||
return 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) {
|
async inventory(actor, input) {
|
||||||
fields(input, []);
|
fields(input, []);
|
||||||
const projectId = ref(input.projectRef, 'project');
|
const projectId = ref(input.projectRef, 'project');
|
||||||
@@ -70,8 +134,102 @@ export class B2Infrastructure {
|
|||||||
}));
|
}));
|
||||||
return { items: results.flatMap((result) => result.items), hosts: results.map((result) => result.host) };
|
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 enrollmentOptions(actor, input) {
|
||||||
|
fields(input, []);
|
||||||
|
const projectId = ref(input.projectRef, 'project');
|
||||||
|
const db = await this.pool.connect();
|
||||||
|
let sources;
|
||||||
|
try {
|
||||||
|
await db.query('begin');
|
||||||
|
await findProjectWithCapability(db, actor, projectId, 'device.enroll');
|
||||||
|
sources = (await db.query(`select s.*, v.host_id, h.display_name,
|
||||||
|
coalesce((select json_agg(l.contour_id order by l.contour_id) from device_b2_contour_links l
|
||||||
|
where l.source_id=s.id and l.project_id=v.project_id), '[]'::json) as contour_ids
|
||||||
|
from device_b2_hosts s join device_b2_host_views v on v.source_id=s.id
|
||||||
|
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
|
||||||
|
where v.project_id=$1 and h.lifecycle_state='active'`, [projectId])).rows;
|
||||||
|
await db.query('commit');
|
||||||
|
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
|
||||||
|
return { hosts: await Promise.all(sources.map(async source => {
|
||||||
|
const host = { hostRef: `host:${source.host_id}`, name: source.display_name };
|
||||||
|
try {
|
||||||
|
const remote = await this.clientFor(source);
|
||||||
|
const identity = await remote.call('/v2/identity');
|
||||||
|
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
|
||||||
|
const contours = (await remote.call('/v2/contours')).items
|
||||||
|
.filter(item => source.contour_ids.includes(item.id) && item.access === 'manage')
|
||||||
|
.map(({ id, name }) => ({ id, name }));
|
||||||
|
return { ...host, reachable: true, contours };
|
||||||
|
} catch { return { ...host, reachable: false, contours: [] }; }
|
||||||
|
})) };
|
||||||
|
}
|
||||||
|
async enrollment(actor, input) {
|
||||||
|
fields(input, ['contourId', 'request']);
|
||||||
|
const projectId = ref(input.projectRef, 'project'), hostId = ref(input.hostRef, 'host');
|
||||||
|
const contourId = opaque(input.contourId), request = input.request;
|
||||||
|
if (!request || typeof request !== 'object' || Array.isArray(request)
|
||||||
|
|| !['catalog', 'inspect', 'register'].includes(request.action)) throw b2Error('b2_request_invalid');
|
||||||
|
const db = await this.pool.connect();
|
||||||
|
let source;
|
||||||
|
try {
|
||||||
|
await db.query('begin');
|
||||||
|
await findProjectWithCapability(db, actor, projectId, 'device.enroll');
|
||||||
|
if (request.action === 'register') await findProjectWithCapability(db, actor, projectId, 'device.claim');
|
||||||
|
source = (await db.query(`select s.* from device_b2_hosts s
|
||||||
|
join device_b2_host_views v on v.source_id=s.id
|
||||||
|
join device_b2_contour_links l on l.source_id=s.id and l.project_id=v.project_id
|
||||||
|
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
|
||||||
|
where v.host_id=$1 and v.project_id=$2 and l.contour_id=$3 and h.lifecycle_state='active'`,
|
||||||
|
[hostId, projectId, contourId])).rows[0];
|
||||||
|
if (!source) throw b2Error('b2_access_denied', 403);
|
||||||
|
await db.query('commit');
|
||||||
|
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
|
||||||
|
const remote = await this.clientFor(source);
|
||||||
|
const identity = await remote.call('/v2/identity');
|
||||||
|
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
|
||||||
|
// Only the selected project's linked contour may receive identity/configuration.
|
||||||
|
return remote.call(`/v2/contours/${contourId}/enrollment`, request);
|
||||||
|
}
|
||||||
async execute(actor, input, requestId) {
|
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 === 'inventory') return this.inventory(actor, input);
|
||||||
|
if (input.action === 'tracker') return this.tracker(actor, input);
|
||||||
|
if (input.action === 'enrollment-options') return this.enrollmentOptions(actor, input);
|
||||||
|
if (input.action === 'enrollment') return this.enrollment(actor, input);
|
||||||
const projectId = ref(input.projectRef, 'project');
|
const projectId = ref(input.projectRef, 'project');
|
||||||
const hostId = ref(input.hostRef, 'host');
|
const hostId = ref(input.hostRef, 'host');
|
||||||
const action = input.action;
|
const action = input.action;
|
||||||
@@ -83,7 +241,7 @@ export class B2Infrastructure {
|
|||||||
// Host management can affect all projects of the company. A project-only
|
// Host management can affect all projects of the company. A project-only
|
||||||
// grant must not turn into company-wide administration.
|
// grant must not turn into company-wide administration.
|
||||||
if (action !== 'devices') assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
|
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');
|
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',
|
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 +261,7 @@ export class B2Infrastructure {
|
|||||||
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
|
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');
|
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);
|
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 this.saveSource(db, project, 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);
|
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)
|
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]);
|
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [hostId, projectId, project.owner_scope_id, saved.id]);
|
||||||
@@ -127,20 +276,41 @@ export class B2Infrastructure {
|
|||||||
fields(input, []);
|
fields(input, []);
|
||||||
const value = source.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
|
const value = source.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
|
||||||
result = { connected: true, endpoint: source.endpoint, authority: source.authority,
|
result = { connected: true, endpoint: source.endpoint, authority: source.authority,
|
||||||
|
sharedProjects: await this.supportsSharedProjects(db),
|
||||||
contours: value.contours || value.items, applications: value.applications || [],
|
contours: value.contours || value.items, applications: value.applications || [],
|
||||||
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
|
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
|
||||||
} else if (action === 'link') {
|
} else if (['link', 'unlink', 'project-connect', 'contour-connect'].includes(action)) {
|
||||||
fields(input, ['contourId', 'targetProjectRef']);
|
fields(input, action === 'contour-connect' ? ['name', 'targetProjectRef'] : action === 'project-connect' ? ['targetProjectRef'] : ['contourId', 'targetProjectRef']);
|
||||||
const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
|
const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
|
||||||
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
|
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
|
||||||
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
|
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
|
||||||
const contour = opaque(input.contourId);
|
let contour;
|
||||||
|
if (action === 'unlink') {
|
||||||
|
contour = opaque(input.contourId);
|
||||||
|
await db.query('delete from device_b2_contour_links where source_id=$1 and contour_id=$2 and project_id=$3', [source.id, contour, targetId]);
|
||||||
|
result = { linked: false, contourId: contour, projectRef: `project:${targetId}` };
|
||||||
|
} else {
|
||||||
|
if (action === 'contour-connect') {
|
||||||
|
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
|
||||||
|
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
|
||||||
|
if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
|
||||||
|
// Retry a lost response without creating another remote contour.
|
||||||
|
contour = (await remote.call('/v2/management/contours', { key: 'dc-' + requestId, name: input.name.trim() })).id;
|
||||||
|
} else 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');
|
const permitted = await remote.call('/v2/contours');
|
||||||
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
|
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
|
||||||
const current = links.find((link) => link.contour_id === contour);
|
if (links.some((link) => link.contour_id === contour && link.project_id !== targetId)
|
||||||
if (current && current.project_id !== targetId) throw b2Error('b2_contour_already_linked', 409);
|
&& !await this.supportsSharedProjects(db)) throw b2Error('b2_shared_projects_migration_required', 409);
|
||||||
await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref)
|
await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref)
|
||||||
values($1,$2,$3,$4,$5) on conflict(source_id,contour_id) do nothing`,
|
values($1,$2,$3,$4,$5) on conflict do nothing`,
|
||||||
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
|
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
|
||||||
if (targetId !== projectId) {
|
if (targetId !== projectId) {
|
||||||
const related = (await db.query('select host_id from device_b2_host_views where source_id=$1 and project_id=$2', [source.id, targetId])).rows[0];
|
const related = (await db.query('select host_id from device_b2_host_views where source_id=$1 and project_id=$2', [source.id, targetId])).rows[0];
|
||||||
@@ -156,6 +326,7 @@ export class B2Infrastructure {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
|
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
|
||||||
|
}
|
||||||
} else if (action === 'devices') {
|
} else if (action === 'devices') {
|
||||||
fields(input, []);
|
fields(input, []);
|
||||||
const contours = links.filter((link) => link.project_id === projectId);
|
const contours = links.filter((link) => link.project_id === projectId);
|
||||||
@@ -176,6 +347,24 @@ export class B2Infrastructure {
|
|||||||
result = await remote.call('/v2/management/applications', {
|
result = await remote.call('/v2/management/applications', {
|
||||||
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
|
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
|
||||||
});
|
});
|
||||||
|
} else if (action === 'application-connect') {
|
||||||
|
fields(input, ['name', 'contourId', 'access']);
|
||||||
|
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
|
||||||
|
const contour = opaque(input.contourId);
|
||||||
|
const access = input.access ?? 'manage';
|
||||||
|
if (!['read', 'control', 'manage'].includes(access)) throw b2Error('b2_request_invalid');
|
||||||
|
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]: access },
|
||||||
|
});
|
||||||
|
// 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') {
|
} else if (action === 'key-issue') {
|
||||||
fields(input, ['integrationId', 'replace']);
|
fields(input, ['integrationId', 'replace']);
|
||||||
if (typeof input.replace !== 'boolean') throw b2Error('b2_replace_invalid');
|
if (typeof input.replace !== 'boolean') throw b2Error('b2_replace_invalid');
|
||||||
|
|||||||
@@ -19,12 +19,13 @@ const actor = { userRef: 'user:operator', hubRole: 'owner', groupRefs: [], owner
|
|||||||
const source = { id: '55555555-5555-4555-8555-555555555555', owner_scope_id: ownerId,
|
const source = { id: '55555555-5555-4555-8555-555555555555', owner_scope_id: ownerId,
|
||||||
remote_host_id: pkg.host_id, endpoint: pkg.endpoint, fingerprint: pkg.fingerprint,
|
remote_host_id: pkg.host_id, endpoint: pkg.endpoint, fingerprint: pkg.fingerprint,
|
||||||
integration_id: pkg.integration_id, authority: pkg.authority, secret_ref: 'private-ref' };
|
integration_id: pkg.integration_id, authority: pkg.authority, secret_ref: 'private-ref' };
|
||||||
function repository({ role = 'owner', links = [], otherOwner = ownerId } = {}) {
|
function repository({ role = 'owner', links = [], otherOwner = ownerId, sharedProjects = true } = {}) {
|
||||||
const writes = [];
|
const writes = [];
|
||||||
const db = { release() {}, async query(sql, values) {
|
const db = { release() {}, async query(sql, values) {
|
||||||
if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] };
|
if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] };
|
||||||
|
if (sql.includes('obj_description')) return { rows: [{ marker: sharedProjects ? 'nodedc.device-b2-shared-contours/v1' : 'nodedc.device-b2-foundation/v1' }] };
|
||||||
if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner,
|
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,
|
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' }] };
|
project_role: role, capability_allow: [], capability_deny: [], lifecycle_state: 'active' }] };
|
||||||
if (sql.includes('from device_infrastructure_hosts')) return { rows: [{ id: hostId }] };
|
if (sql.includes('from device_infrastructure_hosts')) return { rows: [{ id: hostId }] };
|
||||||
@@ -195,3 +196,219 @@ 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);
|
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), access: 'host' }, requestId), /b2_request_invalid/);
|
||||||
|
assert.equal(calls.length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('host catalogue includes external unlinked contours without creating local projects', async () => {
|
||||||
|
const repo = repository();
|
||||||
|
const contours = [{ id: 'a'.repeat(32), key: 'external', name: 'External fleet' }];
|
||||||
|
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async () => ({ contours }) }) });
|
||||||
|
const result = await service.execute(actor, { action: 'status', projectRef: `project:${projectId}`, hostRef: `host:${hostId}` });
|
||||||
|
assert.deepEqual(result.contours, contours);
|
||||||
|
assert.deepEqual(result.links, []);
|
||||||
|
assert.equal(result.sharedProjects, true);
|
||||||
|
assert.deepEqual(repo.writes, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('second project can share a contour after migration and old foundation fails explicitly', async () => {
|
||||||
|
for (const sharedProjects of [true, false]) {
|
||||||
|
const contour = 'c'.repeat(32);
|
||||||
|
const repo = repository({ sharedProjects, links: [{ contour_id: contour, project_id: otherProject }] });
|
||||||
|
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async () => ({ items: [{ id: contour }] }) }) });
|
||||||
|
const result = service.execute(actor, { action: 'link', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, contourId: contour });
|
||||||
|
if (sharedProjects) {
|
||||||
|
assert.equal((await result).linked, true);
|
||||||
|
assert.equal(repo.writes.filter(item => item.sql.includes('device_b2_contour_links')).length, 1);
|
||||||
|
} else {
|
||||||
|
await assert.rejects(result, /b2_shared_projects_migration_required/);
|
||||||
|
assert.deepEqual(repo.writes, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('new contour retries retain remote identity and authorize target before creation', async () => {
|
||||||
|
const contour = 'c'.repeat(32), calls = [], requestId = 'd'.repeat(32);
|
||||||
|
const repo = repository();
|
||||||
|
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async (path, body) => {
|
||||||
|
calls.push({ path, body }); return path.endsWith('/management/contours') ? { id: contour } : { items: [{ id: contour }] };
|
||||||
|
} }) });
|
||||||
|
const input = { action: 'contour-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'New fleet' };
|
||||||
|
assert.equal((await service.execute(actor, input, requestId)).contourId, contour);
|
||||||
|
assert.equal((await service.execute(actor, input, requestId)).contourId, contour);
|
||||||
|
assert.equal(calls[0].body.key, calls[2].body.key);
|
||||||
|
assert.equal(calls[0].body.key, 'dc-' + requestId);
|
||||||
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enrollment options reveal only managed contours linked to the current active project', async () => {
|
||||||
|
const own = 'a'.repeat(32), foreign = 'b'.repeat(32); const repo = repository();
|
||||||
|
const db = await repo.pool.connect(), original = db.query; let released = false;
|
||||||
|
db.release = () => { released = true; };
|
||||||
|
db.query = async (sql, values) => {
|
||||||
|
if (sql.includes('from device_b2_hosts')) {
|
||||||
|
assert.match(sql, /l.project_id=v.project_id/); assert.match(sql, /h.lifecycle_state='active'/);
|
||||||
|
assert.deepEqual(values, [projectId]); return { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [own] }] };
|
||||||
|
}
|
||||||
|
return original(sql, values);
|
||||||
|
};
|
||||||
|
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
|
||||||
|
assert.ok(released);
|
||||||
|
return path === '/v2/identity' ? { host_id: pkg.host_id } : { items: [{ id: own, name: 'Own', access: 'manage' }, { id: foreign, name: 'Foreign', access: 'manage' }] };
|
||||||
|
} }) });
|
||||||
|
const result = await service.execute(actor, { projectRef: `project:${projectId}`, action: 'enrollment-options' });
|
||||||
|
assert.deepEqual(result.hosts[0].contours, [{ id: own, name: 'Own' }]); assert.ok(!JSON.stringify(result).includes('Foreign'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enrollment validates project capability, active host and contour before forwarding USB', async () => {
|
||||||
|
const own = 'a'.repeat(32), foreign = 'b'.repeat(32); const repo = repository();
|
||||||
|
const db = await repo.pool.connect(), original = db.query; const calls = [];
|
||||||
|
db.query = async (sql, values) => {
|
||||||
|
if (sql.includes('from device_b2_hosts')) {
|
||||||
|
assert.match(sql, /l.project_id=v.project_id/); assert.match(sql, /h.lifecycle_state='active'/);
|
||||||
|
return { rows: values[0] === hostId && values[1] === projectId && values[2] === own ? [source] : [] };
|
||||||
|
}
|
||||||
|
return original(sql, values);
|
||||||
|
};
|
||||||
|
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
|
||||||
|
calls.push(path); return path === '/v2/identity' ? { host_id: pkg.host_id } : { accepted: body.action };
|
||||||
|
} }) });
|
||||||
|
const input = { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'enrollment', contourId: own, request: { action: 'register', name: 'B2', imei: '323456789012345', number: 300 } };
|
||||||
|
await assert.rejects(service.execute(actor, { ...input, contourId: foreign }), /b2_access_denied/);
|
||||||
|
assert.deepEqual(calls, []);
|
||||||
|
assert.deepEqual(await service.execute(actor, input), { accepted: 'register' });
|
||||||
|
assert.deepEqual(calls, ['/v2/identity', `/v2/contours/${own}/enrollment`]);
|
||||||
|
const denied = new B2Infrastructure({ pool: repository({ role: 'viewer' }).pool, secrets: { read: async () => assert.fail('no credentials') } });
|
||||||
|
await assert.rejects(denied.execute({ ...actor, hubRole: 'member' }, input));
|
||||||
|
await assert.rejects(denied.execute({ ...actor, hubRole: 'member' }, { projectRef: input.projectRef, action: 'enrollment-options' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enrollment permission alone cannot claim a device into a project', async () => {
|
||||||
|
const repo = repository({ role: 'engineer' }), db = await repo.pool.connect(), original = db.query;
|
||||||
|
db.query = async (sql, values) => {
|
||||||
|
const result = await original(sql, values);
|
||||||
|
if (sql.includes('from device_project_grants')) result.rows[0].capability_deny = ['device.claim'];
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => assert.fail('no remote credentials') } });
|
||||||
|
await assert.rejects(service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'enrollment', contourId: 'a'.repeat(32), request: { action: 'register', imei: '323456789012345', number: 300, name: 'B2' } }));
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user