11 Commits
Author SHA1 Message Date
DCCONSTRUCTIONS fc2e9c8bc1 fix(device): pin responsive shared header geometry
Device Core qualification / qualify (push) Successful in 8m12s
2026-11-05 13:20:01 +03:00
DCCONSTRUCTIONS e30a6dd2a1 fix(device): consume the canonical shared profile header
Device Core qualification / qualify (push) Successful in 8m26s
2026-11-05 13:09:59 +03:00
DCCONSTRUCTIONS dcb0c76ac8 Group expanded VPS contours and label the contour list
Device Core qualification / qualify (push) Successful in 7m23s
2026-10-01 16:11:14 +03:00
DCCONSTRUCTIONS 5200159d0b Complete shared contour project linking and scoped application onboarding 2026-10-01 14:47:07 +03:00
DCCONSTRUCTIONS 1b3001dfa1 Remove passive access summary from project overview
Device Core qualification / qualify (push) Successful in 7m21s
2026-10-01 12:17:22 +03:00
DCCONSTRUCTIONS f500d0af0f Stack project overview into full-width resource rows
Device Core qualification / qualify (push) Successful in 7m37s
2026-10-01 12:01:20 +03:00
DCCONSTRUCTIONS 2851f10f0f Simplify infrastructure and management navigation
Device Core qualification / qualify (push) Successful in 7m55s
2026-10-01 11:36:21 +03:00
DCCONSTRUCTIONS d9911a336f Use normal USB deadlines for successful protocol fixtures
Device Core qualification / qualify (push) Successful in 8m24s
2026-10-01 10:20:11 +03:00
DCCONSTRUCTIONS d0e9acd7bc Integrate tracker commands into the settings tab
Device Core qualification / qualify (push) Failing after 3m29s
2026-10-01 10:13:34 +03:00
DCCONSTRUCTIONS be30fafa95 Enforce claim permission and bounded full USB enrollment envelopes
Device Core qualification / qualify (push) Successful in 8m31s
2026-10-01 09:33:04 +03:00
DCCONSTRUCTIONS dc9fe6e0fc Add direct B2 device enrollment and consolidate VPS controls
Device Core qualification / qualify (push) Successful in 8m6s
2026-10-01 09:21:43 +03:00
29 changed files with 1340 additions and 203 deletions
@@ -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());
});
@@ -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);
});
+12 -60
View File
@@ -17,11 +17,9 @@ import {
} from "@nodedc/ui-react"; } from "@nodedc/ui-react";
import { useB2Inventory } from "./b2/useB2Inventory"; import { useB2Inventory } from "./b2/useB2Inventory";
import { B2AddHost } from "./b2/B2AddHost";
import { B2HostSettings } from "./b2/B2HostSettings"; import { B2HostSettings } from "./b2/B2HostSettings";
import { import {
archiveHost,
createConfigurationRevision, createConfigurationRevision,
closeAssetBinding, closeAssetBinding,
ensureAsset, ensureAsset,
@@ -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,14 +299,6 @@ export function DeviceControlView({
onCreated={completed} onCreated={completed}
onError={onError} onError={onError}
/> />
<B2AddHost
key={workspace.project.projectRef + ":" + (dialog === "host")}
open={dialog === "host"}
projectRef={workspace.project.projectRef}
onClose={close}
onCreated={completed}
onError={onError}
/>
<EndpointDialog <EndpointDialog
key={`EndpointDialog:${dialogHostRef}:${dialog}`} key={`EndpointDialog:${dialogHostRef}:${dialog}`}
initialHostRef={dialogHostRef} initialHostRef={dialogHostRef}
@@ -487,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,
@@ -503,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;
@@ -524,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);
@@ -568,18 +519,19 @@ function HostsView({
status={<StatusBadge tone={remote ? remote.reachable ? 'success' : 'warning' : freshnessTone(host.telemetry.freshness)}>{remote ? remote.reachable ? 'Подключён' : 'Нет связи' : host.lifecycleState === 'suspended' ? 'В архиве' : freshnessLabel(host.telemetry.freshness)}</StatusBadge>} 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}
<IconButton label={`Мониторинг ${host.displayName}`} onClick={() => onSelectHost(host.hostRef)}><Icon name="activity" /></IconButton>
<IconButton label={`Сведения ${host.displayName}`} aria-expanded={expanded} onClick={() => setExpandedHost(expanded ? null : host.hostRef)}><Icon name={expanded ? "chevron-up" : "chevron-down"} /></IconButton> <IconButton label={`Сведения ${host.displayName}`} aria-expanded={expanded} onClick={() => setExpandedHost(expanded ? null : host.hostRef)}><Icon name={expanded ? "chevron-up" : "chevron-down"} /></IconButton>
</>} /> </>} />
{expanded ? <SettingsCard title="Сведения о хосте"> {expanded ? <div className="b2-disclosure__body">
<CanonicalResourceList> {isB2(host) ? <CanonicalResourceList>
{isB2(host) ? <li><CanonicalResourceRow title="ARNavi VPS" description={remote?.endpoint} metadata="Адрес получен из ключа сервера" /></li> : null} <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.endpoints.filter((item) => item.hostRef === host.hostRef).map((item) => <li key={item.endpointRef}><CanonicalResourceRow title="Адрес подключения" description={item.endpointUri} /></li>)} <li><CanonicalResourceRow title="Контуры проекта" status={String(remote?.contours ?? '—')} /></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?.devices ?? '—')} /></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={<StatusBadge>Не подключены</StatusBadge>} /></li>
</CanonicalResourceList> </CanonicalResourceList> : <>
{canManageInfrastructure ? <div className="b2-actions"><Button disabled={archiving} onClick={() => setArchiveTarget(host)}>{host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button>{!isB2(host) ? <><Button onClick={() => onCreateEndpoint(host.hostRef)}>Адрес</Button><Button onClick={() => onCreateDeployment(host.hostRef)}>Развёртывание</Button><Button onClick={() => onCreateService(host.hostRef)} disabled={!topology.deployments.some((item) => item.hostRef === host.hostRef)}>Сервис</Button></> : null}</div> : null} <HostTelemetryWorkspace host={host} services={topology.serviceInstances.filter(item => item.hostRef === host.hostRef)} onPoll={onPoll} onError={onError} />
</SettingsCard> : null} {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}
+22 -33
View File
@@ -12,7 +12,6 @@ import {
ResourceList, ResourceList,
ResourceRow, ResourceRow,
HeaderNavigation, HeaderNavigation,
HeaderProfile,
HeaderWorkspace, HeaderWorkspace,
Icon, Icon,
type IconName, type IconName,
@@ -58,8 +57,9 @@ 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 { useB2Inventory } from "./b2/useB2Inventory";
import { capabilityLabel, projectRoleLabel } from "./presentationLabels";
import { import {
DeviceControlView, DeviceControlView,
type ControlViewId, type ControlViewId,
@@ -102,13 +102,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: "Узлы и маршруты", 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" },
@@ -193,11 +189,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);
@@ -297,7 +294,6 @@ export function DeviceManagerApp() {
setInventoryDetail(null); setInventoryDetail(null);
projectRefCurrent.current = projectRef; projectRefCurrent.current = projectRef;
setWorkspace(null); setWorkspace(null);
setSelectedHostRef(null);
setActiveProjectRef(projectRef); setActiveProjectRef(projectRef);
}; };
@@ -318,7 +314,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) {
@@ -379,7 +374,6 @@ export function DeviceManagerApp() {
</> </>
} }
right={ right={
<HeaderProfile>
<UserProfileMenu <UserProfileMenu
displayName={session.user.displayName} displayName={session.user.displayName}
subtitle={session.user.email} subtitle={session.user.email}
@@ -395,7 +389,6 @@ export function DeviceManagerApp() {
{ id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" }, { id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" },
]} ]}
/> />
</HeaderProfile>
} }
/> />
} }
@@ -417,8 +410,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>
@@ -494,8 +487,10 @@ export function DeviceManagerApp() {
expanded={shell.contentExpanded} expanded={shell.contentExpanded}
onExpandedChange={shell.setContentExpanded} onExpandedChange={shell.setContentExpanded}
onClose={shell.closeView} onClose={shell.closeView}
utilityActions={[...(activeView === "hosts" && selectedHostRef ? [{ utilityActions={[...(activeView === 'inventory' && canEnroll ? [{
label: "Вернуться к VPS и хостам", icon: "chevron-left" as const, onClick: () => setSelectedHostRef(null), label: 'Добавить устройство', icon: 'plus' as const, onClick: () => setAddDeviceOpen(true),
}] : []), ...(activeView === 'hosts' && capabilities.has('infrastructure.manage') ? [{
label: 'Добавить VPS', icon: 'plus' as const, onClick: () => setAddHostOpen(true),
}] : []), { }] : []), {
label: "Обновить данные", label: "Обновить данные",
icon: "refresh", icon: "refresh",
@@ -504,8 +499,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}
@@ -557,6 +550,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}
@@ -782,9 +777,7 @@ function EnvironmentBackdrop({
); );
} }
function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: { function ProjectView({ 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;
@@ -803,8 +796,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}
@@ -849,7 +840,6 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) { function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) {
const b2 = useB2Inventory(workspace.project.projectRef, workspace); const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const [showPermissions, setShowPermissions] = useState(false);
const incomplete = !b2.data || b2.data.hosts.some((host) => !host.reachable); 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 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 deviceDetail = !incomplete ? 'В реестре' : (b2.error || b2.data) ? 'Данные VPS недоступны' : 'Загрузка…';
@@ -859,14 +849,13 @@ function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) {
{ label: 'Коллекции', value: workspace.collections.length, detail: 'Группы устройств' }, { label: 'Коллекции', value: workspace.collections.length, detail: 'Группы устройств' },
]; ];
return ( return (
<div className="device-manager-overview-grid"> <ResourceList>
<ResourceList>{metrics.map((metric) => <li key={metric.label}><ResourceRow title={metric.label} metadata={metric.detail} status={<StatusBadge>{metric.value ?? '—'}</StatusBadge>} /></li>)}</ResourceList> {metrics.map((metric) => (
<ResourceRow title="Ваш доступ" metadata={projectRoleLabel(workspace.project.access.projectRole || 'read')} <li key={metric.label}>
actions={<IconButton label="Права в проекте" aria-expanded={showPermissions} aria-controls="project-permissions" onClick={() => setShowPermissions(!showPermissions)}><Icon name={showPermissions ? 'chevron-up' : 'chevron-down'} /></IconButton>} /> <ResourceRow title={metric.label} metadata={metric.detail} status={<StatusBadge>{metric.value ?? '—'}</StatusBadge>} />
{showPermissions ? <div id="project-permissions"><ResourceList> </li>
{workspace.project.access.capabilities.map((capability) => <li key={capability}><ResourceRow title={capabilityLabel(capability)} /></li>)} ))}
</ResourceList></div> : null} </ResourceList>
</div>
); );
} }
@@ -1295,12 +1284,12 @@ function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated,
}> }>
<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}
/> />
@@ -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>;
}
+98 -36
View File
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, 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, type B2Application } from './api'; import { b2Request, type B2Status, type B2Application } from './api';
import './b2.css'; import './b2.css';
@@ -19,13 +19,18 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
const [projects, setProjects] = useState<ProjectSummary[]>([]); const [projects, setProjects] = useState<ProjectSummary[]>([]);
const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]); const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
const [creating, setCreating] = useState(''), [name, setName] = useState(''); const [creating, setCreating] = useState(''), [name, setName] = useState('');
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string } | null>(null); const [access, setAccess] = useState('read');
const [hiddenHistory, setHiddenHistory] = useState<string[]>([]); 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 [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null);
const [credentialRows, setCredentialRows] = useState<string[]>([]); 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> = {}, requestId?: string) => b2Request<T>(project.projectRef, host.hostRef, action, data, requestId); 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]) => {
@@ -35,10 +40,25 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
}).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]);
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) { async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) {
setPending(action); setPending(action);
try { try {
const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string }>(action, data, requestId); const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string; contourId?: string }>(action, data, requestId);
if (result.connection) { if (result.connection) {
const { integration_id: applicationId, client_id: clientId } = result.connection; const { integration_id: applicationId, client_id: clientId } = result.connection;
setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) }); setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) });
@@ -48,10 +68,24 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null); if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null);
if (action === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null); if (action === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null);
if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); } 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); 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); await refresh().catch(() => undefined); 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 busy = Boolean(pending), canManage = status?.authority === 'host'; const busy = Boolean(pending), canManage = status?.authority === 'host';
const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id]; const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id];
@@ -68,7 +102,6 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
<ResourceRow title={app.name} metadata={legacy ? 'Подключение Mission Core · v1' : active ? 'Ключ выдан' : 'Нет действующего ключа'} <ResourceRow title={app.name} metadata={legacy ? 'Подключение Mission Core · v1' : active ? 'Ключ выдан' : 'Нет действующего ключа'}
actions={<> actions={<>
{open && !legacy ? <> {open && !legacy ? <>
<IconButton label={`История ключей ${app.name}`} aria-pressed={!hiddenHistory.includes(app.id)} onClick={() => setHiddenHistory(toggle(hiddenHistory, app.id))}><Icon name={hiddenHistory.includes(app.id) ? 'eye-off' : 'eye'} /></IconButton>
{canManage ? <> {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={`${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> <IconButton label={`Удалить приложение ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'application-delete', fields: { integrationId: app.id }, text: `Удалить «${app.name}» со всеми ключами и связями с контурами на этом VPS? Доступ приложения прекратится. Устройства, данные контуров и другие приложения сохранятся.` })}><Icon name="trash" /></IconButton>
@@ -81,7 +114,8 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
<dl className="b2-tracker-facts"><dt>Тип подключения</dt><dd>Прямая привязка Mission Core</dd><dt>ID приложения</dt><dd>{app.id}</dd></dl> <dl className="b2-tracker-facts"><dt>Тип подключения</dt><dd>Прямая привязка Mission Core</dd><dt>ID приложения</dt><dd>{app.id}</dd></dl>
<p>Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.</p> <p>Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.</p>
</> : <> </> : <>
<ResourceList>{app.credentials.filter((item) => item.enabled || !hiddenHistory.includes(app.id)).map((item) => { <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 keyOpen = credentialRows.includes(item.client_id);
const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null; const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null;
return <li key={item.client_id} className="b2-disclosure"> return <li key={item.client_id} className="b2-disclosure">
@@ -107,10 +141,14 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
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: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]} sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]}
activeSection={section} onSectionChange={setSection} onClose={onClose} activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => { headerActions={<>
{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 () => {
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></>}>
<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} metadata="Подключение Device Core к серверу ARNavi" <ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>} status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>}
@@ -126,39 +164,63 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
<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 className="b2-actions"><Button disabled={busy} onClick={() => { setImportOpen(false); setConnection(''); }}>Отмена</Button><Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>{status?.connected ? 'Обновить доступ Device Core' : 'Подключить Device Core'}</Button></div>
</div></SettingsCard> : null} </div></SettingsCard> : null}
</> : null} </> : null}
{section === 'contours' ? <ResourceList>{projects.map((item) => { {section === 'contours' ? <>
const links = (status?.links || []).filter((link) => link.projectRef === item.projectRef); <h3 id="b2-contours-heading" className="b2-section-heading b2-contours-heading">Контуры</h3>
const linked = links.length > 0, open = expanded.includes(item.projectRef); {newContour ? <SettingsCard title="Новый контур VPS" description="Создаётся на этом VPS и связывается с выбранным проектом Device Core."><div className="b2-settings">
const apps = (status?.applications || []).filter((app) => app.authority !== 'host' && links.some((link) => app.grants[link.contourId])); <TextField label="Название контура" value={contourName} disabled={busy || Boolean(contourIntent)} maxLength={160} autoFocus onChange={event => setContourName(event.target.value)} />
const available = (status?.contours || []).filter((contour) => !status?.links?.some((link) => link.contourId === contour.id)); <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} />
return <li key={item.projectRef} className="b2-disclosure"> <div className="b2-actions"><Button disabled={busy} onClick={() => { setNewContour(false); setContourIntent(null); }}>Отмена</Button><Button disabled={busy || !contourName.trim() || !targetProject} loading={pending === 'contour-connect'} onClick={() => {
<ResourceRow title={item.name} metadata={linked ? 'Контур VPS связан с проектом' : 'Проект Device Core'} const intent = contourIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: contourName.trim(), projectRef: targetProject };
actions={<> setContourIntent(intent); void run('contour-connect', { name: intent.name, targetProjectRef: intent.projectRef }, intent.id);
{open && linked && canManage ? <IconButton label={`Добавить приложение в ${item.name}`} disabled={busy} onClick={() => { setCreating(item.projectRef); setName(''); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : null} }}>{contourIntent ? 'Уточнить создание' : 'Создать контур'}</Button></div>
<IconButton label={`Контур ${item.name}`} aria-expanded={open} aria-controls={`contour-${item.projectRef}`} onClick={() => setExpanded(toggle(expanded, item.projectRef))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton> </div></SettingsCard> : null}
{!status?.contours?.length && !busy ? <p>На VPS ещё нет контуров. Создайте первый кнопкой «+» в шапке настроек.</p> : null}
<ResourceList className="b2-contours" aria-labelledby="b2-contours-heading">{(status?.contours || []).map(contour => {
const links = (status?.links || []).filter(link => link.contourId === contour.id);
const open = expanded.includes(contour.id);
const apps = (status?.applications || []).filter(app => app.authority !== 'host' && app.grants[contour.id]);
const available = projects.filter(item => item.access.capabilities.includes('infrastructure.manage') && !links.some(link => link.projectRef === item.projectRef));
const projectNames = links.map(link => projects.find(item => item.projectRef === link.projectRef)?.name || 'Недоступный проект');
return <li key={contour.id}>
<GlassSurface className="b2-contour" data-expanded={open} materialRim={false}>
<ResourceRow className="b2-contour__header" title={contour.name} metadata={links.length ? `Проекты: ${projectNames.join(', ')}` : 'Не связан с проектами Device Core'} actions={<>
{open && canManage ? <IconButton label={`Добавить приложение в ${contour.name}`} disabled={busy} onClick={() => { setCreating(contour.id); setName(''); setAccess('read'); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : 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>
</>} /> </>} />
{open ? <div id={`contour-${item.projectRef}`} className="b2-disclosure__body"> {open ? <div id={`contour-${contour.id}`} className="b2-disclosure__body">
{!linked ? <> <div className="b2-section-heading"><strong>Проекты Device Core</strong></div>
{canManage ? <Button disabled={busy} loading={pending === 'project-connect'} onClick={() => void run('project-connect', { targetProjectRef: item.projectRef })}>Подключить проект к VPS</Button> : null} <p>Связанные проекты видят один реестр устройств этого контура. Ключи внешних приложений управляются отдельно.</p>
{available.length ? <Select label="Связать с существующим контуром" value="" options={[{ value: '', label: 'Выбрать контур VPS' }, ...available.map((c) => ({ value: c.id, label: c.name }))]} onChange={(contourId) => { if (contourId) void run('link', { contourId, targetProjectRef: item.projectRef }); }} disabled={busy} /> : null} {links.length ? <ResourceList>{links.map(link => {
</> : <> const item = projects.find(value => value.projectRef === link.projectRef);
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>;
})}</ResourceList> : null}
{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> <div className="b2-section-heading"><strong>Приложения и ключи</strong></div>
<ResourceList>{apps.map(applicationRow)}</ResourceList> <ResourceList>{apps.map(applicationRow)}</ResourceList>
{!apps.length && creating !== item.projectRef ? <p>Ключи приложений ещё не выданы</p> : null} {!apps.length && creating !== contour.id ? <p>Ключи приложений ещё не выданы</p> : null}
{creating === item.projectRef ? <div className="b2-settings"> {creating === contour.id ? <div className="b2-settings">
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={(event) => setName(event.target.value)} /> <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={() => { <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() }; const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim(), access };
setCreationIntent(intent); setCreationIntent(intent);
void run('application-connect', { name: intent.name, contourId: links[0].contourId }, intent.id); void run('application-connect', { name: intent.name, contourId: contour.id, access: intent.access }, intent.id);
}}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div> }}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div>
</div> : null} </div> : null}
</>} </div> : null}
</div> : null} </GlassSurface>
</li>; </li>;
})}</ResourceList> : null} })}</ResourceList>
</> : null}
</div> </div>
</FeatureSettingsWindow> </FeatureSettingsWindow>
<ConfirmationModal open={Boolean(confirm)} title={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Ключ приложения'} description={confirm?.text} confirmLabel={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Подтвердить'} cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && !busy && await run(confirm.action, confirm.fields)) setConfirm(null); }} /> <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); }} />
</>; </>;
} }
@@ -10,7 +10,7 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
const [data,setData]=useState<TrackerState|null>(null), [name,setName]=useState(device.name); const [data,setData]=useState<TrackerState|null>(null), [name,setName]=useState(device.name);
const [policy,setPolicy]=useState<Policy>({parameters:{},connectivity:{mode:'preserve'}}); const [policy,setPolicy]=useState<Policy>({parameters:{},connectivity:{mode:'preserve'}});
const [profile,setProfile]=useState(''),[profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false); const [profile,setProfile]=useState(''),[profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false);
const [busy,setBusy]=useState('load'),[dirty,setDirty]=useState(false),[commandsOpen,setCommandsOpen]=useState(initialSection==='commands'); const [busy,setBusy]=useState('load'),[dirty,setDirty]=useState(false),[commandRefresh,setCommandRefresh]=useState(0);
const [bootstrapFirmware,setBootstrapFirmware]=useState(''),[bootstrapPassword,setBootstrapPassword]=useState(''); const [bootstrapFirmware,setBootstrapFirmware]=useState(''),[bootstrapPassword,setBootstrapPassword]=useState('');
const profileIntent=useRef<Record<string,unknown>|null>(null); const profileIntent=useRef<Record<string,unknown>|null>(null);
const [latest,setLatest]=useState<Operation|null>(null); const [latest,setLatest]=useState<Operation|null>(null);
@@ -65,11 +65,11 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000); const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
} }
return <> return <>
<FeatureSettingsWindow open={!profileOpen&&!commandsOpen} title="Настройки устройства" subtitle={`ARNavi B2 · ${device.number}`} <FeatureSettingsWindow open={!profileOpen} title="Настройки устройства" subtitle={`ARNavi B2 · ${device.number}`}
identity={{title:'ARNavi B2',subtitle:`IMEI ${device.identifier.masked}`,avatarLabel:'AR'}} 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}))]} 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} activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={<IconButton label="Обновить сведения о трекере" disabled={Boolean(busy)} loading={busy==='refresh'} onClick={()=>void run('refresh',async()=>{await refresh();})}><Icon name="refresh" /></IconButton>} 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'&&section!=='firmware'?<WindowFooterActions><Button disabled={disabled||!dirty||!data} loading={busy==='save'} onClick={()=>void run('save',async()=>{await save();})}>Сохранить настройки</Button><Button disabled={disabled||!data} onClick={()=>{profileIntent.current=null;setProfileName('');setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>:undefined}> footer={section!=='commands'&&section!=='firmware'?<WindowFooterActions><Button disabled={disabled||!dirty||!data} loading={busy==='save'} onClick={()=>void run('save',async()=>{await save();})}>Сохранить настройки</Button><Button disabled={disabled||!data} onClick={()=>{profileIntent.current=null;setProfileName('');setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>:undefined}>
<div className="b2-tracker-form" aria-busy={Boolean(busy)}> <div className="b2-tracker-form" aria-busy={Boolean(busy)}>
<StatusBadge tone={connected?'success':'neutral'}>{connected?'Передаёт данные на VPS':data?'Нет свежих данных':'Загрузка…'}</StatusBadge> <StatusBadge tone={connected?'success':'neutral'}>{connected?'Передаёт данные на VPS':data?'Нет свежих данных':'Загрузка…'}</StatusBadge>
@@ -102,7 +102,7 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
</div></SettingsCard> </div></SettingsCard>
</>:null} </>: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} {groupNames.includes(section)&&data?<><span>Пустое поле — сохранить значение трекера.</span>{data.fields.filter(field=>field.group===section).map(field=><TextField key={field.id} label={field.label} hint={`${field.minimum} … ${field.maximum}`} type="number" step={1} min={field.minimum} max={field.maximum} disabled={disabled||!Object.hasOwn(data.observed?.parameters||{},field.id)} placeholder={String(data.observed?.parameters[field.id]??'Недоступно на этой прошивке')} value={policy.parameters[field.id]??''} onChange={event=>{const parameters={...policy.parameters};if(event.target.value==='')delete parameters[field.id];else parameters[field.id]=Number(event.target.value);edit({...policy,parameters});}} />)}</>:null}
{section==='commands'?<SettingsCard title="Команды устройства"><Button onClick={()=>setCommandsOpen(true)}>Открыть консоль команд</Button></SettingsCard>:null} <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> {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>}> <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));}} /> <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));}} />
@@ -111,25 +111,26 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
</SettingsCard></>:null} </SettingsCard></>:null}
</div> </div>
</FeatureSettingsWindow> </FeatureSettingsWindow>
{commandsOpen?<B2CommandWindow projectRef={projectRef} device={device} data={data} canCommand={canCommand} onClose={()=>setCommandsOpen(false)} onError={onError} />:null}
<Window open={profileOpen} title="Сохранить профиль" size="sm" onClose={()=>setProfileOpen(false)} footer={<WindowFooterActions><Button loading={busy==='profile'} disabled={Boolean(busy)||!profileName.trim()} onClick={()=>void run('profile',async()=>{profileIntent.current ||= {action:'profile-save',id:newIntent(),name:profileName,policy};try{await request(profileIntent.current);profileIntent.current=null;}catch(error){if(error instanceof B2RequestError&&error.rejected)profileIntent.current=null;throw error;}setProfileOpen(false);await refresh();})}>Сохранить профиль</Button></WindowFooterActions>}><TextField label="Название профиля" disabled={Boolean(busy)||Boolean(profileIntent.current)} autoFocus value={profileName} onChange={event=>setProfileName(event.target.value)} /></Window> <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}}])]; const presets=[{id:'position',label:'Запросить координаты',command:{kind:'request-position'}},{id:'restart',label:'Перезапустить B2',command:{kind:'restart'}},...[4,5,6].flatMap(pin=>[...([true,false] as const).map(enabled=>({id:`pin${pin}-${enabled}`,label:`${enabled?'Включить':'Выключить'} выход PIN${pin}`,command:{kind:'set-output',pin,enabled}})),{id:`pin${pin}-pulse`,label:`Импульс PIN${pin} · 5 с`,command:{kind:'pulse-output',pin,seconds:5}}])];
function B2CommandWindow({projectRef,device,data,canCommand,onClose,onError}:{projectRef:string;device:TrackerRef;data:TrackerState|null;canCommand:boolean;onClose:()=>void;onError:(error:unknown)=>void}) { 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 [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 [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 intent=useRef<Record<string,unknown>|null>(null),alive=useRef(true);
const request=<T,>(body:Record<string,unknown>)=>trackerRequest<T>(projectRef,device,body); 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);}} async function refresh(append=false) {const result=await request<{items:Operation[];before:number|null}>({action:'journal',...(append&&before?{before}:{})});if(alive.current){setRows(old=>append?[...old,...result.items]:result.items);setBefore(result.before);}}
useEffect(()=>{alive.current=true;void refresh().catch(onError);return()=>{alive.current=false;};},[]); useEffect(()=>{alive.current=true;return()=>{alive.current=false;};},[]);
useEffect(()=>{if(!rows.some(row=>['queued','dispatched'].includes(row.state)))return;const timer=setTimeout(()=>void refresh().catch(onError),3000);return()=>clearTimeout(timer);},[rows]); 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 selected=presets.find(item=>item.id===selection)!;
const pin='pin' in selected.command?selected.command.pin:null; const pin='pin' in selected.command?selected.command.pin:null;
const available=data?.capabilities.configuration&&(!pin||data.observed?.output_modes[String(pin)]===1); 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);}} async function send(command:Record<string,unknown>=selected.command) {setBusy(true);try {intent.current ||= {action:'command',id:newIntent(),command};await request(intent.current);intent.current=null;await refresh();}catch(error){if(error instanceof B2RequestError&&error.rejected)intent.current=null;onError(error);}finally{setBusy(false);}}
return <Window open title="Команды устройства" subtitle={`ARNavi B2 · ${device.number}`} size="lg" onClose={onClose} headerActions={<IconButton label="Обновить журнал команд" disabled={busy} onClick={()=>void refresh().catch(onError)}><Icon name="refresh" /></IconButton>}> // Keep the panel mounted across tabs so an uncertain send retains its intent ID.
return <div hidden={!active}>
<div className="b2-tracker-form"> <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} /> <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} {pin?<span>Подтверждение доставки не определяет положение контактов реле.</span>:null}
@@ -139,6 +140,6 @@ function B2CommandWindow({projectRef,device,data,canCommand,onClose,onError}:{pr
{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} {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> </li>)}</ResourceList>{!rows.length?<span>Команд пока нет</span>:null}{before?<Button onClick={()=>void refresh(true).catch(onError)}>Предыдущие команды</Button>:null}</SettingsCard>
</div> </div>
</Window>; </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; } 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 -1
View File
@@ -2,6 +2,7 @@ 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 };
@@ -18,7 +19,7 @@ const messages: Record<string, string> = {
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.',
+5
View File
@@ -6,6 +6,11 @@
.b2-disclosure { display: grid; gap: var(--nodedc-space-2); } .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-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-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-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 { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr); gap: .65rem 1rem; margin: 0; font-size: var(--nodedc-font-size-sm); }
@@ -1,10 +1,10 @@
{ {
"version": "0.2.3", "version": "0.2.5",
"filename": "nodedc-arnavi-vps-0.2.3.pyz", "filename": "nodedc-arnavi-vps-0.2.5.pyz",
"sha256": "0d52c38d0e8afd7c1d72bb59e01d20328f8ac2cd8bb2abfd50f3d265db4bcaf4", "sha256": "d9a822ca7c2498841a6fd13fddac27da4fc22366931ba8980b97c66c159a383f",
"bytes": 16126822, "bytes": 16129246,
"sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git", "sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git",
"sourceCommit": "973e994f02176d438e8ff42f17baccc5fddb6184", "sourceCommit": "193253dd48a1c6390ea4c5e500693123b88ce2ea",
"manifestSha256": "b5aa33a08addace744b0ffecc23777fbe56a8d1ea58f6dd59e5161082a6a847a", "manifestSha256": "139a3c1d7f3e8266e2154586783133078311aa9dae76d74ed229aab16f816197",
"environment": "ubuntu-24.04-amd64" "environment": "ubuntu-24.04-amd64"
} }
+3
View File
@@ -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>;
+71
View File
@@ -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 = '';
}
}
-18
View File
@@ -1222,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;
@@ -1646,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;
} }
@@ -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;
+6
View File
@@ -38,3 +38,9 @@ Legacy Mission Core access is visible as a compatible connection.
- Verify the existing home video/media survives releases. - Verify the existing home video/media survives releases.
- Full B2 command/settings parity remains a distinct domain integration task; - Full B2 command/settings parity remains a distinct domain integration task;
a UI release or successful deployment must not be recorded as its completion. a UI release or successful deployment must not be recorded as its completion.
The AppHeader right slot consumes the complete shared UserProfileMenu. Its
canonical order is profile label, inbox menu button, avatar; interface settings
remain a permission-controlled menu action. Do not add a HeaderProfile wrapper,
separate settings gear, or local spacing/geometry overrides.
+171
View File
@@ -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.
+41
View File
@@ -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
закрывают настройки целиком. Переключение вкладок сохраняет выбор команды,
фильтр и идентификатор незавершённой отправки; возврат обновляет журнал.
Кнопка обновления в шапке на вкладке команд обновляет журнал и состояние трекера.
+2 -2
View File
@@ -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": "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2" "commit": "06cb8ad4cd193ae1b4b1ac40a513fd642e12b878"
}, },
"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()
+109
View File
@@ -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)
+244
View File
@@ -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 });
}
+1 -1
View File
@@ -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 });
} }
@@ -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.
@@ -164,10 +168,68 @@ export class B2Infrastructure {
// borrow the host administrator credential from another project. // borrow the host administrator credential from another project.
return remote.call(`/v2/contours/${contourId}/devices/${deviceId}/settings`, request); 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 === '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 === '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;
@@ -214,44 +276,57 @@ 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' || action === 'project-connect') { } else if (['link', 'unlink', 'project-connect', 'contour-connect'].includes(action)) {
fields(input, action === 'link' ? ['contourId', 'targetProjectRef'] : ['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);
let contour; let contour;
if (action === 'project-connect') { if (action === 'unlink') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403); contour = opaque(input.contourId);
const linked = links.filter((link) => link.project_id === targetId); 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]);
if (linked.length > 1) throw b2Error('b2_conflict', 409); result = { linked: false, contourId: contour, projectRef: `project:${targetId}` };
// Stable project identity makes a retry recover the same contour. } else {
contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', { if (action === 'contour-connect') {
key: 'dc-' + targetId, name: target.name, if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
})).id; if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
} else contour = opaque(input.contourId); if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
const permitted = await remote.call('/v2/contours'); // Retry a lost response without creating another remote contour.
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403); contour = (await remote.call('/v2/management/contours', { key: 'dc-' + requestId, name: input.name.trim() })).id;
const current = links.find((link) => link.contour_id === contour); } else if (action === 'project-connect') {
if (current && current.project_id !== targetId) throw b2Error('b2_contour_already_linked', 409); if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref) const linked = links.filter((link) => link.project_id === targetId);
values($1,$2,$3,$4,$5) on conflict(source_id,contour_id) do nothing`, if (linked.length > 1) throw b2Error('b2_conflict', 409);
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]); // Stable project identity makes a retry recover the same contour.
if (targetId !== projectId) { contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', {
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]; key: 'dc-' + targetId, name: target.name,
if (!related) { })).id;
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure', } else contour = opaque(input.contourId);
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', { const permitted = await remote.call('/v2/contours');
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name, if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
providerRef: host.provider_ref, externalRef: source.remote_host_id, if (links.some((link) => link.contour_id === contour && link.project_id !== targetId)
managementCredentialRef: null, lifecycleState: 'active', && !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_host_views(host_id,project_id,owner_scope_id,source_id) values($1,$2,$3,$4,$5) on conflict do nothing`,
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]); [source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
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];
if (!related) {
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name,
providerRef: host.provider_ref, externalRef: source.remote_host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]);
}
} }
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);
@@ -273,13 +348,14 @@ export class B2Infrastructure {
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') { } else if (action === 'application-connect') {
fields(input, ['name', 'contourId']); fields(input, ['name', 'contourId', 'access']);
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid'); if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
const contour = opaque(input.contourId); const contour = opaque(input.contourId);
if (!links.some((link) => link.contour_id === contour)) throw b2Error('b2_access_denied', 403); 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'); if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
const app = await remote.call('/v2/management/applications', { const app = await remote.call('/v2/management/applications', {
key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: 'manage' }, key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: access },
}); });
// The VPS reserves issuance before returning a one-time secret. If // The VPS reserves issuance before returning a one-time secret. If
// the response is lost, status exposes the app for explicit reissue. // the response is lost, status exposes the app for explicit reissue.
@@ -19,10 +19,11 @@ 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,
name: 'Test project', 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,
@@ -231,10 +232,50 @@ test('application creation and issuance use one server-generated request identit
assert.equal(result.id, app); assert.equal(result.id, app);
assert.ok(result.connection); assert.ok(result.connection);
assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false); assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false);
await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32) }, requestId), /b2_access_denied/); 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); 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 () => { test('tracker settings keep project and contour authority across remote calls', async () => {
const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = []; const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = [];
const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect(); const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect();
@@ -318,3 +359,56 @@ test('application deletion requires company and credential authority and forward
assert.deepEqual(calls, [{ path: '/v2/management/applications/delete', body: { integration_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'); 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' } }));
});