27 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
DCCONSTRUCTIONS 010fab999e Compact contour actions and delete VPS applications with all access
Device Core qualification / qualify (push) Successful in 7m19s
2026-10-01 01:10:56 +03:00
DCCONSTRUCTIONS 539c0a60b8 Download VPS installer with session and verify release digest
Device Core qualification / qualify (push) Successful in 6m30s
2026-10-01 00:21:27 +03:00
DCCONSTRUCTIONS 53dbd7483e Complete ARNavi VPS onboarding and contextual key controls
Device Core qualification / qualify (push) Successful in 6m45s
2026-09-30 23:57:17 +03:00
DCCONSTRUCTIONS 19aa5e2796 Align tracker footer actions and text with Mission settings
Device Core qualification / qualify (push) Successful in 6m28s
2026-09-30 23:02:25 +03:00
DCCONSTRUCTIONS 1266b06f9b Align tracker receipt states and attempt history with Mission Core
Device Core qualification / qualify (push) Successful in 6m37s
2026-09-30 22:48:50 +03:00
DCCONSTRUCTIONS 8941769b4c Bring Device Core settings to Mission UI and expose scoped B2 controls
Device Core qualification / qualify (push) Successful in 6m40s
2026-09-30 22:43:54 +03:00
DCCONSTRUCTIONS 8031ed76a2 fix(ui): adopt viewport-safe shared settings windows
Device Core qualification / qualify (push) Successful in 6m52s
2026-09-30 21:34:57 +03:00
DCCONSTRUCTIONS a860b00310 fix(ui): align project overview counts and complete functional labels
Device Core qualification / qualify (push) Successful in 8m43s
2026-09-30 21:27:53 +03:00
DCCONSTRUCTIONS b3b0f900c5 refactor(ui): unify registry lists and functional form labels
Device Core qualification / qualify (push) Successful in 8m18s
2026-09-30 20:59:12 +03:00
DCCONSTRUCTIONS b8d240a0a0 feat(device-manager): align functional UI with Mission Core interaction patterns
Device Core qualification / qualify (push) Successful in 8m53s
2026-09-30 20:53:19 +03:00
DCCONSTRUCTIONS 7072b86fb8 Polish contour settings spacing and zero-count monitoring
Device Core qualification / qualify (push) Successful in 7m32s
2026-09-30 19:57:03 +03:00
DCCONSTRUCTIONS c0487ca17b Restructure ARNavi contour UX and expose project-scoped VPS inventory
Device Core qualification / qualify (push) Successful in 7m42s
2026-09-30 19:35:18 +03:00
DCCONSTRUCTIONS 1bf3ee6d41 docs: record live shared VPS infrastructure acceptance 2026-09-30 18:51:59 +03:00
DCCONSTRUCTIONS 880d260ccb Save issued B2 application keys as downloadable JSON packages
Device Core qualification / qualify (push) Successful in 6m30s
2026-09-30 17:53:31 +03:00
DCCONSTRUCTIONS 341d1f87e6 Qualify the standalone Core runtime lock used by Docker
Device Core qualification / qualify (push) Successful in 5m54s
2026-09-30 17:51:38 +03:00
DCCONSTRUCTIONS f4f63bccf3 Import VPS connection packages from local JSON files
Device Core qualification / qualify (push) Successful in 6m24s
2026-09-30 17:34:13 +03:00
50 changed files with 2822 additions and 846 deletions
+3 -1
View File
@@ -58,7 +58,9 @@ platform runner registry is validated separately in `NODEDC_PLATFORM`.
The accepted Device Core policy is automatic deployment after a push to `main`
passes its checks. See [Continuous deployment](docs/CONTINUOUS_DEPLOYMENT.md)
for the pinned source qualification workflow, Synology setup and activation
status. Automatic production installation is not enabled yet.
status. Automatic production installation is active: the Synology controller fetches
qualified releases over outbound HTTPS and invokes the canonical runner.
No operator Mac or new inbound port is required.
Artifact builders in `infra/deploy-runner` emit data-only tarballs. They never
orchestrate Docker or mutate a live host. Promotion remains the established
@@ -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());
});
@@ -84,7 +84,7 @@ test("Device Core overview follows the Mission Core landing-stage geometry", asy
assert.ok(!client.includes('<GlassSurface className="device-manager-home"'));
});
test("VPS inventory and monitoring follow the Mission Core system workspace geometry", async () => {
test("host hardware monitoring retains the established geometry", async () => {
const client = await readFile(
new URL("../src/DeviceControlViews.tsx", import.meta.url),
"utf8",
@@ -99,21 +99,7 @@ test("VPS inventory and monitoring follow the Mission Core system workspace geom
);
for (const expected of [
'className="infrastructure-system-workspace"',
'className="infrastructure-system-workspace host-monitoring-workspace"',
'className="infrastructure-overview-block"',
'className="infrastructure-section infrastructure-hosts-block"',
'className="infrastructure-host-list"',
'className="infrastructure-host-card__summary"',
'className="infrastructure-host-card__freshness"',
'className="infrastructure-host-card__toggle"',
'className="infrastructure-host-card__details"',
'className="infrastructure-host-relations"',
'aria-expanded={expanded}',
'const [expandedHostRefs, setExpandedHostRefs] = useState<Set<string>>',
'topology.endpoints.filter((item) => item.hostRef === host.hostRef)',
'topology.deployments.filter((item) => item.hostRef === host.hostRef)',
'topology.serviceInstances.filter((item) => item.hostRef === host.hostRef)',
'className="host-monitoring-series-grid"',
'className="host-monitoring-hardware"',
'className="host-monitoring-hardware-facts"',
@@ -136,7 +122,6 @@ test("VPS inventory and monitoring follow the Mission Core system workspace geom
".infrastructure-host-relations {",
"grid-template-columns: repeat(3, minmax(0, 1fr));",
"grid-template-columns: repeat(4, minmax(0, 1fr));",
"background: var(--infrastructure-panel-soft);",
".host-monitoring-series polyline {",
"stroke: var(--nodedc-text-primary);",
".host-monitoring-hardware-facts {",
@@ -148,6 +133,7 @@ test("VPS inventory and monitoring follow the Mission Core system workspace geom
assert.ok(!infrastructureSource.includes('title="Deployments и endpoints"'));
assert.ok(!infrastructureSource.includes("ceiling={100}"));
assert.ok(!infrastructureSource.includes("Канонический ontology catalog"));
assert.ok(!styles.includes("background: var(--infrastructure-panel-soft);"), "Functional panels must not add nested black surfaces");
assert.ok(!styles.includes(".host-telemetry-metric,"));
assert.ok(!styles.includes(".host-telemetry-facts"));
});
@@ -180,7 +180,7 @@ export function createDeviceManagerServer({
}
const requestId = singleHeader(request.headers["idempotency-key"]);
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);
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[0].actor.userRef, 'user:local-device-admin');
});
test('B2 USB envelope fits the bounded route while oversized requests are rejected', async (t) => {
const auth = createDeviceManagerAuth({ env: { NODEDC_DEVICE_MANAGER_AUTH_REQUIRED: 'false' } });
let calls = 0;
const coreClient = { ...createLocalPreviewDeviceCore(), async b2Infrastructure(actor, body) { calls++; return { bytes: body.request.usb.settings.length }; } };
const server = createDeviceManagerServer({ auth, coreClient });
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
t.after(() => new Promise(resolve => server.close(resolve)));
const origin = `http://127.0.0.1:${server.address().port}`;
for (const [size, status] of [[88000, 200], [140000, 413]]) {
const response = await fetch(origin + '/api/device-manager/b2/infrastructure', { method: 'POST', headers: { origin, 'content-type': 'application/json', 'idempotency-key': 'b'.repeat(32) }, body: JSON.stringify({ action: 'enrollment', request: { action: 'inspect', usb: { settings: 'A'.repeat(size) } } }) });
assert.equal(response.status, status); await response.arrayBuffer();
}
assert.equal(calls, 1);
});
@@ -0,0 +1,17 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
test('downloadable VPS installer matches its immutable release metadata and deploy size limit', async () => {
const metadata = JSON.parse(await readFile(new URL('../src/b2/installer-release.json', import.meta.url), 'utf8'));
assert.match(metadata.filename, /^nodedc-arnavi-vps-\d+\.\d+\.\d+\.pyz$/);
assert.equal(metadata.environment, 'ubuntu-24.04-amd64');
assert.match(metadata.sourceCommit, /^[a-f0-9]{40}$/);
assert.equal(metadata.sourceRepository, 'https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git');
const file = await readFile(new URL('../public/installers/' + metadata.filename, import.meta.url));
assert.equal(file.length, metadata.bytes);
assert.ok(file.length < 16 * 1024 * 1024);
assert.equal(createHash('sha256').update(file).digest('hex'), metadata.sha256);
assert.equal(file.subarray(0, 2).toString(), 'PK');
});
File diff suppressed because it is too large Load Diff
+65 -143
View File
@@ -1,7 +1,10 @@
import { useEffect, useMemo, useRef, useState } from "react";
import {
Button,
GlassSurface,
FeatureSettingsWindow,
ConfirmationModal,
ResourceList,
ResourceRow,
Icon,
IconButton,
Select,
@@ -14,6 +17,7 @@ import {
createConfigurationRevision,
setDesiredConfiguration,
updateDevice,
archiveDevice,
} from "./api";
import {
accessLabel,
@@ -27,58 +31,16 @@ import type {
SessionView,
} from "./types";
import { B2TrackerSettings } from "./b2/B2TrackerSettings";
import type { TrackerRef } from "./b2/tracker";
import { useB2Inventory } from "./b2/useB2Inventory";
export type DeviceInventoryDetailState = {
deviceRef: string;
sectionId: string;
editing: boolean;
};
export function DeviceDetailHeaderTools({
device,
detail,
canEdit,
onDetailChange,
}: {
device: DeviceView;
detail: DeviceInventoryDetailState;
canEdit: boolean;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
const catalog = getDeviceProfileCatalog(device.modelProfileRef);
const activeSection = catalog.sections.find((section) => section.id === detail.sectionId)
?? catalog.sections[0];
return (
<div className="device-detail-header-tools">
<Select
className="device-detail-section-select"
label="Раздел устройства"
value={activeSection?.id ?? catalog.sections[0]?.id ?? "passport"}
options={catalog.sections.map((section) => ({
value: section.id,
label: section.label,
}))}
onChange={(sectionId) => onDetailChange({ ...detail, sectionId })}
placement="bottom-end"
minMenuWidth={320}
menuWidth="anchor"
variant="split"
/>
<IconButton
label={detail.editing ? "Завершить редактирование" : "Редактировать устройство"}
disabled={!canEdit}
data-active={detail.editing || undefined}
onClick={() => onDetailChange({
...detail,
editing: !detail.editing,
})}
>
<Icon name="edit" size={17} />
</IconButton>
</div>
);
}
export function DeviceInventoryView({
workspace,
canClaim,
@@ -100,15 +62,22 @@ export function DeviceInventoryView({
onError: (reason: unknown) => void;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
const [tracker, setTracker] = useState<{ device: TrackerRef; projectRef: string; section: string } | null>(null);
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const [typeFilter, setTypeFilter] = useState("all");
const [archiveTarget, setArchiveTarget] = useState<DeviceView | null>(null);
const [archiving, setArchiving] = useState(false);
const [statusFilter, setStatusFilter] = useState("all");
const [sortOrder, setSortOrder] = useState("activity");
const selectedDevice = workspace.devices.find(
(device) => device.deviceRef === detail?.deviceRef,
) ?? null;
const pendingEnrollments = workspace.enrollments.filter(
(enrollment) => enrollment.lifecycleState !== "claimed",
(enrollment) => ["pending", "observed"].includes(enrollment.lifecycleState),
);
const deviceRows = useMemo(() => workspace.devices
.filter((device) => statusFilter === "archived" ? device.lifecycleState === "suspended" : !["suspended", "retired"].includes(device.lifecycleState))
.filter((device) => typeFilter === "all" || device.modelProfileRef.toLowerCase().includes("b2"))
.map((device) => {
const session = latestSession(workspace, device);
const online = session?.lifecycleState === "online" || device.session?.state === "online";
@@ -128,7 +97,7 @@ export function DeviceInventoryView({
return left.online ? -1 : 1;
}
return String(right.lastSeenAt || "").localeCompare(String(left.lastSeenAt || ""));
}), [sortOrder, statusFilter, workspace]);
}), [sortOrder, statusFilter, typeFilter, workspace]);
useEffect(() => {
if (detail?.deviceRef && !selectedDevice) onDetailChange(null);
@@ -143,32 +112,29 @@ export function DeviceInventoryView({
return () => window.clearInterval(timer);
}, [detail?.deviceRef, onError, onPoll]);
if (selectedDevice && detail) {
return (
<DeviceDetailView
device={selectedDevice}
detail={detail}
workspace={workspace}
canConfigure={canConfigure}
canManageProject={canManageProject}
onDetailChange={onDetailChange}
onSaved={onPoll}
onError={onError}
onBack={() => onDetailChange(null)}
/>
);
}
const remoteRows = (b2.data?.items || []).filter(() => !['pending', 'archived', 'active', 'inactive'].includes(statusFilter))
.sort((a, b) => a.name.localeCompare(b.name, 'ru'));
const count = workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + (b2.data?.items.length || 0);
return (
<div className="device-inventory">
{tracker && tracker.projectRef===workspace.project.projectRef ? <B2TrackerSettings key={`${tracker.projectRef}:${tracker.device.id}`} projectRef={tracker.projectRef} device={tracker.device} initialSection={tracker.section} onClose={()=>setTracker(null)} onError={onError} onChanged={onPoll} canConfigure={canConfigure} canCommand={workspace.project.access.capabilities.includes('command.dispatch')} /> : null}
{selectedDevice && detail ? <DeviceDetailView key={selectedDevice.deviceRef} device={selectedDevice} detail={detail} workspace={workspace}
canConfigure={canConfigure} canManageProject={canManageProject} onDetailChange={onDetailChange} onSaved={onPoll} onError={onError} onBack={() => onDetailChange(null)} /> : null}
<ConfirmationModal open={Boolean(archiveTarget)} title={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить устройство?' : 'Перенести устройство в архив?'} description={archiveTarget?.displayName} confirmLabel={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => {
if (!archiveTarget || archiving) return;
setArchiving(true);
try { await archiveDevice(workspace.project.projectRef, archiveTarget.deviceRef, archiveTarget.lifecycleState !== 'suspended'); setArchiveTarget(null); await onPoll(); } catch (reason) { onError(reason); } finally { setArchiving(false); }
}} />
<div className="device-manager-panel-toolbar device-inventory__toolbar">
<div>
<strong>Реестр устройств</strong>
<p>{workspace.devices.length} зарегистрировано · {pendingEnrollments.length} ожидают подключения</p>
<p>{count} зарегистрировано · {pendingEnrollments.length} ожидают подключения</p>
</div>
</div>
<div className="device-inventory__filters" aria-label="Фильтры устройств">
<Select label="Тип устройства" value={typeFilter} onChange={setTypeFilter} options={[{ value: 'all', label: 'Все типы' }, { value: 'arnavi', label: 'ARNavi B2' }]} />
<Select
label="Состояние"
value={statusFilter}
@@ -177,6 +143,7 @@ export function DeviceInventoryView({
{ value: "active", label: "Активные" },
{ value: "inactive", label: "Неактивные" },
{ value: "pending", label: "Ожидают подключения" },
{ value: "archived", label: "Архив" },
]}
onChange={setStatusFilter}
/>
@@ -193,54 +160,22 @@ export function DeviceInventoryView({
/>
</div>
{statusFilter !== "pending" && !deviceRows.length ? (
<GlassSurface className="device-manager-empty device-inventory__empty" padding="lg" tone="soft">
<Icon name="inbox" size={24} />
<h3>{workspace.devices.length ? "Устройств с таким состоянием нет" : "В проекте пока нет устройств"}</h3>
<p>Добавьте разрешённый трекер через «плюс». Идентификатор попадёт в Device Core по защищённому процессу подключения.</p>
</GlassSurface>
) : statusFilter !== "pending" ? (
<GlassSurface className="device-inventory-table" padding="sm" tone="soft" role="table" aria-label="Устройства проекта">
<div className="device-inventory-table__head" role="row">
<span role="columnheader">Устройство</span>
<span role="columnheader">Профиль</span>
<span role="columnheader">IMEI</span>
<span role="columnheader">ID интеграционного устройства</span>
<span role="columnheader">Канал</span>
<span role="columnheader">Последний пакет</span>
<span aria-hidden="true" />
</div>
{deviceRows.map(({ device, session, online, lastSeenAt }) => {
return (
<Button
key={device.deviceRef}
type="button"
variant="ghost"
className="device-inventory-row"
role="row"
onClick={() => onDetailChange({
deviceRef: device.deviceRef,
sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? "passport",
editing: false,
})}
>
<span className="device-inventory-row__device" role="cell">
<span className="device-inventory-row__icon"><Icon name="apps" size={17} /></span>
<span><strong>{device.displayName}</strong><small>{device.deviceKey || "ключ не назначен"}</small></span>
</span>
<span role="cell">{profileLabel(workspace, device)}</span>
<span role="cell">{deviceIdentifierDisplayValue(device) || "не назначен"}</span>
<span role="cell">{device.integrationDeviceId || "не назначен"}</span>
<span role="cell"><StatusBadge tone={online ? "success" : "neutral"}>{online ? "Онлайн" : session?.lifecycleState || device.lifecycleState}</StatusBadge></span>
<span role="cell">{formatDate(lastSeenAt)}</span>
<span className="device-inventory-row__open" role="cell" aria-hidden="true"><Icon name="chevron-right" size={16} /></span>
</Button>
);
})}
</GlassSurface>
) : null}
{b2.error ? <p role="alert">{b2.error}</p> : null}
{b2.data?.hosts.filter((host) => !host.reachable).map((host) => <ResourceRow key={host.hostRef} title={host.name} status={<StatusBadge tone="warning">Нет связи с VPS</StatusBadge>} />)}
{statusFilter !== 'pending' ? <ResourceList>
{remoteRows.map((device) => <li key={`${device.hostRef}:${device.id}`}><ResourceRow
icon={<Icon name="apps" />} title={device.name || `ARNavi B2 · ${device.number}`} metadata={`ARNavi B2 · ${device.number} · IMEI ${device.identifier.masked}`} description={device.hostName}
actions={<><IconButton label={`Команды: ${device.name || 'ARNavi B2'}`} onClick={()=>setTracker({device,projectRef:workspace.project.projectRef,section:'commands'})}><Icon name="terminal" /></IconButton><IconButton label={`Настройки: ${device.name || 'ARNavi B2'}`} onClick={()=>setTracker({device,projectRef:workspace.project.projectRef,section:'identity'})}><Icon name="settings" /></IconButton></>} /></li>)}
{deviceRows.map(({ device, online, lastSeenAt }) => <li key={device.deviceRef}><ResourceRow
icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`}
description={lastSeenAt ? formatDate(lastSeenAt) : undefined}
status={<StatusBadge tone={online ? 'success' : 'neutral'}>{device.lifecycleState === 'suspended' ? 'В архиве' : online ? 'Онлайн' : 'Не в сети'}</StatusBadge>}
actions={<><IconButton label={`Настройки ${device.displayName}`} onClick={() => onDetailChange({ deviceRef: device.deviceRef, sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? 'passport', editing: false })}><Icon name="settings" /></IconButton>
{canManageProject && !online ? <Button size="compact" disabled={archiving} onClick={() => setArchiveTarget(device)}>{device.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button> : null}</>} /></li>)}
</ResourceList> : null}
{statusFilter !== 'pending' && !deviceRows.length && !remoteRows.length ? <div className="device-manager-empty device-inventory__empty"><Icon name="inbox" size={24} /><h3>{!b2.data && !b2.error ? 'Загрузка устройств…' : b2.error || b2.data?.hosts.some((host) => !host.reachable) ? 'Реестр VPS недоступен' : statusFilter === 'archived' ? 'Архив пуст' : count ? 'Нет устройств с таким состоянием' : 'В проекте пока нет устройств'}</h3></div> : null}
{(statusFilter === "all" || statusFilter === "pending") ? (
{(statusFilter === "pending" || statusFilter === "all" && pendingEnrollments.length > 0) ? (
<section className="device-inventory__pending" aria-label="Ожидают подключения">
<div className="device-inventory__section-heading">
<div>
@@ -264,9 +199,9 @@ export function DeviceInventoryView({
<p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p>
</SettingsCard>
)) : (
<GlassSurface className="device-manager-panel-empty device-inventory__pending-empty" padding="md" tone="soft">
<div className="device-manager-panel-empty device-inventory__pending-empty">
Нет ожидающих подключений.
</GlassSurface>
</div>
)}
</section>
) : null}
@@ -417,35 +352,21 @@ function DeviceDetailView({
};
return (
<FeatureSettingsWindow open title="Настройки устройства" subtitle={workspace.project.name}
identity={{ title: device.displayName, subtitle: `${catalog.vendor} · ${catalog.model}`, avatarLabel: catalog.vendor.slice(0, 2) }}
sections={catalog.sections.map((section) => ({ id: section.id, label: section.label }))}
activeSection={activeSection.id} onSectionChange={(sectionId) => onDetailChange({ ...detail, sectionId })} onClose={onBack}
headerActions={<><IconButton label="Обновить устройство" disabled={saving} onClick={() => void onSaved().catch(onError)}><Icon name="refresh" /></IconButton>
{(canConfigure || canManageProject) ? <IconButton label={detail.editing ? 'Завершить редактирование' : 'Редактировать устройство'} disabled={saving} onClick={() => onDetailChange({ ...detail, editing: !detail.editing })}><Icon name="edit" /></IconButton> : null}</>}>
<div ref={detailRef} className="device-detail">
<div className="device-detail__header">
<IconButton label="Вернуться к списку устройств" onClick={onBack}>
<Icon name="chevron-left" size={18} />
</IconButton>
<div className="device-detail__identity">
<small>{catalog.vendor} · {catalog.model}</small>
<h2>{device.displayName}</h2>
<p>{identifierDisplayValue || "Идентификатор не назначен"} · {device.modelProfileRef}</p>
</div>
<StatusBadge tone={session?.lifecycleState === "online" ? "success" : "neutral"}>
{session?.lifecycleState === "online" ? "Онлайн" : session?.lifecycleState || device.lifecycleState}
</StatusBadge>
</div>
<div className="device-detail__legend" aria-label="Режимы доступа">
<AccessBadge access="read-only" />
<AccessBadge access="managed" />
<AccessBadge access="protected" />
</div>
<GlassSurface className="device-detail__connection" padding="md" tone="soft">
<div className="device-detail__connection">
<div><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div>
<div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div>
<div><span>Протокол</span><strong>{session?.protocol || profile?.protocol || "Нет данных"}</strong></div>
<div><span>Последняя активность</span><strong>{formatDate(session?.lastSeenAt || device.session?.lastSeenAt)}</strong></div>
<div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div>
<div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div>
</GlassSurface>
</div>
<div className="device-detail__layout">
<section className="device-detail-section">
@@ -475,7 +396,7 @@ function DeviceDetailView({
? draftValues[item.path]
: readPath(context, item.path);
return (
<GlassSurface key={item.key} className="device-detail-field" padding="sm" tone="soft" data-access={access} data-editing={editable || undefined}>
<div key={item.key} className="device-detail-field" data-access={access} data-editing={editable || undefined}>
{editable && item.valueKind === "boolean" ? (
<Switch
checked={Boolean(value)}
@@ -503,7 +424,7 @@ function DeviceDetailView({
{item.description ? <small>{item.description}</small> : null}
</>
)}
</GlassSurface>
</div>
);
})}
</div>
@@ -534,14 +455,15 @@ function DeviceDetailView({
) : null}
<div className="device-detail-section__state">
<span>Desired</span>
<span>Запрошенная конфигурация</span>
<strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong>
<span>Applied</span>
<span>Подтверждена устройством</span>
<strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong>
</div>
</section>
</div>
</div>
</FeatureSettingsWindow>
);
}
@@ -614,12 +536,12 @@ function AccessNotice({
commandTransport: ProjectWorkspace["policies"]["commandTransport"];
}) {
if (access === "read-only") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></div>;
}
if (access === "protected") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></div>;
}
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></div>;
}
function latestSession(workspace: ProjectWorkspace, device: DeviceView): SessionView | null {
+64 -66
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import {
AdminNavigationPanel,
AppHeader,
@@ -9,8 +9,9 @@ import {
Dropdown,
FeatureSettingsWindow,
GlassSurface,
ResourceList,
ResourceRow,
HeaderNavigation,
HeaderProfile,
HeaderWorkspace,
Icon,
type IconName,
@@ -56,12 +57,14 @@ import type {
ProjectWorkspace,
} from "./types";
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
import { B2AddDevice } from "./b2/B2AddDevice";
import { B2AddHost } from "./b2/B2AddHost";
import { useB2Inventory } from "./b2/useB2Inventory";
import {
DeviceControlView,
type ControlViewId,
} from "./DeviceControlViews";
import {
DeviceDetailHeaderTools,
DeviceInventoryView,
type DeviceInventoryDetailState,
} from "./DeviceInventoryView";
@@ -99,13 +102,9 @@ const sectionNavigation: Record<PrimarySection, NavigationItem[]> = {
],
infrastructure: [
{ id: "hosts", label: "VPS и хосты", icon: "building", capability: "telemetry.observe" },
{ id: "infrastructure", label: "Edges и маршруты", icon: "globe", capability: "telemetry.observe" },
{ id: "catalog", label: "Модели и адаптеры", icon: "database", capability: "project.read" },
],
management: [
{ 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: [
{ id: "audit", label: "Аудит", icon: "clipboard", capability: "audit.read" },
@@ -188,10 +187,14 @@ export function DeviceManagerApp() {
const [workspace, setWorkspace] = useState<ProjectWorkspace | null>(null);
const [activeOwnerRef, setActiveOwnerRef] = useState("");
const [activeProjectRef, setActiveProjectRef] = useState("");
const projectRefCurrent = useRef(activeProjectRef);
projectRefCurrent.current = activeProjectRef;
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [projectDialogOpen, setProjectDialogOpen] = useState(false);
const [collectionDialogOpen, setCollectionDialogOpen] = useState(false);
const [addHostOpen, setAddHostOpen] = useState(false);
const [addDeviceOpen, setAddDeviceOpen] = useState(false);
const [enrollmentDialogOpen, setEnrollmentDialogOpen] = useState(false);
const [claimEnrollment, setClaimEnrollment] = useState<EnrollmentView | null>(null);
const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);
@@ -231,6 +234,7 @@ export function DeviceManagerApp() {
useEffect(() => {
applyNodedcTheme(document.documentElement, {
theme: presentation.environment.theme,
appearance: "mission",
accent: hexToRgb(presentation.environment.accentHex),
});
}, [presentation.environment.accentHex, presentation.environment.theme]);
@@ -286,9 +290,11 @@ export function DeviceManagerApp() {
}, [activeOwnerRef, activeProjectRef, visibleProjects]);
const selectProject = (projectRef: string) => {
if (projectRef === activeProjectRef) return;
setInventoryDetail(null);
projectRefCurrent.current = projectRef;
setWorkspace(null);
setActiveProjectRef(projectRef);
shell.closeView();
};
const openSection = (section: PrimarySection) => {
@@ -305,14 +311,17 @@ export function DeviceManagerApp() {
};
const selectOwner = (ownerRef: string) => {
if (ownerRef === activeOwnerRef) return;
setActiveOwnerRef(ownerRef);
setInventoryDetail(null);
setWorkspace(null);
const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef);
if (nextProject) {
projectRefCurrent.current = nextProject.projectRef;
setActiveProjectRef(nextProject.projectRef);
shell.closeView();
}
else {
projectRefCurrent.current = "";
setActiveProjectRef("");
setWorkspace(null);
shell.closeView();
@@ -322,6 +331,7 @@ export function DeviceManagerApp() {
const refreshWorkspace = async () => {
if (!activeProjectRef) return;
const next = await loadWorkspace(activeProjectRef);
if (projectRefCurrent.current !== activeProjectRef) return;
setWorkspace(next);
await refreshProjects();
};
@@ -329,17 +339,14 @@ export function DeviceManagerApp() {
const pollWorkspace = async () => {
if (!activeProjectRef) return;
const next = await loadWorkspace(activeProjectRef);
setWorkspace(next);
if (projectRefCurrent.current === activeProjectRef) setWorkspace(next);
};
if (loading || !session) {
return <div className="device-manager-boot">Подключаем Device Core…</div>;
}
const activeView = shell.activeView;
const selectedInventoryDevice = inventoryDetail
? workspace?.devices.find((device) => device.deviceRef === inventoryDetail.deviceRef) ?? null
: null;
const activeView = visibleNavigationItems.some((item) => item.id === shell.activeView) ? shell.activeView : null;
return (
<>
<ApplicationShell
@@ -367,7 +374,6 @@ export function DeviceManagerApp() {
</>
}
right={
<HeaderProfile>
<UserProfileMenu
displayName={session.user.displayName}
subtitle={session.user.email}
@@ -383,7 +389,6 @@ export function DeviceManagerApp() {
{ id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" },
]}
/>
</HeaderProfile>
}
/>
}
@@ -405,8 +410,8 @@ export function DeviceManagerApp() {
{activeSection === "devices" && activeProject ? (
<IconButton
label="Подключить устройство"
disabled={!canEnroll || !workspace?.routes.some((route) => route.lifecycleState === "active")}
onClick={() => setEnrollmentDialogOpen(true)}
disabled={!canEnroll}
onClick={() => setAddDeviceOpen(true)}
>
<Icon name="plus" size={16} />
</IconButton>
@@ -482,21 +487,18 @@ export function DeviceManagerApp() {
expanded={shell.contentExpanded}
onExpandedChange={shell.setContentExpanded}
onClose={shell.closeView}
headerTools={activeView === "inventory" && selectedInventoryDevice && inventoryDetail ? (
<DeviceDetailHeaderTools
device={selectedInventoryDevice}
detail={inventoryDetail}
canEdit={canConfigure || canManageProject}
onDetailChange={setInventoryDetail}
/>
) : undefined}
utilityActions={[{
utilityActions={[...(activeView === 'inventory' && canEnroll ? [{
label: 'Добавить устройство', icon: 'plus' as const, onClick: () => setAddDeviceOpen(true),
}] : []), ...(activeView === 'hosts' && capabilities.has('infrastructure.manage') ? [{
label: 'Добавить VPS', icon: 'plus' as const, onClick: () => setAddHostOpen(true),
}] : []), {
label: "Обновить данные",
icon: "refresh",
onClick: () => refreshWorkspace().catch((reason) => setError(errorText(reason))),
}]}
>
<ProjectView
key={activeProjectRef}
view={activeView}
workspace={workspace}
canManageCollections={canManageCollections}
@@ -548,6 +550,8 @@ export function DeviceManagerApp() {
}}
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
open={enrollmentDialogOpen}
workspace={workspace}
@@ -773,16 +777,6 @@ function EnvironmentBackdrop({
);
}
function Metric({ label, value, detail, tone = "neutral" }: { label: string; value: number; detail: string; tone?: "neutral" | "success" | "warning" }) {
return (
<GlassSurface className="device-manager-metric" padding="md" tone="soft">
<span>{label}</span>
<strong>{value}</strong>
<StatusBadge tone={tone}>{detail}</StatusBadge>
</GlassSurface>
);
}
function ProjectView({ view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: {
view: ViewId;
workspace: ProjectWorkspace | null;
@@ -826,7 +820,7 @@ function ProjectView({ view, workspace, canManageCollections, canClaim, canConfi
if (view === "collections") return (
<div className="device-manager-stack">
<div className="device-manager-panel-toolbar">
<p>Коллекции группируют устройства для последующих bindings и задач.</p>
<p>Группы устройств проекта.</p>
<Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button>
</div>
<EntityList
@@ -841,17 +835,27 @@ function ProjectView({ view, workspace, canManageCollections, canClaim, canConfi
/>
</div>
);
return <ProjectOverview key={workspace.project.projectRef} workspace={workspace} />;
}
function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) {
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const incomplete = !b2.data || b2.data.hosts.some((host) => !host.reachable);
const deviceCount = incomplete ? null : workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + b2.data!.items.length;
const deviceDetail = !incomplete ? 'В реестре' : (b2.error || b2.data) ? 'Данные VPS недоступны' : 'Загрузка…';
const metrics = [
{ label: 'Устройства', value: deviceCount, detail: deviceDetail },
{ label: 'Ожидают проверки', value: workspace.discoveries.filter((item) => item.lifecycleState === 'quarantine').length, detail: 'Обнаружены' },
{ label: 'Коллекции', value: workspace.collections.length, detail: 'Группы устройств' },
];
return (
<div className="device-manager-overview-grid">
<Metric label="Устройства" value={workspace.devices.length} detail="inventory" />
<Metric label="Quarantine" value={workspace.discoveries.filter((item) => item.lifecycleState === "quarantine").length} detail="safe projection" />
<Metric label="Коллекции" value={workspace.collections.length} detail="bindings ready" />
<SettingsCard title="Права проекта" description={workspace.project.access.projectRole || "read"}>
<div className="device-manager-capabilities">
{workspace.project.access.capabilities.map((capability) => <StatusBadge key={capability}>{capability}</StatusBadge>)}
</div>
</SettingsCard>
</div>
<ResourceList>
{metrics.map((metric) => (
<li key={metric.label}>
<ResourceRow title={metric.label} metadata={metric.detail} status={<StatusBadge>{metric.value ?? '—'}</StatusBadge>} />
</li>
))}
</ResourceList>
);
}
@@ -934,7 +938,7 @@ function ProjectSettingsDialog({ open, workspace, presentation, onClose, onSaved
avatarUrl: iconPreview ?? undefined,
}}
sections={[
{ id: "identity", label: "Идентичность", icon: "profile", group: "Проект" },
{ id: "identity", label: "Основное", icon: "profile", group: "Проект" },
{ id: "media", label: "Медиа", icon: "image", group: "Оформление" },
]}
activeSection={section}
@@ -1233,13 +1237,9 @@ function EnvironmentSettingsDialog({ open, presentation, onClose, onSaved, onErr
function EntityList({ items, empty }: { items: Array<{ id: string; title: string; subtitle: string; status: string; tone: "neutral" | "success" | "warning" }>; empty: string }) {
if (!items.length) return <div className="device-manager-panel-empty">{empty}</div>;
return <div className="device-manager-entity-list">{items.map((item) => (
<GlassSurface key={item.id} className="device-manager-entity" padding="md" tone="soft">
<span className="device-manager-entity__icon"><Icon name="circle" /></span>
<span className="device-manager-entity__body"><strong>{item.title}</strong><small>{item.subtitle}</small></span>
<StatusBadge tone={item.tone}>{item.status}</StatusBadge>
</GlassSurface>
))}</div>;
return <ResourceList>{items.map((item) => <li key={item.id}><ResourceRow
icon={<Icon name="folder" />} title={item.title} description={item.subtitle}
status={<StatusBadge tone={item.tone}>{item.status}</StatusBadge>} /></li>)}</ResourceList>;
}
function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: {
@@ -1279,17 +1279,17 @@ function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated,
await onCreated();
} catch (reason) { onError(reason); } finally { setPending(false); }
};
return <Window open={open} title="Новый Device Project" subtitle={ownerScope?.displayName || "Owner scope недоступен"} onClose={onClose} footer={
return <Window open={open} title="Новый проект" subtitle={ownerScope?.displayName || "Компания недоступна"} onClose={onClose} footer={
<WindowFooterActions><Button variant="ghost" onClick={onClose}>Отмена</Button><Button type="submit" form="device-project-form" variant="primary" disabled={pending || !ownerScope}>{pending ? "Создаём…" : "Создать"}</Button></WindowFooterActions>
}>
<form id="device-project-form" className="device-manager-form" onSubmit={submit}>
<Select
label="Контур проекта"
label="Владелец проекта"
value={ownerRef}
options={ownerScopes.map((scope) => ({
value: scope.ownerRef,
label: scope.displayName,
description: scope.scopeKind === "company" ? "Коммерческий контур" : "Личный контур",
description: scope.scopeKind === "company" ? "Компания" : "Личное пространство",
}))}
onChange={setOwnerRef}
/>
@@ -1353,7 +1353,6 @@ function ClaimDialog({ enrollment, project, onClose, onClaimed, onError }: {
<form id="device-claim-form" className="device-manager-form" onSubmit={submit}>
<TextField label="Название устройства" value={name} onChange={(event) => setName(event.target.value)} required maxLength={160} />
<TextField label="Ключ устройства" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<p className="device-manager-card-copy">Claim использует только ссылки на enrollment и discovery. Исходный идентификатор не запрашивается повторно.</p>
</form>
</Window>;
}
@@ -1432,7 +1431,6 @@ function EnrollmentDialog({ open, workspace, onClose, onCreated, onError }: {
<TextField label="Ключ enrollment" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<TextField label="IMEI" value={imei} onChange={(event) => setImei(event.target.value.replace(/\D/g, "").slice(0, 15))} required pattern="[0-9]{15}" inputMode="numeric" autoComplete="off" />
<TextField label="Истекает" type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} description="Опционально. Время будет сохранено в UTC." />
<p className="device-manager-card-copy">IMEI передаётся один раз по HTTPS в Device Control Core. В базе, audit и ответе останутся только HMAC и маска.</p>
</form>
</Window>;
}
@@ -1458,11 +1456,11 @@ function viewTitle(view: ViewId) {
collections: "Коллекции",
catalog: "Модели и адаптеры",
hosts: "VPS и хосты",
infrastructure: "Edges и маршруты",
sessions: "Gateway sessions",
bindings: "Data bindings",
commands: "Command ledger",
audit: "Immutable audit",
infrastructure: "Узлы и маршруты",
sessions: "Подключения устройств",
bindings: "Связи с Foundry",
commands: "Команды",
audit: "Аудит",
access: "Доступ к проекту",
settings: "Настройки и конфигурации",
})[view];
+7
View File
@@ -442,3 +442,10 @@ async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
}
return body as T;
}
export function archiveDevice(projectRef: string, deviceRef: string, archived: boolean) {
return mutate("/api/device-manager/devices:update", { projectRef, deviceRef, archived });
}
export function archiveHost(projectRef: string, hostRef: string, archived: boolean) {
return mutate("/api/device-manager/infrastructure-hosts:ensure", { projectRef, hostRef, archived });
}
@@ -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>;
}
+72
View File
@@ -0,0 +1,72 @@
import { useRef, useState } from 'react';
import { Button, Icon, Select, SettingsCard, TextAreaField, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
import { b2Request } from './api';
import release from './installer-release.json';
import './b2.css';
const installCommand = `sudo python3 ${release.filename} --device-core`;
const keyCommand = 'sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection';
export function B2AddHost({ open, projectRef, onClose, onCreated, onError }: {
open: boolean; projectRef: string; onClose: () => void; onCreated: () => Promise<void>; onError: (error: unknown) => void;
}) {
const [name, setName] = useState('ARNavi VPS'), [connection, setConnection] = useState('');
const [pending, setPending] = useState(false);
const [downloading, setDownloading] = useState(false);
const fileInput = useRef<HTMLInputElement>(null);
async function downloadInstaller() {
setDownloading(true);
try {
const response = await fetch(`/installers/${release.filename}`, { credentials: 'same-origin', signal: AbortSignal.timeout(45000) });
if (!response.ok) throw new Error('Не удалось скачать установщик. Проверьте вход в Device Core и повторите.');
const bytes = await response.arrayBuffer();
const digest = await crypto.subtle.digest('SHA-256', bytes);
const sha256 = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
if (bytes.byteLength !== release.bytes || sha256 !== release.sha256) throw new Error('Загруженный файл не прошёл проверку. Повторите скачивание.');
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
const link = document.createElement('a'); link.href = url; link.download = release.filename;
document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (error) {
onError(error instanceof Error && ['TimeoutError', 'AbortError'].includes(error.name)
? new Error('Сервер не успел передать установщик. Повторите скачивание.') : error);
} finally { setDownloading(false); }
}
return <Window open={open} title="Добавить VPS" size="lg" onClose={onClose} footer={
<WindowFooterActions><Button onClick={onClose}>Отмена</Button><Button type="submit" form="b2-add-vps" loading={pending} disabled={pending || !name.trim() || !connection.trim()}>Подключить VPS</Button></WindowFooterActions>
}>
<form id="b2-add-vps" className="b2-settings" onSubmit={async (event) => {
event.preventDefault(); if (pending) return;
setPending(true);
try {
await b2Request(projectRef, '', 'register-host', { name: name.trim(), connection });
setConnection(''); await onCreated();
} catch (error) { onError(error); } finally { setPending(false); }
}}>
<Select label="Поддерживаемый VPS" value="arnavi" onChange={() => undefined} options={[{ value: 'arnavi', label: 'ARNavi VPS' }]} />
<div className="b2-onboarding-grid">
<SettingsCard title="1. Установить сервер" description={`ARNavi VPS ${release.version} · Ubuntu Server 24.04 LTS · x86-64`}>
<div className="b2-settings">
<div className="b2-actions"><Button disabled={downloading} loading={downloading} onClick={downloadInstaller}><Icon name="download" />Скачать установщик</Button></div>
<p>Перенесите файл на новый VPS. В его терминале выполните команду и укажите публичный IP или домен.</p>
<TextAreaField label="Установка на VPS" rows={2} readOnly value={installCommand} />
<p>Порты сервера: 19443/TCP для API и 9922/TCP для трекеров. Ключ администратора Device Core создаётся при первой установке.</p>
<TextAreaField label="Получить ключ подключения на VPS" rows={2} readOnly value={keyCommand} />
<p>Скопируйте полученный JSON в блок подключения или загрузите сохранённый файл.</p>
<p className="b2-key-id">SHA-256 установщика: {release.sha256}</p>
</div>
</SettingsCard>
<SettingsCard title="2. Подключить сервер">
<div className="b2-settings">
<TextField label="Название VPS" value={name} maxLength={160} disabled={pending} required onChange={(event) => setName(event.target.value)} />
<Button disabled={pending} onClick={() => fileInput.current?.click()}><Icon name="upload" />Загрузить ключ сервера</Button>
<input ref={fileInput} type="file" hidden accept=".json,application/json" aria-label="Файл ключа сервера" onChange={async (event) => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return;
try { if (file.size > 16384) throw new Error('Файл ключа слишком большой.'); const text = await file.text(); JSON.parse(text); setConnection(text); }
catch { onError(new Error('Не удалось прочитать JSON ключа сервера.')); }
}} />
<TextAreaField label="Ключ администратора VPS · JSON" value={connection} disabled={pending} rows={4} autoComplete="off" spellCheck={false} maxLength={16384} required onChange={(event) => setConnection(event.target.value)} />
</div>
</SettingsCard>
</div>
</form>
</Window>;
}
+191 -90
View File
@@ -1,125 +1,226 @@
import { useEffect, useState } from 'react';
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge,
TextField, TextAreaField, WindowFooterActions, ConfirmationModal } from '@nodedc/ui-react';
import { loadProjects } from '../api';
import { useEffect, useRef, useState } from 'react';
import { Button, FeatureSettingsWindow, GlassSurface, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
import { archiveHost, loadProjects } from '../api';
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
import { b2Request, type B2Status } from './api';
import { b2Request, type B2Status, type B2Application } from './api';
import './b2.css';
type Section = 'connection' | 'contours' | 'applications';
type Section = 'connection' | 'contours';
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
onChanged: () => Promise<void>; onError: (error: unknown) => void;
}) {
const project = workspace.project;
const [section, setSection] = useState<Section>('connection');
const [section, setSection] = useState<Section>('contours');
const [status, setStatus] = useState<B2Status | null>(null);
const [pending, setPending] = useState('');
const [connection, setConnection] = useState('');
const [key, setKey] = useState(''); const [name, setName] = useState('');
const [contour, setContour] = useState('');
const [targetProject, setTargetProject] = useState(project.projectRef);
const [pending, setPending] = useState('load');
const [connection, setConnection] = useState(''), [importOpen, setImportOpen] = useState(false);
const connectionFile = useRef<HTMLInputElement>(null);
const [projects, setProjects] = useState<ProjectSummary[]>([]);
const [issued, setIssued] = useState('');
const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
const [creating, setCreating] = useState(''), [name, setName] = useState('');
const [access, setAccess] = useState('read');
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string; access: string } | null>(null);
const [newContour, setNewContour] = useState(false), [contourName, setContourName] = useState('');
const [targetProject, setTargetProject] = useState(project.projectRef);
const [contourIntent, setContourIntent] = useState<{ id: string; name: string; projectRef: string } | null>(null);
const [syncError, setSyncError] = useState('');
const [archiveConfirm, setArchiveConfirm] = useState(false);
const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null);
const [credentialRows, setCredentialRows] = useState<string[]>([]);
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
const request = <T,>(action: string, data: Record<string, unknown> = {}) => b2Request<T>(project.projectRef, host.hostRef, action, data);
const refresh = () => request<B2Status>('status').then(setStatus);
const request = <T,>(action: string, data: Record<string, unknown> = {}, requestId?: string) => b2Request<T>(project.projectRef, host.hostRef, action, data, requestId);
const refresh = async () => { const value = await request<B2Status>('status'); setStatus(value); setSyncError(''); return value; };
useEffect(() => {
let active = true;
setPending('load');
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
if (!active) return;
setStatus(value);
setStatus(value); if (!value.connected) { setSection('connection'); setImportOpen(true); }
setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef));
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
return () => { active = false; };
}, [host.hostRef, project.projectRef]);
async function run(action: string, data: Record<string, unknown> = {}) {
useEffect(() => {
if (pending) return;
let active = true, timer: number;
async function sync() {
try {
if (document.visibilityState === 'visible') {
const value = await request<B2Status>('status');
if (active) { setStatus(value); setSyncError(''); }
}
} catch { if (active) setSyncError('Не удалось обновить список VPS. Показаны последние полученные сведения.'); }
finally { if (active) timer = window.setTimeout(sync, 30000); }
}
timer = window.setTimeout(sync, 30000);
return () => { active = false; window.clearTimeout(timer); };
}, [host.hostRef, project.projectRef, pending]);
async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) {
setPending(action);
try {
const result = await request<{ connection?: unknown }>(action, data);
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2));
if (action === 'connect') setConnection('');
await refresh(); await onChanged();
} catch (error) { onError(error); } finally { setPending(''); }
const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string; contourId?: string }>(action, data, requestId);
if (result.connection) {
const { integration_id: applicationId, client_id: clientId } = result.connection;
setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) });
setKeyRows((rows) => [...new Set([...rows, applicationId])]);
setCredentialRows((rows) => [...new Set([...rows, clientId])]);
}
if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null);
if (action === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null);
if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); }
if (action === 'contour-connect') {
setNewContour(false); setContourName(''); setContourIntent(null);
if (result.contourId) setExpanded(rows => [...new Set([...rows, result.contourId!])]);
}
setCreating(''); setName(''); setCreationIntent(null);
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
return true;
} 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 toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id];
function downloadIssuedKey() {
if (!issued) return;
const url = URL.createObjectURL(new Blob([issued.value + '\n'], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = 'arnavi-application-key.json';
document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function applicationRow(app: B2Application) {
const legacy = app.key === 'legacy-mission-core';
const open = keyRows.includes(app.id), active = app.credentials.some((item) => item.enabled);
return <li key={app.id} className="b2-disclosure">
<ResourceRow title={app.name} metadata={legacy ? 'Подключение Mission Core · v1' : active ? 'Ключ выдан' : 'Нет действующего ключа'}
actions={<>
{open && !legacy ? <>
{canManage ? <>
<IconButton label={`${active ? 'Перевыпустить' : 'Выдать'} ключ ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: active }, text: active ? `Перевыпустить ключ «${app.name}»? Прежний ключ перестанет работать.` : `Выдать ключ «${app.name}»?` })}><Icon name="plus" /></IconButton>
<IconButton label={`Удалить приложение ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'application-delete', fields: { integrationId: app.id }, text: `Удалить «${app.name}» со всеми ключами и связями с контурами на этом VPS? Доступ приложения прекратится. Устройства, данные контуров и другие приложения сохранятся.` })}><Icon name="trash" /></IconButton>
</> : null}
</> : null}
<IconButton label={`Ключи ${app.name}`} aria-expanded={open} aria-controls={`keys-${app.id}`} onClick={() => setKeyRows(toggle(keyRows, app.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>
</>} />
{open ? <div id={`keys-${app.id}`} className="b2-disclosure__body">
{legacy ? <>
<dl className="b2-tracker-facts"><dt>Тип подключения</dt><dd>Прямая привязка Mission Core</dd><dt>ID приложения</dt><dd>{app.id}</dd></dl>
<p>Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.</p>
</> : <>
<dl className="b2-tracker-facts"><dt>Доступ приложения</dt><dd>{Object.entries(app.grants).map(([contourId, grant]) => `${status?.contours?.find(contour => contour.id === contourId)?.name || contourId}: ${{ read: 'чтение', control: 'чтение и команды', manage: 'управление устройствами' }[grant] || grant}`).join('; ')}</dd></dl>
<ResourceList>{app.credentials.map((item) => {
const keyOpen = credentialRows.includes(item.client_id);
const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null;
return <li key={item.client_id} className="b2-disclosure">
<ResourceRow title={`Ключ · …${item.client_id.slice(-8)}`} status={<StatusBadge tone={item.enabled ? 'success' : 'neutral'}>{item.enabled ? 'Действует' : 'Отозван'}</StatusBadge>}
actions={<IconButton label={`Сведения ключа ${item.client_id}`} aria-expanded={keyOpen} aria-controls={`credential-${item.client_id}`} onClick={() => setCredentialRows(toggle(credentialRows, item.client_id))}><Icon name={keyOpen ? 'chevron-up' : 'chevron-down'} /></IconButton>} />
{keyOpen ? <div id={`credential-${item.client_id}`} className="b2-disclosure__body">
<dl className="b2-tracker-facts"><dt>ID для сверки</dt><dd><code className="b2-key-id">{item.client_id}</code></dd><dt>VPS</dt><dd>{status?.endpoint}</dd></dl>
{secret ? <SettingsCard title="Ключ подключения приложения" description="Импортируйте файл в приложение с поддержкой ARNavi API v2. Секрет показывается один раз."><div className="b2-settings">
<TextAreaField label="Файл подключения" value={secret.value} readOnly rows={4} />
<div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(secret.value).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued(null)}>Скрыть секрет</Button></div>
</div></SettingsCard> : <p>Секрет скрыт. ID ключа можно сверить с полем client_id в сохранённом файле подключения.</p>}
{item.enabled && canManage ? <div className="b2-actions"><Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: item.client_id }, text: `Отозвать ключ «${app.name}»?` })}>Отозвать ключ</Button></div> : null}
</div> : null}
</li>;
})}</ResourceList>
{!app.credentials.length ? <p>Ключи ещё не выданы</p> : null}
</>}
</div> : null}
</li>;
}
const contours = status?.contours || [];
const canManage = status?.authority === 'host';
const busy = Boolean(pending);
return <>
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' },
{ id: 'contours', label: 'Контуры и проекты', icon: 'layers', disabled: !status?.connected },
{ id: 'applications', label: 'Приложения и ключи', icon: 'key', disabled: !status?.connected }]}
activeSection={section} onSectionChange={(value) => { setSection(value); setKey(''); setName(''); }} onClose={onClose}
footer={<WindowFooterActions><Button onClick={onClose}>Закрыть</Button>
sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]}
activeSection={section} onSectionChange={setSection} onClose={onClose}
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(''); }
}}><Icon name="refresh" /></IconButton></WindowFooterActions>}>
<div className="b2-settings">
}}><Icon name="refresh" /></IconButton></>}>
<div className="b2-settings" aria-busy={busy}>
{syncError ? <p role="status">{syncError}</p> : null}
{section === 'connection' ? <>
<SettingsCard title="ARNavi VPS" description="Одно подключение сервера для проектов компании. Устройства разделяются контурами.">
<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Проверяем подключение' : status ? 'Не подключён' : 'Состояние не получено'}</StatusBadge>
{status?.endpoint ? <p>{status.endpoint}</p> : null}
</SettingsCard>
<SettingsCard title={status?.connected ? 'Заменить ключ подключения' : 'Подключить сервер'} description="Вставьте ключ, выданный на VPS. После подключения он хранится только на сервере Device Core.">
<div className="b2-settings">
<TextAreaField label="Ключ подключения" value={connection} autoComplete="off" spellCheck={false}
onChange={(event) => setConnection(event.target.value)} rows={5} />
<Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>Подключить</Button>
</div>
</SettingsCard>
<ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>}
actions={<IconButton label="Импортировать ключ доступа Device Core" aria-expanded={importOpen} onClick={() => setImportOpen(!importOpen)}><Icon name="key" /></IconButton>} />
{importOpen ? <SettingsCard title="Доступ Device Core к VPS" description="Файл доступа выдаёт администратор этого VPS."><div className="b2-settings">
<Button disabled={busy} onClick={() => connectionFile.current?.click()}><Icon name="upload" />Загрузить файл доступа</Button>
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл доступа к VPS" disabled={busy} onChange={async (event) => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return; setPending('file');
try { if (file.size > 16384) throw new Error(); const text = await file.text(); JSON.parse(text); setConnection(text); }
catch { onError(new Error('Не удалось прочитать файл доступа.')); } finally { setPending(''); }
}} />
<TextAreaField label="Содержимое файла доступа" value={connection} autoComplete="off" spellCheck={false} onChange={(event) => setConnection(event.target.value)} rows={4} />
<div className="b2-actions"><Button disabled={busy} onClick={() => { setImportOpen(false); setConnection(''); }}>Отмена</Button><Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>{status?.connected ? 'Обновить доступ Device Core' : 'Подключить Device Core'}</Button></div>
</div></SettingsCard> : null}
</> : null}
{section === 'contours' ? <>
<SettingsCard title="Контуры на VPS" description="Связь с проектом определяет, где появятся устройства. Один контур можно подключить к нескольким приложениям.">
<div className="b2-settings">
{contours.map((item) => {
const link = status?.links?.find((value) => value.contourId === item.id);
return <div className="b2-resource" key={item.id}><div><strong>{item.name}</strong><small>{item.key}</small></div>
<StatusBadge tone={link ? 'success' : 'neutral'}>{link ? projects.find((p) => p.projectRef === link.projectRef)?.name || 'Связан с проектом' : 'Не связан'}</StatusBadge></div>;
})}
{!contours.length ? <p>На VPS пока нет контуров.</p> : null}
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
<Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((item) => ({ value: item.projectRef, label: item.name }))} />
<Button loading={pending === 'link'} disabled={busy || !contour || !targetProject} onClick={() => void run('link', { contourId: contour, targetProjectRef: targetProject })}>Связать с проектом</Button>
</div>
</SettingsCard>
{canManage ? <SettingsCard title="Новый контур" description="Контур создаётся на VPS и получает собственный реестр устройств.">
<div className="b2-settings"><TextField label="Название" value={name} onChange={(e) => setName(e.target.value)} />
<TextField label="Код контура" value={key} placeholder="robot2b" onChange={(e) => setKey(e.target.value)} />
<Button loading={pending === 'contour-create'} disabled={busy || !/^[a-z][a-z0-9-]{0,63}$/.test(key) || !name.trim()}
onClick={() => void run('contour-create', { key, name })}>Создать контур</Button></div>
</SettingsCard> : null}
</> : null}
{section === 'applications' ? <>
{issued ? <SettingsCard title="Новый ключ приложения" description="Скопируйте ключ и передайте в подключаемое приложение. Позже его можно перевыпустить без потери устройств.">
<div className="b2-settings"><TextAreaField label="Ключ" value={issued} readOnly rows={6} />
<Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать ключ</Button>
<Button onClick={() => setIssued('')}>Скрыть</Button></div>
</SettingsCard> : null}
{(status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core').map((app) => <SettingsCard key={app.id} title={app.name}
description={Object.keys(app.grants).map((id) => contours.find((item) => item.id === id)?.name || id).join(', ')}>
<div className="b2-settings">
{app.credentials.map((credential) => <div className="b2-resource" key={credential.client_id}>
<div><small>{credential.client_id}</small><StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge></div>
{credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${app.name}»? Подключённый клиент потеряет доступ.` })}>Отозвать</Button> : null}
</div>)}
<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: true }, text: `Выдать новый ключ для «${app.name}»? Предыдущие ключи этого приложения перестанут работать. Устройства и история сохранятся.` })}>{app.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>
</div>
</SettingsCard>)}
{canManage ? <SettingsCard title="Подключить новое приложение" description="Для каждого приложения создайте отдельный ключ. Несколько приложений могут работать с одним контуром независимо.">
<div className="b2-settings"><TextField label="Название приложения" value={name} onChange={(e) => setName(e.target.value)} />
<TextField label="Код приложения" value={key} placeholder="robot2b-client" onChange={(e) => setKey(e.target.value)} />
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
<Button loading={pending === 'application-create'} disabled={busy || !contour || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)}
onClick={() => void run('application-create', { key, name, contourId: contour })}>Создать приложение</Button></div>
</SettingsCard> : <SettingsCard title="Доступ к контуру" description="Управление ключами доступно через управляющее подключение VPS." />}
<h3 id="b2-contours-heading" className="b2-section-heading b2-contours-heading">Контуры</h3>
{newContour ? <SettingsCard title="Новый контур VPS" description="Создаётся на этом VPS и связывается с выбранным проектом Device Core."><div className="b2-settings">
<TextField label="Название контура" value={contourName} disabled={busy || Boolean(contourIntent)} maxLength={160} autoFocus onChange={event => setContourName(event.target.value)} />
<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} />
<div className="b2-actions"><Button disabled={busy} onClick={() => { setNewContour(false); setContourIntent(null); }}>Отмена</Button><Button disabled={busy || !contourName.trim() || !targetProject} loading={pending === 'contour-connect'} onClick={() => {
const intent = contourIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: contourName.trim(), projectRef: targetProject };
setContourIntent(intent); void run('contour-connect', { name: intent.name, targetProjectRef: intent.projectRef }, intent.id);
}}>{contourIntent ? 'Уточнить создание' : 'Создать контур'}</Button></div>
</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-${contour.id}`} className="b2-disclosure__body">
<div className="b2-section-heading"><strong>Проекты Device Core</strong></div>
<p>Связанные проекты видят один реестр устройств этого контура. Ключи внешних приложений управляются отдельно.</p>
{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>
<ResourceList>{apps.map(applicationRow)}</ResourceList>
{!apps.length && creating !== contour.id ? <p>Ключи приложений ещё не выданы</p> : null}
{creating === contour.id ? <div className="b2-settings">
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={event => setName(event.target.value)} />
<Select label="Доступ приложения" value={access} disabled={busy || Boolean(creationIntent)} options={[{ value: 'read', label: 'Чтение устройств и данных' }, { value: 'control', label: 'Чтение и команды' }, { value: 'manage', label: 'Управление устройствами контура' }]} onChange={setAccess} />
<div className="b2-actions"><Button disabled={busy} onClick={() => { setCreating(''); setCreationIntent(null); }}>Отмена</Button><Button loading={pending === 'application-connect'} disabled={busy || !name.trim()} onClick={() => {
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim(), access };
setCreationIntent(intent);
void run('application-connect', { name: intent.name, contourId: contour.id, access: intent.access }, intent.id);
}}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div>
</div> : null}
</div> : null}
</GlassSurface>
</li>;
})}</ResourceList>
</> : null}
</div>
</FeatureSettingsWindow>
<ConfirmationModal open={Boolean(confirm)} title="Изменить доступ приложения" description={confirm?.text}
confirmLabel="Продолжить" cancelLabel="Отмена" onClose={() => setConfirm(null)}
onConfirm={async () => { if (confirm) await run(confirm.action, confirm.fields); setConfirm(null); }} />
<ConfirmationModal open={archiveConfirm} title={host.lifecycleState === 'suspended' ? 'Восстановить VPS?' : 'Перенести VPS в архив?'} description={`${host.displayName}. Изменится только запись в этом проекте. Сервер, устройства и подключения других проектов сохранятся.`} confirmLabel={host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => setArchiveConfirm(false)} onConfirm={async () => {
if (busy) return; setPending('archive');
try { await archiveHost(project.projectRef, host.hostRef, host.lifecycleState !== 'suspended'); setArchiveConfirm(false); await onChanged(); onClose(); } catch (error) { onError(error); } finally { setPending(''); }
}} />
<ConfirmationModal open={Boolean(confirm)} title={confirm?.action === 'application-delete' ? 'Удалить приложение' : ['link', 'unlink'].includes(confirm?.action || '') ? 'Связь проекта и контура' : 'Ключ приложения'} description={confirm?.text} confirmLabel={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Подтвердить'} cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && !busy && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
</>;
}
@@ -0,0 +1,145 @@
import { useEffect, useRef, useState } from 'react';
import { Button, FeatureSettingsWindow, Icon, IconButton, ResourceList, ResourceRow, Select, SettingsCard, StatusBadge, Switch, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
import { trackerRequest, newIntent, operationName, stateName, operationTone, formatTime, type TrackerRef, type TrackerState, type Policy, type Operation } from './tracker';
import { B2RequestError } from './api';
import './b2.css';
type Props = { projectRef:string;device:TrackerRef;initialSection?:string;onClose:()=>void;onError:(error:unknown)=>void;onChanged:()=>Promise<void>;canConfigure:boolean;canCommand:boolean };
export function B2TrackerSettings({projectRef,device,initialSection='identity',onClose,onError,onChanged,canConfigure,canCommand}:Props) {
const [section,setSection]=useState(initialSection==='commands'?'commands':'identity');
const [data,setData]=useState<TrackerState|null>(null), [name,setName]=useState(device.name);
const [policy,setPolicy]=useState<Policy>({parameters:{},connectivity:{mode:'preserve'}});
const [profile,setProfile]=useState(''),[profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false);
const [busy,setBusy]=useState('load'),[dirty,setDirty]=useState(false),[commandRefresh,setCommandRefresh]=useState(0);
const [bootstrapFirmware,setBootstrapFirmware]=useState(''),[bootstrapPassword,setBootstrapPassword]=useState('');
const profileIntent=useRef<Record<string,unknown>|null>(null);
const [latest,setLatest]=useState<Operation|null>(null);
const request=<T,>(body:Record<string,unknown>)=>trackerRequest<T>(projectRef,device,body);
const alive=useRef(true), intent=useRef<{action:string;request:Record<string,unknown>}|null>(null);
const file=useRef<HTMLInputElement>(null);
useEffect(()=>{
alive.current=true;
request<TrackerState>({action:'state'}).then(value=>{if(alive.current){setData(value);setLatest(value.latest_operation);setName(value.name);setPolicy(value.policy);}}).catch(onError).finally(()=>{if(alive.current)setBusy('');});
return()=>{alive.current=false;};
},[device.id,projectRef]);
async function refresh() { const next=await request<TrackerState>({action:'state'}); if(alive.current){setData(next);setLatest(next.latest_operation);} return next; }
useEffect(()=>{
if(!latest || !['queued','dispatched'].includes(latest.state))return;
let active=true;
const timer=setTimeout(async()=>{try {const result=await request<{items:Operation[]}>({action:'journal'});const item=result.items.find(row=>row.id===latest.id);if(active&&item){setLatest(item);if(!['queued','dispatched'].includes(item.state))await refresh();}}catch(error){if(active)onError(error);}},3000);
return()=>{active=false;clearTimeout(timer);};
},[latest]);
const edit=(value:Policy)=>{setPolicy(value);setDirty(true);};
async function run(label:string,work:()=>Promise<void>) {setBusy(label);try{await work();}catch(error){onError(error);}finally{if(alive.current)setBusy('');}}
async function save() {
if(!data)return 0;
const result=await request<{revision:number}>({action:'save',revision:data.revision,name,policy});
setData({...data,revision:result.revision,name,policy});setDirty(false);await onChanged();return result.revision;
}
async function operation(action:'read'|'apply') {
if(!data)return;
const pending=intent.current;
if(pending && pending.action!==action)throw new Error('Сначала уточните результат предыдущей отправки.');
if(!pending){
const revision=action==='apply'&&dirty?await save():data.revision;
intent.current={action,request:{action,id:newIntent(),...(action==='apply'?{revision,expected_sha256:data.observed?.sha256}:!data.observed?{bootstrap:{firmware:bootstrapFirmware,password:bootstrapPassword}}:{})}};
}
try {const result=await request<Operation>(intent.current!.request);intent.current=null;setBootstrapPassword('');setLatest(result);} catch(error) {if(error instanceof B2RequestError&&error.rejected)intent.current=null;throw error;}
}
const groupNames=[...new Set(data?.fields.map(field=>field.group)||[])];
const pending=Boolean(latest&&['queued','dispatched'].includes(latest.state));
const disabled=Boolean(busy)||pending||!canConfigure;
const connected=Boolean(data?.last_seen_at && Date.now()/1000-data.last_seen_at<120);
async function uploadFirmware(value:File) {
if(!/\.dfw$/i.test(value.name)||value.size>4*1024*1024||!value.size)throw new Error('Выберите непустой файл .dfw до 4 МБ.');
const bytes=new Uint8Array(await value.arrayBuffer());
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),n=>n.toString(16).padStart(2,'0')).join('');
for(let offset=0;offset<bytes.length;offset+=24576){const chunk=btoa(String.fromCharCode(...bytes.slice(offset,offset+24576)));await request({action:'firmware-upload',digest,filename:value.name,size:bytes.length,offset,chunk});}
await refresh();
}
async function downloadFirmware(digest:string) {
const chunks:Uint8Array<ArrayBuffer>[]=[];let offset=0,size=1,filename='firmware.dfw';
while(offset<size){const result=await request<{chunk:string;size:number;filename:string}>({action:'firmware-download',digest,offset});size=result.size;filename=result.filename;const bytes=Uint8Array.from(atob(result.chunk),c=>c.charCodeAt(0));if(!bytes.length)throw new Error('Неполный файл прошивки');chunks.push(bytes);offset+=bytes.length;}
const blob=new Blob(chunks);const actual=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',await blob.arrayBuffer())),n=>n.toString(16).padStart(2,'0')).join('');
if(actual!==digest)throw new Error('Контрольная сумма файла не совпала');
const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
return <>
<FeatureSettingsWindow open={!profileOpen} title="Настройки устройства" subtitle={`ARNavi B2 · ${device.number}`}
identity={{title:'ARNavi B2',subtitle:`IMEI ${device.identifier.masked}`,avatarLabel:'AR'}}
sections={[{id:'identity',label:'Устройство и проект'},{id:'connection',label:'Сервер и связь'},{id:'commands',label:'Команды'},{id:'firmware',label:'Прошивка'},...groupNames.map((group,index)=>({id:group,label:group,group:index===0?'Параметры профиля':undefined}))]}
activeSection={section} onSectionChange={setSection} onClose={onClose}
headerActions={<IconButton label={section==='commands'?'Обновить журнал команд':'Обновить сведения о трекере'} disabled={Boolean(busy)} loading={busy==='refresh'} onClick={()=>void run('refresh',async()=>{if(section==='commands')setCommandRefresh(value=>value+1);await refresh();})}><Icon name="refresh" /></IconButton>}
footer={section!=='commands'&&section!=='firmware'?<WindowFooterActions><Button disabled={disabled||!dirty||!data} loading={busy==='save'} onClick={()=>void run('save',async()=>{await save();})}>Сохранить настройки</Button><Button disabled={disabled||!data} onClick={()=>{profileIntent.current=null;setProfileName('');setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>:undefined}>
<div className="b2-tracker-form" aria-busy={Boolean(busy)}>
<StatusBadge tone={connected?'success':'neutral'}>{connected?'Передаёт данные на VPS':data?'Нет свежих данных':'Загрузка…'}</StatusBadge>
{data&&section!=='commands'&&section!=='firmware'?<SettingsCard title="Настройки через VPS">
<div className="b2-tracker-form">
<span>{data.observed?`Последнее чтение: ${formatTime(data.observed.received_at)}`:'Настройки трекера ещё не прочитаны'}</span>
{latest?<StatusBadge tone={operationTone(latest.state)}>{stateName(latest.state)}</StatusBadge>:null}{pending?<span>Задание сохранено на VPS. Окно можно закрыть.</span>:null}
<Button disabled={Boolean(busy)||pending||!canConfigure||!canCommand||!data.capabilities.configuration} loading={busy==='apply'} onClick={()=>void run('apply',()=>operation('apply'))}>{intent.current?.action==='apply'?'Уточнить отправку':'Отправить через VPS'}</Button>
{!data.observed?<><Select label="Версия прошивки B2" value={bootstrapFirmware} disabled={Boolean(busy)||!canCommand} onChange={setBootstrapFirmware} options={[{value:'',label:'Выберите установленную версию'},{value:'0.01',label:'0.01'},{value:'0.06',label:'0.06'}]} /><TextField label="Пароль конфигурации трекера" type="password" autoComplete="off" maxLength={6} value={bootstrapPassword} disabled={Boolean(busy)||!canCommand} onChange={event=>setBootstrapPassword(event.target.value)} /></>:null}
<Button disabled={Boolean(busy)||pending||!canCommand||(!data.capabilities.configuration&&!intent.current&&(!bootstrapFirmware||!/^\d{6}$/.test(bootstrapPassword)))} loading={busy==='read'} onClick={()=>void run('read',()=>operation('read'))}>{intent.current?.action==='read'?'Уточнить чтение':'Прочитать через VPS'}</Button>
</div>
</SettingsCard>:null}
{section==='identity'&&data?<>
<TextField label="Название" value={name} disabled={disabled} onChange={event=>{setName(event.target.value);setDirty(true);}} />
<Select label="Сохранённый профиль" value={profile} disabled={disabled} options={[{value:'',label:'Без профиля'},...data.profiles.map(item=>({value:item.id,label:item.name}))]} onChange={id=>{setProfile(id);const selected=data.profiles.find(item=>item.id===id);if(selected)edit(structuredClone(selected.policy));}} />
<SettingsCard title="Сведения об устройстве"><dl className="b2-tracker-facts"><dt>Модель</dt><dd>ARNavi B2 · 231</dd><dt>Номер</dt><dd>{data.number}</dd><dt>IMEI</dt><dd>{data.identifier}</dd><dt>Прошивка</dt><dd>{data.firmware||'Не прочитана'}</dd><dt>Последние данные</dt><dd>{formatTime(data.last_seen_at)}</dd></dl></SettingsCard>
</>:null}
{section==='connection'&&data?<>
{[1,2].map(slot=><SettingsCard key={slot} title={`SIM${slot}`} actions={data.modem?.active_sim===slot&&Date.now()/1000-data.modem.measured_at<90?<StatusBadge tone="success">Интернет</StatusBadge>:undefined}>
<div className="b2-tracker-form"><span>{data.sims[String(slot)]?.identifier||'Нет сведений о карте'}</span><dl className="b2-tracker-facts"><dt>Регистрация</dt><dd>{({0:'Не обнаружена',1:'В домашней сети',2:'Поиск сети',3:'Отказ регистрации',4:'Нет сведений',5:'Роуминг'} as Record<number,string>)[data.cellular.status?.sim_states[String(slot)]??4]}</dd><dt>Сигнал</dt><dd>{data.cellular.networks?.[String(slot)]?.signal!=null?`${data.cellular.networks[String(slot)].signal} / 31`:'—'}</dd><dt>Наблюдение</dt><dd>{formatTime(data.cellular.measured_at)}</dd><dt>APN</dt><dd>{(slot===1?data.observed?.apn1:data.observed?.apn2)||'Автоматически'}</dd></dl>
<Select label={`Настройки оператора SIM${slot}`} value={policy.connectivity[slot===1?'preset1':'preset2']||''} disabled={disabled||policy.connectivity.mode==='native'} options={[{value:'',label:'Сохранить или указать APN'},...data.carrier_presets.map(item=>({value:item.id,label:item.label}))]} onChange={preset=>{const connectivity={...policy.connectivity};const key=slot===1?'preset1':'preset2';if(preset)connectivity[key]=preset;else delete connectivity[key];edit({...policy,connectivity});}} />
<TextField label={`APN SIM${slot}`} placeholder="Сохранить текущее значение" value={policy.connectivity[slot===1?'apn1':'apn2']??''} disabled={disabled||policy.connectivity.mode==='native'||Boolean(policy.connectivity[slot===1?'preset1':'preset2'])} onChange={event=>edit({...policy,connectivity:{...policy.connectivity,[slot===1?'apn1':'apn2']:event.target.value}})} />
</div>
</SettingsCard>)}
<Select label="Режим интернета" value={policy.connectivity.mode} disabled={disabled} onChange={mode=>edit({...policy,connectivity:{...policy.connectivity,mode}})} options={[{value:'preserve',label:'Сохранить режим трекера'},{value:'native',label:'Автоматический режим без заданного APN'},{value:'both',label:'Автоматический режим — сохранить APN'},{value:'sim1',label:'Только SIM1'},{value:'sim2',label:'Только SIM2'}]} />
<SettingsCard title="Сервер мониторинга"><div className="b2-tracker-form">
<Switch label="Задать сервер в профиле" checked={Boolean(policy.endpoint)} disabled={disabled} onChange={checked=>edit({...policy,endpoint:checked?{slot:1,host:data.observed?.servers[0]?.host||'',port:data.observed?.servers[0]?.port||9922}:null})} />
{policy.endpoint?<><TextField label="DNS/IP сервера" value={policy.endpoint.host} disabled={disabled} onChange={event=>edit({...policy,endpoint:{...policy.endpoint!,host:event.target.value}})} /><TextField label="Порт" type="number" min={1} max={65535} value={policy.endpoint.port} disabled={disabled} onChange={event=>edit({...policy,endpoint:{...policy.endpoint!,port:Number(event.target.value)}})} /><Select label="Слот сервера" value={String(policy.endpoint.slot)} disabled={disabled} options={[1,3,4].map(slot=>({value:String(slot),label:`Сервер ${slot}`}))} onChange={slot=>edit({...policy,endpoint:{...policy.endpoint!,slot:Number(slot)}})} /></>:null}
<ResourceList>{data.observed?.servers.map(server=><li key={server.slot}><ResourceRow title={`Сервер ${server.slot}`} metadata={`${server.host}:${server.port}`} description={server.slot===2?'Связь с текущим VPS':undefined} /></li>)}</ResourceList>
</div></SettingsCard>
</>:null}
{groupNames.includes(section)&&data?<><span>Пустое поле — сохранить значение трекера.</span>{data.fields.filter(field=>field.group===section).map(field=><TextField key={field.id} label={field.label} hint={`${field.minimum} … ${field.maximum}`} type="number" step={1} min={field.minimum} max={field.maximum} disabled={disabled||!Object.hasOwn(data.observed?.parameters||{},field.id)} placeholder={String(data.observed?.parameters[field.id]??'Недоступно на этой прошивке')} value={policy.parameters[field.id]??''} onChange={event=>{const parameters={...policy.parameters};if(event.target.value==='')delete parameters[field.id];else parameters[field.id]=Number(event.target.value);edit({...policy,parameters});}} />)}</>:null}
<B2CommandPanel projectRef={projectRef} device={device} data={data} canCommand={canCommand} active={section==='commands'} refreshKey={commandRefresh} onError={onError} />
{section==='firmware'&&data?<><SettingsCard title="Прошивка устройства"><ResourceRow title={`Установлена ${data.firmware||'неизвестная версия'}`} metadata="Архив файлов · установка по сети недоступна" /></SettingsCard>
<SettingsCard title="Архив прошивок" actions={<IconButton label="Добавить прошивку" disabled={disabled} onClick={()=>file.current?.click()}><Icon name="plus" /></IconButton>}>
<input ref={file} type="file" accept=".dfw" hidden onChange={event=>{const selected=event.target.files?.[0];event.target.value='';if(selected)void run('firmware',()=>uploadFirmware(selected));}} />
<ResourceList>{data.firmwares.map(item=><li key={item.sha256}><ResourceRow title={item.filename} metadata={`${item.bytes.toLocaleString('ru-RU')} байт · ${formatTime(item.added_at)}`} description={item.complete?undefined:'Загрузка не завершена — выберите файл повторно'} actions={<IconButton label={`Скачать ${item.filename}`} disabled={!item.complete||Boolean(busy)} onClick={()=>void run('firmware',()=>downloadFirmware(item.sha256))}><Icon name="download" /></IconButton>} /></li>)}</ResourceList>
{!data.firmwares.length?<span>Нет сохранённых файлов</span>:null}
</SettingsCard></>:null}
</div>
</FeatureSettingsWindow>
<Window open={profileOpen} title="Сохранить профиль" size="sm" onClose={()=>setProfileOpen(false)} footer={<WindowFooterActions><Button loading={busy==='profile'} disabled={Boolean(busy)||!profileName.trim()} onClick={()=>void run('profile',async()=>{profileIntent.current ||= {action:'profile-save',id:newIntent(),name:profileName,policy};try{await request(profileIntent.current);profileIntent.current=null;}catch(error){if(error instanceof B2RequestError&&error.rejected)profileIntent.current=null;throw error;}setProfileOpen(false);await refresh();})}>Сохранить профиль</Button></WindowFooterActions>}><TextField label="Название профиля" disabled={Boolean(busy)||Boolean(profileIntent.current)} autoFocus value={profileName} onChange={event=>setProfileName(event.target.value)} /></Window>
</>;
}
const presets=[{id:'position',label:'Запросить координаты',command:{kind:'request-position'}},{id:'restart',label:'Перезапустить B2',command:{kind:'restart'}},...[4,5,6].flatMap(pin=>[...([true,false] as const).map(enabled=>({id:`pin${pin}-${enabled}`,label:`${enabled?'Включить':'Выключить'} выход PIN${pin}`,command:{kind:'set-output',pin,enabled}})),{id:`pin${pin}-pulse`,label:`Импульс PIN${pin} · 5 с`,command:{kind:'pulse-output',pin,seconds:5}}])];
function B2CommandPanel({projectRef,device,data,canCommand,active,refreshKey,onError}:{projectRef:string;device:TrackerRef;data:TrackerState|null;canCommand:boolean;active:boolean;refreshKey:number;onError:(error:unknown)=>void}) {
const [filter,setFilter]=useState('all');
const [selection,setSelection]=useState('position'),[rows,setRows]=useState<Operation[]>([]),[before,setBefore]=useState<number|null>(null),[busy,setBusy]=useState(false),[details,setDetails]=useState<string[]>([]),[history,setHistory]=useState<Record<string,unknown>>({});
const intent=useRef<Record<string,unknown>|null>(null),alive=useRef(true);
const request=<T,>(body:Record<string,unknown>)=>trackerRequest<T>(projectRef,device,body);
async function refresh(append=false) {const result=await request<{items:Operation[];before:number|null}>({action:'journal',...(append&&before?{before}:{})});if(alive.current){setRows(old=>append?[...old,...result.items]:result.items);setBefore(result.before);}}
useEffect(()=>{alive.current=true;return()=>{alive.current=false;};},[]);
useEffect(()=>{if(active)void refresh().catch(onError);},[active,refreshKey]);
useEffect(()=>{if(!active||!rows.some(row=>['queued','dispatched'].includes(row.state)))return;const timer=setTimeout(()=>void refresh().catch(onError),3000);return()=>clearTimeout(timer);},[active,rows]);
const selected=presets.find(item=>item.id===selection)!;
const pin='pin' in selected.command?selected.command.pin:null;
const available=data?.capabilities.configuration&&(!pin||data.observed?.output_modes[String(pin)]===1);
async function send(command:Record<string,unknown>=selected.command) {setBusy(true);try {intent.current ||= {action:'command',id:newIntent(),command};await request(intent.current);intent.current=null;await refresh();}catch(error){if(error instanceof B2RequestError&&error.rejected)intent.current=null;onError(error);}finally{setBusy(false);}}
// Keep the panel mounted across tabs so an uncertain send retains its intent ID.
return <div hidden={!active}>
<div className="b2-tracker-form">
<SettingsCard title="Отправка команды"><div className="b2-tracker-form"><Select label="Команда" value={selection} disabled={busy||Boolean(intent.current)} options={presets.map(item=>({value:item.id,label:item.label,disabled:'pin' in item.command&&data?.observed?.output_modes[String(item.command.pin)]!==1}))} onChange={setSelection} />
{pin?<span>Подтверждение доставки не определяет положение контактов реле.</span>:null}
<Button loading={busy} disabled={busy||!canCommand||!available} onClick={()=>void send()}>{intent.current?'Уточнить отправку':'Отправить'}</Button>
</div></SettingsCard>
<SettingsCard title="Журнал команд"><Select label="Показать команды" value={filter} onChange={setFilter} options={[{value:'all',label:'Все команды'},{value:'pending',label:'Ожидают результата'},{value:'finished',label:'Завершённые'}]} /><ResourceList>{rows.filter(row=>filter==='all'||(filter==='pending')===['queued','dispatched'].includes(row.state)).map(row=><li key={row.id}><ResourceRow title={operationName(row.kind,row.command)} metadata={formatTime(row.created_at)} status={<StatusBadge tone={operationTone(row.state)}>{stateName(row.state)}</StatusBadge>} actions={<>{canCommand&&row.repeatable&&row.command?<IconButton label={`Повторить ${operationName(row.kind,row.command)}`} disabled={busy||Boolean(intent.current)} onClick={()=>{const preset=presets.find(item=>JSON.stringify(item.command)===JSON.stringify(row.command));if(preset)setSelection(preset.id);void send(row.command);}}><Icon name="refresh" /></IconButton>:null}<IconButton label={`Подробнее ${row.id}`} aria-expanded={details.includes(row.id)} onClick={()=>{setDetails(old=>old.includes(row.id)?old.filter(id=>id!==row.id):[...old,row.id]);void request({action:'attempts',operation:row.id}).then(value=>setHistory(old=>({...old,[row.id]:value}))).catch(onError);}}><Icon name={details.includes(row.id)?'chevron-up':'chevron-down'} /></IconButton>{canCommand&&['queued','dispatched'].includes(row.state)?<IconButton label={`Остановить ${row.id}`} onClick={()=>void request({action:'cancel',operation:row.id,kind:row.kind}).then(()=>refresh()).catch(onError)}><Icon name="close" /></IconButton>:null}</>} />
{details.includes(row.id)?<div className="b2-disclosure__body"><dl className="b2-tracker-facts"><dt>Попытки</dt><dd>{row.attempt_count??0}</dd><dt>Отправлена</dt><dd>{formatTime(row.dispatched_at)}</dd><dt>Ответ</dt><dd>{formatTime(row.received_at||row.delivered_at||row.verified_at)}</dd><dt>Результат</dt><dd>{stateName(row.state)}</dd><dt>ID</dt><dd>{row.id}</dd></dl><AttemptRows value={history[row.id]} onMore={before=>void request<{items:Operation[];next_before:number|null}>({action:'attempts',operation:row.id,before}).then(value=>setHistory(old=>({...old,[row.id]:{...value,items:[...((old[row.id] as {items:Operation[]})?.items||[]),...value.items]}}))).catch(onError)} /></div>:null}
</li>)}</ResourceList>{!rows.length?<span>Команд пока нет</span>:null}{before?<Button onClick={()=>void refresh(true).catch(onError)}>Предыдущие команды</Button>:null}</SettingsCard>
</div>
</div>;
}
function AttemptRows({value,onMore}:{value:unknown;onMore:(before:number)=>void}) { const page=value as {items?:Operation[];next_before?:number|null}|undefined;return page?.items?.length?<><ResourceList>{page.items.map((item,index)=><li key={item.id||index}><ResourceRow title={`Попытка ${item.number??index+1}`} metadata={formatTime(item.dispatched_at)} status={<StatusBadge tone={operationTone(item.state)}>{stateName(item.state)}</StatusBadge>} /></li>)}</ResourceList>{page.next_before?<Button onClick={()=>onMore(page.next_before!)}>Предыдущие попытки</Button>:null}</>:null; }
+14 -4
View File
@@ -2,17 +2,24 @@ export type B2Contour = { id: string; key: string; name: string; access?: string
export type B2Application = { id: string; key: string; name: string; authority: 'host' | 'contours';
grants: Record<string, string>; credentials: Array<{ client_id: string; enabled: boolean }> };
export type B2Status = { connected: boolean; endpoint?: string; authority?: 'host' | 'contours';
sharedProjects?: boolean;
contours?: B2Contour[]; applications?: B2Application[];
links?: Array<{ contourId: string; projectRef: string }> };
export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string };
const messages: Record<string, string> = {
b2_settings_revision_changed: 'Настройки изменились. Обновите сведения о трекере перед отправкой.',
b2_settings_initial_read_required: 'Сначала прочитайте настройки трекера через VPS.',
b2_settings_sim_observation_required: 'Нет свежих данных выбранной SIM. Дождитесь регистрации карты и обновите сведения.',
b2_request_invalid: 'Проверьте параметры: VPS отклонил запрос.',
b2_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.',
b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.',
b2_host_management_required: 'Нужен ключ администратора VPS из установщика. Ключ приложения подходит только для доступа к его контуру.',
b2_host_identity_mismatch: 'Сервер не совпадает с идентификатором в файле подключения.',
b2_host_not_connected: 'Сначала подключите VPS.',
b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.',
b2_key_rejected: 'VPS не принял ключ подключения.',
b2_conflict: 'На VPS уже есть запись с такими данными. Обновите список и проверьте результат.',
b2_contour_already_linked: 'Этот контур уже связан с другим проектом.',
b2_shared_projects_migration_required: 'На сервере Device Core ещё не установлена миграция общих контуров. До её установки контур можно связать только с одним проектом.',
b2_connection_identity_conflict: 'Этот хост уже подключён другим приложением или ключом сервера.',
b2_certificate_mismatch: 'Сертификат VPS не соответствует ключу подключения.',
b2_private_storage_unavailable: 'Закрытое хранилище ключей ещё не настроено на Device Core.',
@@ -20,13 +27,16 @@ const messages: Record<string, string> = {
b2_company_mismatch: 'Выберите проект той же компании.',
device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.',
};
export async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}): Promise<T> {
export class B2RequestError extends Error {
constructor(message: string, public readonly rejected: boolean) { super(message); }
}
export async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}, requestId = crypto.randomUUID().replaceAll('-', '')): Promise<T> {
const response = await fetch('/api/device-manager/b2/infrastructure', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID().replaceAll('-', '') },
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': requestId },
body: JSON.stringify({ projectRef, hostRef, action, ...fields }),
});
const body = await response.json().catch(() => null);
if (!response.ok || body?.ok !== true) throw new Error(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.');
if (!response.ok || body?.ok !== true) throw new B2RequestError(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.', response.status >= 400 && response.status < 500);
return body.result as T;
}
+21 -6
View File
@@ -1,6 +1,21 @@
.b2-settings { display: grid; gap: var(--nodedc-space-md, 16px); }
.b2-settings p { margin: 0; font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
.b2-resource { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-sm, 8px); flex-wrap: wrap; }
.b2-resource > div { display: grid; gap: 4px; min-width: 0; }
.b2-resource strong { font-size: var(--nodedc-font-size-sm); }
.b2-resource small { font-size: var(--nodedc-font-size-xs); overflow-wrap: anywhere; color: var(--nodedc-text-secondary); }
.b2-settings { display: grid; gap: var(--nodedc-space-4); }
.b2-settings p, .b2-path { margin: 0; font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
.b2-path { overflow-wrap: anywhere; }
.b2-actions { display: flex; gap: var(--nodedc-space-2); flex-wrap: wrap; justify-content: flex-end; }
.b2-key-id { font-family: inherit; font-size: var(--nodedc-font-size-sm); overflow-wrap: anywhere; font-weight: 400; }
.b2-disclosure { display: grid; gap: var(--nodedc-space-2); }
.b2-disclosure__body { display: grid; gap: var(--nodedc-space-3); padding: var(--nodedc-space-2) var(--nodedc-space-3) var(--nodedc-space-4); }
.b2-section-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-3); font-size: var(--nodedc-font-size-sm); }
.b2-contours-heading { margin: 0; padding-inline: var(--nodedc-space-3); font-weight: var(--nodedc-font-weight-strong); }
.b2-contours { gap: var(--nodedc-space-4); }
.b2-contour { display: grid; gap: var(--nodedc-space-2); }
.b2-contour[data-expanded="false"] { background: transparent; box-shadow: none; }
.b2-contour[data-expanded="true"] > .b2-contour__header { background: transparent; }
.b2-tracker-form { display: grid; min-width: 0; gap: 1rem; font-size: var(--nodedc-font-size-sm); }
.b2-tracker-facts { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr); gap: .65rem 1rem; margin: 0; font-size: var(--nodedc-font-size-sm); }
.b2-tracker-facts dt { color: var(--nodedc-text-muted); }
.b2-tracker-facts dd { margin: 0; overflow-wrap: anywhere; }
.b2-onboarding-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--nodedc-space-4); align-items: start; }
.b2-onboarding-grid > * { min-width: 0; }
@@ -0,0 +1,10 @@
{
"version": "0.2.5",
"filename": "nodedc-arnavi-vps-0.2.5.pyz",
"sha256": "d9a822ca7c2498841a6fd13fddac27da4fc22366931ba8980b97c66c159a383f",
"bytes": 16129246,
"sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git",
"sourceCommit": "193253dd48a1c6390ea4c5e500693123b88ce2ea",
"manifestSha256": "139a3c1d7f3e8266e2154586783133078311aa9dae76d74ed229aab16f816197",
"environment": "ubuntu-24.04-amd64"
}
+22
View File
@@ -0,0 +1,22 @@
import { b2Request, type B2Device } from './api';
export type TrackerRef = B2Device & { hostRef: string; hostName: string };
export type Policy = { parameters: Record<string, number>; connectivity: { mode: string; apn1?: string; apn2?: string; preset1?: string; preset2?: string }; endpoint?: { host: string; port: number; slot: number } | null };
export type Operation = { command?:Record<string,unknown>;repeatable?:boolean;number?:number; id: string; kind: string; state: string; runtime_phase?: string; reason?: string; sequence?: number; created_at?: number; received_at?: number; dispatched_at?: number; verified_at?: number; delivered_at?: number; attempt_count?: number; roundtrip_seconds?: number; delivery_seconds?: number; stop_requested?: boolean };
export type TrackerState = { id: string; name: string; number: number; identifier: string; revision: number; firmware: string | null; policy: Policy;
observed: { sha256: string; received_at: number; parameters: Record<string, number>; servers: Array<{slot:number;host:string;port:number}>; apn1:string;apn2:string;internet_mode:string;output_modes:Record<string,number> } | null;
carrier_presets: Array<{id:string;label:string;apn:string}>;
cellular: {measured_at?:number;status?:{sim_states:Record<string,number>};networks?:Record<string,{mcc:number|null;mnc:number;signal:number|null}>};
fields: Array<{id:string;label:string;group:string;minimum:number;maximum:number}>;
profiles: Array<{id:string;name:string;policy:Policy}>;
firmwares: Array<{sha256:string;filename:string;bytes:number;complete:boolean;added_at:number}>;
latest_operation:Operation|null; last_seen_at: number | null; modem: {active_sim:number;measured_at:number} | null; sims: Record<string,{identifier:string;measured_at:number|null}>;
capabilities: {configuration:boolean;firmware_archive:boolean;firmware_install:boolean};
};
export function trackerRequest<T>(projectRef: string, device: TrackerRef, request: Record<string, unknown>) {
return b2Request<T>(projectRef,device.hostRef,'tracker',{contourId:device.contourId,deviceId:device.id,request});
}
export const newIntent = () => crypto.randomUUID().replaceAll('-','');
export const operationName = (kind: string, command?:Record<string,unknown>) => command?.pin ? `${kind==='pulse-output'?'Импульс':command.enabled?'Включить':'Выключить'} PIN${command.pin}${kind==='pulse-output'?` · ${command.seconds} с`:''}` : ({'request-position':'Запросить координаты',restart:'Перезапустить B2','read-configuration':'Прочитать настройки','configure-all':'Применить настройки','select-sim':'Изменить режим SIM','set-output':'Переключить выход','pulse-output':'Импульс выхода'}[kind] || 'Операция B2');
export const stateName = (state: string) => ({queued:'В очереди VPS',dispatched:'Отправлено B2',observed:'Настройки прочитаны',verified:'Настройки проверены',accepted:'Принято B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',sim_selected:'SIM подключена',reconnected:'Связь после перезапуска подтверждена',delivered:'Доставлено',stopped:'Повторы остановлены',cancelled:'Отменено до отправки',rejected:'Отклонено',uncertain:'Результат неизвестен',unconfirmed:'Результат не подтверждён',not_applied:'Не применено',expired:'Попытка завершилась без ответа',failed:'Ошибка'}[state] || 'Неизвестный статус');
export const operationTone = (state:string):'success'|'warning'|'neutral' => ['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral';
export const formatTime = (value?: number | null) => value ? new Date(value*1000).toLocaleString('ru-RU') : '—';
+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 = '';
}
}
@@ -0,0 +1,21 @@
import { useEffect, useState } from 'react';
import { b2Request, type B2Device } from './api';
export type B2HostState = { hostRef: string; name: string; endpoint: string; contours: number; reachable: boolean; checkedAt: string; devices: number | null };
export type B2Inventory = { items: Array<B2Device & { hostRef: string; hostName: string }>; hosts: B2HostState[] };
export function useB2Inventory(projectRef: string, refreshSignal: unknown) {
const [snapshot, setSnapshot] = useState<{ projectRef: string; data: B2Inventory | null; error: string } | null>(null);
useEffect(() => {
let active = true, timer: ReturnType<typeof setTimeout>;
async function load() {
try {
const next = await b2Request<B2Inventory>(projectRef, '', 'inventory');
if (active) setSnapshot({ projectRef, data: next, error: '' });
} catch (reason) {
if (active) setSnapshot({ projectRef, data: null, error: reason instanceof Error ? reason.message : 'VPS недоступен' });
} finally { if (active) timer = setTimeout(load, 30_000); }
}
void load();
return () => { active = false; clearTimeout(timer); };
}, [projectRef, refreshSignal]);
return snapshot?.projectRef === projectRef ? snapshot : { data: null, error: '' };
}
@@ -0,0 +1,42 @@
const roles: Record<string, string> = {
owner: 'Владелец', admin: 'Администратор', operator: 'Оператор',
maintainer: 'Сопровождение', viewer: 'Наблюдатель', read: 'Просмотр',
};
export const projectRoleLabel = (role: string) => roles[role] || role;
const capabilities: Record<string, string> = {
'access.manage': 'Управление доступом', 'asset.manage': 'Управление объектами',
'audit.read': 'Просмотр аудита', 'binding.manage': 'Управление связями с Foundry',
'collection.manage': 'Управление коллекциями', 'command.confirm': 'Подтверждение команд',
'command.dispatch': 'Отправка команд', 'command.plan': 'Подготовка команд',
'configuration.manage': 'Изменение настроек устройств', 'configuration.read': 'Просмотр настроек устройств',
'credential.manage': 'Управление ключами', 'device.claim': 'Привязка устройств',
'device.enroll': 'Регистрация устройств', 'device.transfer': 'Перенос устройств',
'infrastructure.manage': 'Изменение инфраструктуры', 'infrastructure.read': 'Просмотр инфраструктуры',
'inventory.read': 'Просмотр реестра', 'observation.write': 'Запись наблюдений',
'project.manage': 'Управление проектом', 'project.read': 'Просмотр проекта',
'route.manage': 'Управление маршрутами', 'telemetry.observe': 'Просмотр телеметрии',
};
export const capabilityLabel = (capability: string) => capabilities[capability] || capability;
const eventObjects: Record<string, string> = {
owner_scope: 'Компания', project: 'Проект', collection: 'Коллекция',
project_grant: 'Доступ к проекту', command: 'Команда', device: 'Устройство',
discovery: 'Обнаруженное устройство', enrollment_intent: 'Регистрация устройства',
device_credential_binding: 'Ключ устройства', device_binding: 'Связь устройства',
device_configuration_revision: 'Версия настроек', device_configuration: 'Настройки устройства',
asset: 'Объект', asset_binding: 'Привязка объекта', edge: 'Узел', route: 'Маршрут',
infrastructure_host: 'VPS', infrastructure_endpoint: 'Точка подключения',
infrastructure_deployment: 'Развёртывание', infrastructure_service_instance: 'Сервис',
health_observation: 'Наблюдение',
};
const eventActions: Record<string, string> = {
created: 'создание', updated: 'изменение', archived: 'архивирование', restored: 'восстановление',
revoked: 'отзыв', claimed: 'привязка', queued: 'добавление в очередь', dispatched: 'отправка',
verified: 'подтверждение', confirmed: 'подтверждение', closed: 'закрытие', recorded: 'запись',
desired_changed: 'сохранение изменений', transferred_in: 'перенос в проект', transferred_out: 'перенос из проекта',
};
export function auditEventLabel(event: string) {
const [object, action] = event.split('.');
return eventObjects[object] && eventActions[action] ? `${eventObjects[object]} · ${eventActions[action]}` : event;
}
+12 -82
View File
@@ -5,7 +5,6 @@
.device-control-toolbar {
align-items: center;
padding: 2px 0 14px;
border-bottom: 1px solid var(--nodedc-glass-outline);
}
.device-control-toolbar > p {
@@ -42,8 +41,8 @@
.device-control-resource-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
gap: var(--nodedc-space-3);
grid-template-columns: minmax(0, 1fr);
}
.device-control-row {
@@ -122,9 +121,7 @@
}
.device-control-form {
max-height: min(62vh, 680px);
overflow-y: auto;
padding-right: 3px;
min-width: 0;
}
.infrastructure-system-workspace {
@@ -142,55 +139,9 @@
.infrastructure-assets-block {
min-width: 0;
border-radius: var(--nodedc-radius-card);
background: var(--infrastructure-panel-soft);
padding: 1rem;
}
.infrastructure-system-workspace .nodedc-status {
min-height: auto;
justify-content: flex-start;
gap: 0.42rem;
border-radius: 0;
background: transparent;
color: var(--nodedc-text-primary);
padding: 0;
font-size: var(--nodedc-font-size-sm);
font-weight: var(--nodedc-font-weight-medium);
}
.infrastructure-system-workspace .nodedc-status::before {
width: 0.42rem;
height: 0.42rem;
flex: 0 0 0.42rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
content: "";
}
.infrastructure-system-workspace .nodedc-status[data-tone="success"],
.infrastructure-system-workspace .nodedc-status[data-tone="warning"],
.infrastructure-system-workspace .nodedc-status[data-tone="danger"],
.infrastructure-system-workspace .nodedc-status[data-tone="accent"] {
background: transparent;
color: var(--nodedc-text-primary);
}
.infrastructure-system-workspace .nodedc-status[data-tone="success"]::before {
background: rgb(var(--nodedc-success-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="warning"]::before {
background: rgb(var(--nodedc-warning-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="danger"]::before {
background: rgb(var(--nodedc-danger-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="accent"]::before {
background: var(--nodedc-text-primary);
}
.infrastructure-eyebrow {
display: block;
color: var(--nodedc-text-muted);
@@ -264,7 +215,6 @@
.host-monitoring-series {
min-width: 0;
border-radius: var(--nodedc-radius-card);
background: var(--infrastructure-panel-soft);
}
.infrastructure-count-card {
@@ -425,7 +375,6 @@
margin: 0;
padding: 0.72rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
}
.infrastructure-host-card__facts > div {
@@ -464,7 +413,6 @@
gap: 0.55rem;
padding: 0.72rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
}
.infrastructure-host-relations > section > header {
@@ -573,7 +521,6 @@
gap: 0.9rem;
padding: 0.72rem 0.8rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
}
.infrastructure-registry-row > div,
@@ -610,7 +557,6 @@
.infrastructure-empty {
padding: 0.8rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
color: var(--nodedc-text-muted);
font-size: 0.65rem;
line-height: 1.5;
@@ -696,7 +642,6 @@
margin: 0;
gap: 0;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
}
.host-monitoring-hardware-facts dl > div {
@@ -1277,16 +1222,6 @@ body {
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 {
display: flex;
flex-wrap: wrap;
@@ -1309,8 +1244,8 @@ body {
.device-inventory__filters {
display: grid;
max-width: 620px;
grid-template-columns: repeat(2, minmax(0, 1fr));
max-width: 960px;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.75rem;
}
@@ -1319,7 +1254,6 @@ body {
gap: 0.75rem;
margin-top: 0.45rem;
padding-top: 1rem;
border-top: 1px solid var(--nodedc-glass-border);
}
.device-inventory__section-heading {
@@ -1441,7 +1375,6 @@ body {
align-items: center;
gap: 0.9rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--nodedc-glass-border);
}
.device-detail__identity {
@@ -1604,7 +1537,6 @@ body {
display: flex;
justify-content: flex-end;
gap: 0.55rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem;
}
@@ -1640,7 +1572,6 @@ body {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.35rem 0.7rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem;
color: var(--nodedc-text-secondary);
font-size: 0.65rem;
@@ -1705,14 +1636,6 @@ body {
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 {
display: none;
}
@@ -1750,3 +1673,10 @@ body {
}
}
/* Domain groups use the panel canvas; shared ResourceRow/SettingsCard own surfaces. */
.device-inventory__empty { min-height: 12rem; }
.device-manager-empty h3 { font-size: var(--nodedc-font-size-md); }
.device-control-disclosure__body { padding: var(--nodedc-space-4); color: var(--nodedc-text-secondary); }
.device-control-disclosure__body p { margin-top: 0; }
@@ -0,0 +1,13 @@
{
"schemaVersion": "nodedc.device-b2-shared-contours.v1",
"releaseId": "device-b2-shared-contours-v1-20261001-001",
"baselineReleaseId": "device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718",
"baselineSha256": "fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe",
"files": {
"deployment/device-b2-shared-contours-v1.sql": "caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a",
"deployment/device-b2-shared-contours-v1.rollback.sql": "f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f"
},
"transition": "one-contour-many-projects",
"services": [],
"rollback": "refuse-multiple-projects;preserve-all-rows"
}
@@ -0,0 +1,20 @@
begin;
set local lock_timeout = '5s';
set local statement_timeout = '30s';
lock table device_b2_contour_links in access exclusive mode;
do $$
begin
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-shared-contours/v1'
or (select pg_get_constraintdef(oid) from pg_constraint
where conrelid='device_b2_contour_links'::regclass and contype='p')
is distinct from 'PRIMARY KEY (source_id, contour_id, project_id)' then
raise exception 'device_b2_shared_contours_rollback_predecessor_mismatch';
end if;
if exists(select 1 from device_b2_contour_links group by source_id,contour_id having count(*)>1) then
raise exception 'device_b2_shared_contours_rollback_would_lose_links';
end if;
end $$;
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
alter table device_b2_contour_links add primary key (source_id, contour_id);
comment on table device_b2_contour_links is 'nodedc.device-b2-foundation/v1';
commit;
@@ -0,0 +1,32 @@
begin;
set local lock_timeout = '5s';
set local statement_timeout = '30s';
-- Separate, versioned foundation transition. Never run from application startup.
-- Preserve every assignment; only the identity of an assignment becomes a triple.
lock table device_b2_contour_links in access exclusive mode;
create temporary table device_b2_links_before on commit drop as
select * from device_b2_contour_links;
do $$
begin
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-foundation/v1'
or (select pg_get_constraintdef(oid) from pg_constraint
where conrelid='device_b2_contour_links'::regclass and contype='p')
is distinct from 'PRIMARY KEY (source_id, contour_id)' then
raise exception 'device_b2_shared_contours_predecessor_mismatch';
end if;
end $$;
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
alter table device_b2_contour_links add primary key (source_id, contour_id, project_id);
comment on table device_b2_contour_links is 'nodedc.device-b2-shared-contours/v1';
do $$
begin
if exists(
(select * from device_b2_links_before except all select * from device_b2_contour_links)
union all
(select * from device_b2_contour_links except all select * from device_b2_links_before)
) then
raise exception 'device_b2_shared_contours_row_preservation_failed';
end if;
end $$;
commit;
+69 -10
View File
@@ -1,7 +1,8 @@
# Shared ARNavi VPS and Device Core infrastructure
Status: Synology foundation accepted, 2026-09-30. Shared VPS activation and
end-to-end interface acceptance are still pending.
Status: Synology foundation and VPS 0.2.0 activation accepted, 2026-09-30.
Infrastructure UI acceptance passed on live release r18. Full B2 device, command,
SIM and firmware UI parity remains a separate next phase.
Device Core now has two distinct transport integrations. ADR 0001 still governs
the original Core-initiated mTLS Edge channel. The independent ARNavi VPS service
@@ -20,11 +21,15 @@ initiates all HTTPS requests; this integration adds no inbound Synology port.
3. The server validates that credential against the pinned host before saving
it in a separate private persistent filesystem mount. No secret goes into
project tables, audit payloads, browser storage, Git or deployment artifacts.
4. In Contours and projects, create a contour on the VPS and explicitly link it
4. In VPS settings → Contours, create a contour on the VPS and explicitly link it
to an accessible project of the same company. Linking another project adds
a view of the same host there. It does not duplicate the remote VPS or key.
5. In Applications and keys, create an application for a selected contour.
Issue its key and transfer it to that application's backend. Each application
5. Open that contour, then add an application inside its Applications list.
Open the application to manage its keys.
Issue its key, copy the JSON package and transfer it to that application's backend.
Copy was verified; the download button is implemented but its in-app-browser
download event was not confirmed. The canonical VPS CLI also writes a private
package file. Each application
has its own identity even when several consume the same contour.
6. Reissue replaces the credentials of that application. Contour/device IDs,
history and subscriptions remain. Revoke immediately stops that credential.
@@ -83,8 +88,7 @@ Do not weaken the existing release migration/topology guards to publish this
feature. Postgres/container volumes, existing Edge topology, identities and
secrets remain prerequisites, not selected services.
The public UI and running VPS remain on their accepted previous releases until
that exact transition and VPS authority installation pass acceptance. The old
Public release r18 and VPS authority/foundation003 are accepted. The old
unidentified Robot2B pilot must not be treated as the physical rover tracker.
## Validation bounds
@@ -110,9 +114,12 @@ image, configuration and preserved-service guards remain unchanged.
Current local checks cover company/project authorization, independent VPS
subscriptions, key replacement, private-file permissions and TLS pin-before-send.
These are bounded tests, not fleet simulation. The owner deferred Worker006,
load and simulation. Production acceptance still needs the real VPS, both
DCTOUCH projects, real key import, cross-project denial and independent app
registration. No claim about 50/100-device load is made here.
load and simulation. Live acceptance imported the real administrator package, linked both DCTOUCH
projects and automatically created the second project host view. Independent
Robot2B clients were denied rovers, management and each other's subscriptions.
Reissue preserved the subscription while old credentials/access tokens lost API
access. Project/company authorization negatives remain source-level tests.
No claim about 50/100-device load is made here.
2026-09-30 source qualification: all 275 repository Node tests, TypeScript and UI
production build pass. The standalone `scripts/qualify-b2-foundation.mjs` runs all
@@ -120,3 +127,55 @@ production build pass. The standalone `scripts/qualify-b2-foundation.mjs` runs a
against temporary PostgreSQL WASM. It proves the automatic second-project host
view, secret-reference storage, audit redaction and cross-company/duplicate-link
rejection. This does not substitute for the NAS PostgreSQL16 acceptance.
## Accepted application receipts
Main releases r17/r18 installed automatically after qualification, journals395/396
at2026-09-30T15:03:33Z /15:08:25Z. r18 source
`880d260ccbfd2fa5da267fddbd738b859bc0b4c7`, artifactSHA
`efb1f20d4e59a88befe9897fe98524231b64169f5678ea61c7d38f5a8f650693`;
matching archive/backup and canonical terminal_success were checked via SMB.
No additional NAS command was required.
DCTOUCH links: `rovers` → NODE DC Mission Core; `robot2b` →
Robot2B — Moscow Trike Delivery. The host is one shared company connection,
visible in both projects. Robot2B Client is a separate manage integration for
robot2b only. One final credential is active; all acceptance keys are revoked.
The real rover stays in rovers, Robot2B currently has no trackers. The old pilot
entry is not migrated or confused with that rover.
r16 failed to build Core and rolled back successfully. Root workspace install
did not expose the missing dependency in Core's standalone package-lock. r17
fixes that lock and qualifies the exact production npm context inside the
existing device-install CI stage. The separate r15 Gitea artifact-finalization
error and permanent build-output capture remain open CI follow-ups.
## UX correction after live operator review, 2026-09-30
The r18 functional checks did not establish usability. The next source revision
uses the Design Guidelines ResourceList/ResourceRow and existing settings window:
VPS → contour → applications → application keys. Project assignment is a separate
named relation on the contour. New-object forms appear only after the contextual
plus; revoked keys and applications with only revoked credentials are collapsed.
No duplicate refresh/back controls remain inside host monitoring; Back is a main
window utility beside Refresh. Switching project preserves the open section and
clears its selected object; late responses from the previous project are ignored.
The project inventory reads linked VPS contours through the B2 backend, alongside
the legacy Core registry. It releases its DB transaction before network requests,
checks the remote host identity, masks identifiers and reports each unreachable
host explicitly. A registered/enabled B2 is not labelled online without telemetry.
API availability and hardware metrics are separate: hardware metrics are currently
not connected for the standalone ARNavi service. Full command/SIM/firmware parity
remains open; registration in the list does not imply that parity.
Legacy device and host archive/restore are explicit modes of the existing
`device.update` and `infrastructure_host.ensure` command contracts. They retain
identity, history, bindings and secrets, use existing project capability checks
and audited/idempotent receipts, and require no schema or runner change. Device
archival refuses a live session. The UI exposes Archive and Restore; suspended
records stay out of default lists. No physical tracker operation is sent.
Local validation: 282 Node tests; TypeScript/build; 27 CI contract tests. Production
acceptance and the actual cleanup are recorded separately after the main pipeline
accepts the new release; these source checks alone do not prove deployment.
+90
View File
@@ -0,0 +1,90 @@
# ARNavi VPS: установка и подключение из Device Core
## Пользовательский путь
«Инфраструктура → VPS и хосты → +» открывает один диалог с выбором
поддерживаемого продукта и двумя последовательными блоками по всей ширине. Сейчас поддерживается ARNavi VPS.
1. Скачать установщик 0.2.3, перенести на новый Ubuntu Server 24.04 LTS x86-64.
2. В терминале **этого VPS** выполнить
`sudo python3 nodedc-arnavi-vps-0.2.3.pyz --device-core`.
Установщик запрашивает публичный IP/домен. Требуются 19443/TCP для API и
9922/TCP для трекеров на VPS; это не порты Synology.
3. В том же терминале выполнить
`sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection`.
Это чтение уже созданного закрытого JSON подключения, а не выпуск ещё одного ключа.
4. Вставить JSON или загрузить его файлом во второй блок Device Core,
указать название и нажать «Подключить VPS».
Сервер проверяет полномочия пользователя, TLS fingerprint, identity VPS и
доступ администратора **до** создания записи. Ключ отдельного приложения
не подходит для регистрации VPS. Повторное подключение того же сервера в
том же проекте использует существующую запись. Секрет сохраняется только
в закрытом хранилище Core, не в журнале аудита.
Установщик в режиме `--device-core` создаёт администратора без фиктивного
Mission Core и без заранее выдуманных контуров. Контуры связываются с уже
существующими проектами Device Core через настройки VPS. Существующий VPS
с прямой привязкой Mission Core этот режим менять отказывается: для него
нужен ранее экспортированный ключ администратора, не повторная установка.
## Ключи приложений
Настройки VPS → Контуры → нужный проект → Приложения и ключи.
Выпущенный JSON появляется внутри соответствующей строки ключа. Его нужно
импортировать в приложение, реализующее ARNavi API v2; он содержит endpoint,
TLS fingerprint и OAuth client credentials. Создание ключа само по себе не
подключает и не запускает другое приложение. Для отдельного приложения
создаётся отдельная интеграция в том же контуре.
Полный секрет доступен один раз. После скрытия/закрытия остаётся `client_id`
для сверки с сохранённым JSON, состояние и отзыв. Перевыпуск явно предупреждает
об отключении предыдущего ключа. Отозванные ключи доступны в истории.
Строка прямой привязки Mission Core v1 раскрывает её тип и ID; это не OAuth
credential и кнопка отзыва ключа v2 не должна притворяться её отключением.
## Инфраструктурный реестр
Для подключённого ARNavi VPS строка содержит настройки, круглую кнопку
мониторинга и раскрытие сведений. «В архив» обратимо скрывает локальную запись,
не удаляет VPS. Ручные действия «Адрес», «Развёртывание», «Сервис» оставлены
для общего инфраструктурного реестра, но не предлагаются в обычном ARNavi
сценарии. Они регистрируют метаданные, не устанавливают ПО: сервис требует
записи развёртывания именно выбранного хоста.
## Происхождение скачиваемого файла
Исходный сервер остаётся в отдельном репозитории
`SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS`, commit
`973e994f02176d438e8ff42f17baccc5fddb6184`. Device Core раздаёт только
неизменяемый официальный установщик из `public/installers`.
Метаданные в `src/b2/installer-release.json`; тест проверяет размер и SHA-256.
Сборка: `scripts/build_vps_host.py` отдельного VPS-репозитория с закреплённым
Hydra 26.2.0 archive. Две сборки дали одинаковый SHA-256:
`0d52c38d0e8afd7c1d72bb59e01d20328f8ac2cd8bb2abfd50f3d265db4bcaf4`.
Размер 16126822 байт, ниже лимита одного файла канонического deploy artifact.
Для обновления скачать/собрать новый проверенный релиз в VPS-репозитории,
опубликовать его commit, заменить asset и metadata вместе и пройти CI.
Нельзя редактировать содержимое PYZ в Device Core или переписывать старый релиз.
307 серверных теста покрывают пустое состояние, отдельный bootstrap,
изоляцию контуров, отказ смены режима и прежнюю привязку. Полная установка
0.2.3 на чистую Ubuntu в этой задаче **не выполнялась**. Действующий VPS
обновляется отдельно штатным plan/apply с сохранением identity и данных. Прохождение тестов не является актом приёмки новой машины.
## Компактные действия и удаление приложения
Плюс добавления приложения находится в строке раскрытого контура. В раскрытой
строке приложения: глаз (история отозванных ключей по умолчанию включена), плюс
(выпуск/перевыпуск), корзина (удаление с подтверждением). JSON ключа остаётся
внутри своей строки. Удаление отзывает все ключи и убирает grants/subscriptions
приложения на VPS. Устройства, данные и остальные приложения сохраняются.
Tombstone и audit предотвращают позднее восстановление старым запросом.
Host-admin и прежняя привязка Mission Core v1 защищены от этой операции.
Вкладка «Сервер» — управляющее подключение Device Core к VPS. «Обновить доступ»
импортирует новый JSON управляющего ключа после его перевыпуска на VPS.
Работающее подключение не требует повторного импорта. Это отдельно от ключей
приложений внутри контуров; обновление доступа не устанавливает ПО на сервер.
+46
View File
@@ -0,0 +1,46 @@
# Device Core: UI and UX contract
Device Core remains a separate application with its own companies, projects,
device registry, infrastructure, access rules and management functions. Mission
Core is the reference for interaction and presentation, not its domain model.
The existing home video and media configuration are preserved.
## Components
Consume the pinned NODEDC_DESIGN_GUIDELINE packages. Use ResourceRow for
registries, FeatureSettingsWindow for entity settings, SettingsCard for coherent
forms, and canonical controls and status indicators. Domain wrappers only arrange
these exports; they must not reproduce their visual styles. Avoid nested canvas
surfaces. Keep refresh beside close in the window header. Expand related items
in place instead of replacing the settings page with a back-navigation stack.
## VPS and projects
Existing Device Core projects are the list shown under a VPS. Connecting a
project requests a contour on that VPS using a stable project-derived identity,
then saves the link. Retries reuse that identity. No second project registry is
created. Explicit linking is available for a pre-existing remote contour.
Applications and their keys expand under their project. Creating an application
requires its human-readable name only. Device Core generates its technical ID;
VPS generates the credential. A lost response retains the same creation request
ID in the open form. The status refresh exposes partially completed issuance;
use explicit reissue when a one-time secret was lost. Key IDs are public IDs,
never secrets. Issued means a credential exists, not that the client is online.
Legacy Mission Core access is visible as a compatible connection.
## Acceptance
- Check all five application sections and their empty, populated and error states.
- Verify project switches retain the selected section while clearing entity state.
- Verify project, host, contour and credential isolation with unauthorized actors.
- Verify inline expansion, keyboard focus, Escape, top refresh and narrow layouts.
- Verify the existing home video/media survives releases.
- Full B2 command/settings parity remains a distinct domain integration task;
a UI release or successful deployment must not be recorded as its completion.
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.
+42
View File
@@ -0,0 +1,42 @@
# Device Core · Mission Core visual reference
Reference inspected in the running Mission Core on 2026-09-30: environment
settings; VPS settings; B2 identity, connection, commands, firmware and every
profile section. The actual application is authoritative for appearance; its
rover domain is not imported into Device Core.
The shared `appearance: "mission"` profile lives in Design Guideline/ui-core.
Device Core applies it on documentElement so portals inherit it. Existing Window,
FeatureSettingsWindow, SettingsCard, ResourceRow, Select, Button and StatusBadge
remain the component source. No application-local replica of the modal is added.
Reference measurements in dark mode: modal rgba(15,15,17,.97), radius28px,
plain avatar, selected navigation rgba(247,248,244,.14), control height46px,
settings-card padding16px, status dot6.72px. The material rim and gradient are
removed from this opt-in profile. Light mode keeps the same neutral hierarchy.
Other applications retain their previous appearance unless opting in.
| Surface | Device Core behavior |
| --- | --- |
| B2 inventory | terminal and gear at right; no redundant registered badge |
| B2 settings | persistent left navigation, identity, connection, commands, firmware,86parameters |
| VPS settings | same window; project contours expand inline; refresh at top |
| Keys | application belongs to expanded project contour; server generates identity |
| Project switch | retained active application section; no foreign project device window |
| Product model | company/project permissions remain Device Core's |
| Overview | existing yellow video retained |
Network settings go through the VPS product API documented in the server repo's
TRACKER_SETTINGS_API.md. The backend checks capability, linked project/contour and
server identity. Unknown/private configuration records and recovery endpoint are
preserved. Saving a portable profile is separate from applying it to a tracker.
The web app has no connection to the operator's local USB. USB provisioning stays
in local Mission Core; new network-reachable devices support initial config read
with their installed firmware and configuration password. Firmware controls match
the reference archive/import/download scope; no network flashing is advertised.
Validation: Device Core TypeScript/production build,286server/application tests,
15B2permission/transport tests; VPS298tests; Mission Core71compatibility tests.
Live deployment and UI acceptance are recorded in Ops MISSIONCOR-86 after release;
these local results are not a production acceptance claim.
+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
закрывают настройки целиком. Переключение вкладок сохраняет выбор команды,
фильтр и идентификатор незавершённой отправки; возврат обновляет журнал.
Кнопка обновления в шапке на вкладке команд обновляет журнал и состояние трекера.
+19 -1
View File
@@ -7,8 +7,10 @@ import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import time
@@ -30,9 +32,11 @@ def run(args, cwd, capture=False, capture_errors=False):
).stdout
def install_dependencies(cwd):
def install_dependencies(cwd, *, production=False):
"""Retry only explicit transport failures in a disposable npm ci checkout."""
command = ["npm", "ci", "--ignore-scripts", "--no-audit", "--no-fund"]
if production:
command.append("--omit=dev")
transient = {"ECONNRESET", "ETIMEDOUT", "EAI_AGAIN"}
for attempt in range(1, 4):
try:
@@ -51,6 +55,17 @@ def install_dependencies(cwd):
return
def qualify_core_runtime(root):
"""Exercise the standalone lock used by Docker, outside npm workspaces."""
with tempfile.TemporaryDirectory(prefix="device-core-runtime-") as temporary:
target = Path(temporary)
for name in ("package.json", "package-lock.json"):
shutil.copyfile(root / "services/device-control-core" / name, target / name)
install_dependencies(target, production=True)
run(["node", "--input-type=module", "-e",
"await import('oauth4webapi'); await import('pg');"], target)
def read_lock(root):
lock = json.loads((root / "infra/ci/sources.lock.json").read_text())
if lock.get("schema") != "nodedc.device-core.ci-sources.v1":
@@ -151,6 +166,9 @@ def qualify(root, commit, lock, report):
print("ci_step=" + name, flush=True)
if name in ("design-install", "device-install"):
install_dependencies(cwd)
if name == "device-install":
print("ci_dependency_check=core-standalone-runtime", flush=True)
qualify_core_runtime(root)
else:
run(command, cwd)
completed.append(name)
+2 -2
View File
@@ -5,7 +5,7 @@
"dependencies": {
"NODEDC_DESIGN_GUIDELINE": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"commit": "1b63366d2e7a911e18a293d30cddb0c95e0ba653"
"commit": "06cb8ad4cd193ae1b4b1ac40a513fd642e12b878"
},
"NODEDC_LAUNCHER": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
@@ -13,7 +13,7 @@
},
"platform": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
"commit": "39a2239563de686d8a854627cae15339f1f2a4d9"
"commit": "27c155276a703dd4fd39385011fc5e3f86afcae4"
}
}
}
+32
View File
@@ -119,6 +119,38 @@ class QualificationTests(unittest.TestCase):
self.assertEqual(execute.call_args.args[0], ["npm", "ci", "--ignore-scripts", "--no-audit", "--no-fund"])
pause.assert_called_once_with(5)
def test_core_runtime_uses_its_own_lock_outside_the_workspace(self):
source = self.root / "services/device-control-core"
source.mkdir(parents=True)
for name, value in (("package.json", '{"name":"core"}'),
("package-lock.json", '{"name":"standalone-lock"}')):
(source / name).write_text(value)
(self.root / "package-lock.json").write_text('{"name":"workspace-lock"}')
temporary_paths = []
def inspect_install(path, *, production):
self.assertTrue(production)
self.assertFalse(path.is_relative_to(self.root))
self.assertEqual((path / "package-lock.json").read_text(), '{"name":"standalone-lock"}')
self.assertEqual(sorted(p.name for p in path.iterdir()), ["package-lock.json", "package.json"])
temporary_paths.append(path)
with mock.patch.object(CI, "install_dependencies", side_effect=inspect_install), \
mock.patch.object(CI, "run") as execute:
CI.qualify_core_runtime(self.root)
self.assertIn("await import('oauth4webapi')", execute.call_args.args[0][-1])
self.assertFalse(temporary_paths[0].exists())
def test_core_runtime_lock_failure_stops_before_imports(self):
source = self.root / "services/device-control-core"
source.mkdir(parents=True)
for name in ("package.json", "package-lock.json"):
(source / name).write_text('{}')
failure = subprocess.CalledProcessError(1, "npm", output="npm error code EUSAGE\n")
with mock.patch.object(CI, "install_dependencies", side_effect=failure), \
mock.patch.object(CI, "run") as execute:
with self.assertRaises(subprocess.CalledProcessError):
CI.qualify_core_runtime(self.root)
execute.assert_not_called()
def test_permanent_mixed_and_unclassified_install_failures_never_retry(self):
for output in ("npm error code EINTEGRITY\n", "npm error code E401\n",
"npm error code EUSAGE\n", "download ECONNRESET in explanatory text\n",
@@ -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 });
}
+10
View File
@@ -8,12 +8,22 @@
"name": "@nodedc/device-control-core",
"version": "0.1.0",
"dependencies": {
"oauth4webapi": "3.8.8",
"pg": "8.22.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/oauth4webapi": {
"version": "3.8.8",
"resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz",
"integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/pg": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
+1 -1
View File
@@ -211,7 +211,7 @@ export function createControlCoreApp({
const requestId = String(request.headers["idempotency-key"] || "");
if (!/^[a-f0-9]{32}$/.test(requestId)) throw new TypeError("b2_request_id_invalid");
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);
return writeJson(response, 200, { ok: true, result });
}
@@ -149,7 +149,9 @@ export function createB2Client(input, { fetchImpl } = {}) {
const value = await res.json().catch(() => null);
if (!res.ok) {
if (res.status === 401 || res.status === 403) { token = null; throw b2Error('b2_access_denied', 403); }
if (res.status === 409 && ['settings_revision_changed', 'settings_initial_read_required', 'settings_sim_observation_required'].includes(value?.error)) throw b2Error('b2_' + value.error, 409);
if (res.status === 409) throw b2Error('b2_conflict', 409);
if (res.status === 400) throw b2Error('b2_request_invalid', 400);
throw b2Error('b2_host_request_failed', 502);
}
if (!value || typeof value !== 'object') throw b2Error('b2_response_invalid', 502);
@@ -22,6 +22,10 @@ export class B2Infrastructure {
this.pool = pool; this.secrets = secrets; this.clientFactory = clientFactory;
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) {
// Private file refs are immutable. Re-importing/replacing a key creates a
// new ref and therefore cannot reuse the previous OAuth token cache.
@@ -32,7 +36,200 @@ export class B2Infrastructure {
this.clients.set(source.secret_ref, client);
return client;
}
async verifyConnection(input) {
let value;
try { value = typeof input === 'string' ? JSON.parse(input) : input; }
catch { throw b2Error('b2_connection_invalid'); }
const pkg = connectionPackage(value);
const remote = this.clientFactory(pkg);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const status = await remote.call(pkg.authority === 'host' ? '/v2/management' : '/v2/contours');
if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
return pkg;
}
async saveSource(db, project, pkg) {
const secret = await this.secrets.save(pkg);
const saved = (await db.query(`insert into device_b2_hosts
(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
values($1,$2,$3,$4,$5,$6,$7,$8)
on conflict(owner_scope_id,remote_host_id) do update set
secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now()
where device_b2_hosts.integration_id=excluded.integration_id
and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint
and device_b2_hosts.authority=excluded.authority returning id`,
[randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0];
if (!saved) throw b2Error('b2_connection_identity_conflict', 409);
return saved;
}
async registerHost(actor, input, requestId) {
fields(input, ['connection', 'name']);
const projectId = ref(input.projectRef, 'project');
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
const db = await this.pool.connect();
try {
await db.query('begin');
const project = await findProjectWithCapability(db, actor, projectId, 'infrastructure.manage');
assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
await findProjectWithCapability(db, actor, projectId, 'credential.manage');
// A rejected key never leaves an empty host in the user's registry.
const pkg = await this.verifyConnection(input.connection);
if (pkg.authority !== 'host') throw b2Error('b2_host_management_required', 403);
await db.query('select pg_advisory_xact_lock(hashtextextended($1,0))', [project.owner_scope_id + ':' + pkg.host_id]);
const saved = await this.saveSource(db, project, pkg);
const existing = (await db.query(`select h.host_key from device_b2_host_views v
join device_infrastructure_hosts h on h.id=v.host_id
where v.source_id=$1 and v.project_id=$2`, [saved.id, projectId])).rows[0];
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: input.projectRef, hostKey: existing?.host_key || `b2-${saved.id}`,
displayName: input.name.trim(), providerRef: null, externalRef: pkg.host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
const hostRef = registered.host.hostRef;
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [ref(hostRef, 'host'), projectId, project.owner_scope_id, saved.id]);
await db.query(`insert into device_audit_events(id,event_type,actor_ref,payload,project_id)
values($1,$2,$3,$4::jsonb,$5)`, [randomUUID(), 'b2.register-host', actor.userRef,
JSON.stringify({ projectRef: input.projectRef, hostRef, requestId }), projectId]);
await db.query('commit');
return { connected: true, hostRef, endpoint: pkg.endpoint, authority: pkg.authority };
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
}
async inventory(actor, input) {
fields(input, []);
const projectId = ref(input.projectRef, 'project');
const db = await this.pool.connect();
let sources;
try {
await db.query('begin');
await findProjectWithCapability(db, actor, projectId, 'inventory.read');
sources = (await db.query(`select s.*, v.host_id, h.display_name,
coalesce((select json_agg(l.contour_id order by l.contour_id) from device_b2_contour_links l
where l.source_id=s.id and l.project_id=v.project_id), '[]'::json) as contour_ids
from device_b2_hosts s join device_b2_host_views v on v.source_id=s.id
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
where v.project_id=$1 and h.lifecycle_state='active'`, [projectId])).rows;
await db.query('commit');
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
// Release the database transaction before waiting for any external host.
const results = await Promise.all(sources.map(async (source) => {
const host = { hostRef: `host:${source.host_id}`, name: source.display_name,
endpoint: source.endpoint, contours: source.contour_ids.length };
try {
const remote = await this.clientFor(source);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
const items = [];
for (const contourId of source.contour_ids) {
const snapshot = await remote.call(`/v2/contours/${opaque(contourId)}/devices`);
items.push(...snapshot.items.map((device) => ({ id: device.id, name: device.name, number: device.number,
active: device.active, identifier: { masked: '…' + String(device.imei).slice(-5) },
contourId, hostRef: host.hostRef, hostName: host.name })));
}
return { host: { ...host, reachable: true, checkedAt: new Date().toISOString(), devices: items.length }, items };
} catch {
return { host: { ...host, reachable: false, checkedAt: new Date().toISOString(), devices: null }, items: [] };
}
}));
return { items: results.flatMap((result) => result.items), hosts: results.map((result) => result.host) };
}
async tracker(actor, input) {
fields(input, ['contourId', 'deviceId', 'request']);
const projectId = ref(input.projectRef, 'project'), hostId = ref(input.hostRef, 'host');
const contourId = opaque(input.contourId), deviceId = opaque(input.deviceId);
const request = input.request;
const permissions = {
state: 'configuration.read', journal: 'audit.read', attempts: 'audit.read',
'firmware-download': 'configuration.read', 'firmware-upload': 'configuration.manage',
save: 'configuration.manage', 'profile-save': 'configuration.manage',
read: 'command.dispatch', apply: 'configuration.manage', command: 'command.dispatch', cancel: 'command.dispatch',
};
if (!request || typeof request !== 'object' || !permissions[request.action]) throw b2Error('b2_request_invalid');
const db = await this.pool.connect();
let source;
try {
await db.query('begin');
await findProjectWithCapability(db, actor, projectId, permissions[request.action]);
if (request.action === 'apply') await findProjectWithCapability(db, actor, projectId, 'command.dispatch');
source = (await db.query(`select s.* from device_b2_hosts s
join device_b2_host_views v on v.source_id=s.id
join device_b2_contour_links l on l.source_id=s.id and l.project_id=v.project_id
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
where v.host_id=$1 and v.project_id=$2 and l.contour_id=$3 and h.lifecycle_state='active'`,
[hostId, projectId, contourId])).rows[0];
if (!source) throw b2Error('b2_access_denied', 403);
await db.query('commit');
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
const remote = await this.clientFor(source);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
// VPS checks the device's actual contour as well; a forged device ID cannot
// borrow the host administrator credential from another project.
return remote.call(`/v2/contours/${contourId}/devices/${deviceId}/settings`, request);
}
async enrollmentOptions(actor, input) {
fields(input, []);
const projectId = ref(input.projectRef, 'project');
const db = await this.pool.connect();
let sources;
try {
await db.query('begin');
await findProjectWithCapability(db, actor, projectId, 'device.enroll');
sources = (await db.query(`select s.*, v.host_id, h.display_name,
coalesce((select json_agg(l.contour_id order by l.contour_id) from device_b2_contour_links l
where l.source_id=s.id and l.project_id=v.project_id), '[]'::json) as contour_ids
from device_b2_hosts s join device_b2_host_views v on v.source_id=s.id
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
where v.project_id=$1 and h.lifecycle_state='active'`, [projectId])).rows;
await db.query('commit');
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
return { hosts: await Promise.all(sources.map(async source => {
const host = { hostRef: `host:${source.host_id}`, name: source.display_name };
try {
const remote = await this.clientFor(source);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
const contours = (await remote.call('/v2/contours')).items
.filter(item => source.contour_ids.includes(item.id) && item.access === 'manage')
.map(({ id, name }) => ({ id, name }));
return { ...host, reachable: true, contours };
} catch { return { ...host, reachable: false, contours: [] }; }
})) };
}
async enrollment(actor, input) {
fields(input, ['contourId', 'request']);
const projectId = ref(input.projectRef, 'project'), hostId = ref(input.hostRef, 'host');
const contourId = opaque(input.contourId), request = input.request;
if (!request || typeof request !== 'object' || Array.isArray(request)
|| !['catalog', 'inspect', 'register'].includes(request.action)) throw b2Error('b2_request_invalid');
const db = await this.pool.connect();
let source;
try {
await db.query('begin');
await findProjectWithCapability(db, actor, projectId, 'device.enroll');
if (request.action === 'register') await findProjectWithCapability(db, actor, projectId, 'device.claim');
source = (await db.query(`select s.* from device_b2_hosts s
join device_b2_host_views v on v.source_id=s.id
join device_b2_contour_links l on l.source_id=s.id and l.project_id=v.project_id
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
where v.host_id=$1 and v.project_id=$2 and l.contour_id=$3 and h.lifecycle_state='active'`,
[hostId, projectId, contourId])).rows[0];
if (!source) throw b2Error('b2_access_denied', 403);
await db.query('commit');
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
const remote = await this.clientFor(source);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
// Only the selected project's linked contour may receive identity/configuration.
return remote.call(`/v2/contours/${contourId}/enrollment`, request);
}
async execute(actor, input, requestId) {
if (input.action === 'register-host') return this.registerHost(actor, input, requestId);
if (input.action === 'inventory') return this.inventory(actor, input);
if (input.action === 'tracker') return this.tracker(actor, input);
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 hostId = ref(input.hostRef, 'host');
const action = input.action;
@@ -44,7 +241,7 @@ export class B2Infrastructure {
// Host management can affect all projects of the company. A project-only
// grant must not turn into company-wide administration.
if (action !== 'devices') assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
if (['connect', 'key-issue', 'key-revoke'].includes(action)) {
if (['connect', 'key-issue', 'key-revoke', 'application-connect', 'application-delete'].includes(action)) {
await findProjectWithCapability(db, actor, projectId, 'credential.manage');
}
const host = (await db.query('select id,host_key,display_name,provider_ref from device_infrastructure_hosts where id=$1 and project_id=$2 and lifecycle_state <> $3 for share',
@@ -64,16 +261,7 @@ export class B2Infrastructure {
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const status = pkg.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const secret = await this.secrets.save(pkg);
const saved = (await db.query(`insert into device_b2_hosts
(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
values($1,$2,$3,$4,$5,$6,$7,$8)
on conflict(owner_scope_id,remote_host_id) do update set
secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now()
where device_b2_hosts.integration_id=excluded.integration_id
and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint
and device_b2_hosts.authority=excluded.authority returning id`,
[randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0];
const saved = await this.saveSource(db, project, pkg);
if (!saved) throw b2Error('b2_connection_identity_conflict', 409);
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [hostId, projectId, project.owner_scope_id, saved.id]);
@@ -88,20 +276,41 @@ export class B2Infrastructure {
fields(input, []);
const value = source.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
result = { connected: true, endpoint: source.endpoint, authority: source.authority,
sharedProjects: await this.supportsSharedProjects(db),
contours: value.contours || value.items, applications: value.applications || [],
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
} else if (action === 'link') {
fields(input, ['contourId', 'targetProjectRef']);
} else if (['link', 'unlink', 'project-connect', 'contour-connect'].includes(action)) {
fields(input, action === 'contour-connect' ? ['name', 'targetProjectRef'] : action === 'project-connect' ? ['targetProjectRef'] : ['contourId', 'targetProjectRef']);
const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
const contour = opaque(input.contourId);
let contour;
if (action === 'unlink') {
contour = opaque(input.contourId);
await db.query('delete from device_b2_contour_links where source_id=$1 and contour_id=$2 and project_id=$3', [source.id, contour, targetId]);
result = { linked: false, contourId: contour, projectRef: `project:${targetId}` };
} else {
if (action === 'contour-connect') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
// Retry a lost response without creating another remote contour.
contour = (await remote.call('/v2/management/contours', { key: 'dc-' + requestId, name: input.name.trim() })).id;
} else if (action === 'project-connect') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
const linked = links.filter((link) => link.project_id === targetId);
if (linked.length > 1) throw b2Error('b2_conflict', 409);
// Stable project identity makes a retry recover the same contour.
contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', {
key: 'dc-' + targetId, name: target.name,
})).id;
} else contour = opaque(input.contourId);
const permitted = await remote.call('/v2/contours');
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
const current = links.find((link) => link.contour_id === contour);
if (current && current.project_id !== targetId) throw b2Error('b2_contour_already_linked', 409);
if (links.some((link) => link.contour_id === contour && link.project_id !== targetId)
&& !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)
values($1,$2,$3,$4,$5) on conflict(source_id,contour_id) do nothing`,
values($1,$2,$3,$4,$5) on conflict do nothing`,
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
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];
@@ -117,6 +326,7 @@ export class B2Infrastructure {
}
}
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
}
} else if (action === 'devices') {
fields(input, []);
const contours = links.filter((link) => link.project_id === projectId);
@@ -137,6 +347,24 @@ export class B2Infrastructure {
result = await remote.call('/v2/management/applications', {
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
});
} else if (action === 'application-connect') {
fields(input, ['name', 'contourId', 'access']);
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
const contour = opaque(input.contourId);
const access = input.access ?? 'manage';
if (!['read', 'control', 'manage'].includes(access)) throw b2Error('b2_request_invalid');
if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
const app = await remote.call('/v2/management/applications', {
key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: access },
});
// The VPS reserves issuance before returning a one-time secret. If
// the response is lost, status exposes the app for explicit reissue.
result = { id: app.id, connection: await remote.call('/v2/management/credentials', {
integration_id: app.id, replace: false, request_id: requestId,
}) };
} else if (action === 'application-delete') {
fields(input, ['integrationId']);
result = await remote.call('/v2/management/applications/delete', { integration_id: opaque(input.integrationId) });
} else if (action === 'key-issue') {
fields(input, ['integrationId', 'replace']);
if (typeof input.replace !== 'boolean') throw b2Error('b2_replace_invalid');
@@ -44,6 +44,16 @@ export function normalizeLifecycleManagementCommand(kind, input) {
});
}
if (kind === "device.update" && Object.prototype.hasOwnProperty.call(input, "archived")) {
assertAllowedKeys(input, ["projectRef", "deviceRef", "archived"]);
if (typeof input.archived !== "boolean") throw new TypeError("device_archive_state_invalid");
return Object.freeze({
projectId: normalizeEntityRef(input.projectRef, "project"),
deviceId: normalizeEntityRef(input.deviceRef, "device"),
archived: input.archived,
});
}
if (kind === "device.update") {
assertAllowedKeys(input, [
"projectRef",
@@ -91,7 +91,24 @@ export async function authorizeLifecycleManagementReplay(
}
}
async function archiveDevice(client, actor, command) {
const project = await findProjectWithCapability(client, actor, command.projectId, "project.manage");
const current = await findDeviceForUpdate(client, command.deviceId);
if (current.project_id !== project.id) throw domainError("device_update_project_mismatch", 409);
// Archive is a reversible registry operation. It never closes a live channel.
if (!["claimed", "suspended"].includes(current.lifecycle_state)) throw domainError("device_archive_lifecycle_blocked", 409);
const sessions = await client.query(`select exists(select 1 from device_sessions where device_id=$1
and lifecycle_state in ('connecting','online','closing')) as active`, [current.id]);
if (sessions.rows[0]?.active) throw domainError("device_archive_active_session", 409);
const state = command.archived ? "suspended" : "claimed";
await client.query('update device_instances set lifecycle_state=$3, updated_at=now() where id=$1 and project_id=$2', [current.id, project.id, state]);
await addAudit(client, { eventType: command.archived ? "device.archived" : "device.restored", actorRef: actor.userRef,
projectId: project.id, deviceId: current.id, payload: { deviceRef: `device:${current.id}`, lifecycleState: state } });
return { archived: command.archived };
}
async function updateDevice(client, actor, command) {
if (typeof command.archived === "boolean") return archiveDevice(client, actor, command);
const project = await findProjectWithCapability(
client,
actor,
@@ -81,6 +81,16 @@ export function normalizeOntologyManagementCommand(kind, input) {
});
}
if (kind === "infrastructure_host.ensure" && Object.prototype.hasOwnProperty.call(input, "archived")) {
assertAllowedKeys(input, ["projectRef", "hostRef", "archived"]);
if (typeof input.archived !== "boolean") throw new TypeError("device_archive_state_invalid");
return Object.freeze({
projectId: normalizeEntityRef(input.projectRef, "project"),
hostId: normalizeEntityRef(input.hostRef, "host"),
archived: input.archived,
});
}
if (kind === "infrastructure_host.ensure") {
assertAllowedKeys(input, [
"projectRef", "hostKey", "displayName", "providerRef", "externalRef",
@@ -201,7 +201,18 @@ async function closeAssetBinding(client, actor, project, command) {
return { closed: true, assetBinding: assetBindingView(row) };
}
async function archiveHost(client, actor, project, command) {
const result = await client.query(`update device_infrastructure_hosts set lifecycle_state=$3, updated_at=now()
where id=$1 and project_id=$2 and lifecycle_state in ('active','suspended') returning *`,
[command.hostId, project.id, command.archived ? 'suspended' : 'active']);
const row = requireRow(result, "device_host_not_archivable", 409);
await addAudit(client, { actor, project, eventType: command.archived ? 'infrastructure_host.archived' : 'infrastructure_host.restored',
payload: { hostRef: `host:${row.id}`, lifecycleState: row.lifecycle_state } });
return { archived: command.archived };
}
async function ensureHost(client, actor, project, command) {
if (typeof command.archived === "boolean") return archiveHost(client, actor, project, command);
const result = await client.query(
`insert into device_infrastructure_hosts (
id, owner_scope_id, project_id, host_key, display_name, provider_ref,
@@ -0,0 +1,50 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { normalizeDeviceManagementCommand } from '../src/management-command.mjs';
import { applyLifecycleManagementCommand, authorizeLifecycleManagementReplay } from '../src/lifecycle-repository.mjs';
import { applyOntologyManagementCommand } from '../src/ontology-repository.mjs';
const projectId='11111111-1111-4111-8111-111111111111', entityId='22222222-2222-4222-8222-222222222222';
const actor={ userRef:'user:operator', hubRole:'owner', groupRefs:[], ownerScopes:[] };
function db({role='owner', entityProject=projectId, active=false}={}) {
const writes=[];
return { writes, async query(sql, values) {
if (sql.includes('from device_projects')) return {rows:[{id:projectId,owner_scope_id:'owner',scope_kind:'company',owner_ref:'company:test',lifecycle_state:'active',owner_lifecycle_state:'active'}]};
if (sql.includes('from device_project_grants')) return {rows:[{id:'grant',principal_kind:'user',principal_ref:actor.userRef,project_role:role,capability_allow:[],capability_deny:[],lifecycle_state:'active'}]};
if (sql.includes('from device_instances')) return {rows:[{id:entityId,project_id:entityProject,lifecycle_state:'claimed'}]};
if (sql.includes('from device_sessions')) return {rows:[{active}]};
if (sql.startsWith('update device_infrastructure_hosts')) { writes.push({sql,values}); return {rows:entityProject === projectId ? [{id:entityId,lifecycle_state:values[2]}] : []}; }
if (sql.startsWith('update') || sql.includes('insert into device_audit_events')) {writes.push({sql,values});return {rows:[]};}
throw Error('Unexpected query '+sql);
}};
}
for (const [kind, ref, apply] of [['device.update','deviceRef',applyLifecycleManagementCommand],['infrastructure_host.ensure','hostRef',applyOntologyManagementCommand]]) {
test(`${kind} archive and restore preserve identity and private bindings`,async()=>{
for (const archived of [true,false]) {
const command=normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived});
const client=db(); const result=await apply(client,{actor,commandKind:kind,command});
assert.equal(result.archived,archived);
const update=client.writes.find((write)=>write.sql.startsWith('update'));
assert.match(update.sql,/where id\s*=\s*\$1 and project_id\s*=\s*\$2/);
assert.equal(update.sql.includes('management_credential_ref'),false);
assert.equal(update.sql.includes('display_name'),false);
assert.equal(update.values[2],archived?'suspended':ref==='hostRef'?'active':'claimed');
assert.ok(client.writes.some((write)=>write.sql.includes('device_audit_events')));
}
});
test(`${kind} rejects unauthorized and cross-project archive`,async()=>{
const command=normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:true});
for (const options of [{role:'viewer'},{entityProject:'different'}]) {
const client=db(options); await assert.rejects(apply(client,{actor,commandKind:kind,command}));
if (options.role) assert.equal(client.writes.length,0);
}
assert.throws(()=>normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:'true'}));
assert.throws(()=>normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:true,displayName:'unexpected'}));
});
}
test('archive cannot interrupt an active device and replay rechecks its project',async()=>{
const command=normalizeDeviceManagementCommand('device.update',{projectRef:`project:${projectId}`,deviceRef:`device:${entityId}`,archived:true});
const client=db({active:true});
await assert.rejects(applyLifecycleManagementCommand(client,{actor,commandKind:'device.update',command}),/device_archive_active_session/);
assert.equal(client.writes.length,0);
await assert.rejects(authorizeLifecycleManagementReplay(db({entityProject:'different'}),{actor,commandKind:'device.update',command}),/project_mismatch/);
});
@@ -19,12 +19,13 @@ const actor = { userRef: 'user:operator', hubRole: 'owner', groupRefs: [], owner
const source = { id: '55555555-5555-4555-8555-555555555555', owner_scope_id: ownerId,
remote_host_id: pkg.host_id, endpoint: pkg.endpoint, fingerprint: pkg.fingerprint,
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 db = { release() {}, async query(sql, values) {
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,
lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
name: 'Test project', lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
if (sql.includes('from device_project_grants')) return { rows: [{ id: 'grant', principal_kind: 'user', principal_ref: actor.userRef,
project_role: role, capability_allow: [], capability_deny: [], lifecycle_state: 'active' }] };
if (sql.includes('from device_infrastructure_hosts')) return { rows: [{ id: hostId }] };
@@ -156,3 +157,258 @@ test('TLS pin is verified before any HTTP credential reaches the peer', async ()
await rm(root, { recursive: true, force: true });
}
});
test('project inventory releases DB before networking and never exposes other projects or credentials', async () => {
const contour = 'c'.repeat(32); let released = false; const calls = [];
const repo = repository({ role: 'viewer' });
const db = await repo.pool.connect(); const original = db.query;
db.release = () => { released = true; };
db.query = async (sql, values) => {
if (sql.includes('from device_b2_hosts')) {
assert.match(sql, /v.project_id=\$1 and h.lifecycle_state='active'/);
assert.match(sql, /l.project_id=v.project_id/);
assert.deepEqual(values, [projectId]);
return { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [contour] }] };
}
return original(sql, values);
};
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
assert.equal(released, true); calls.push(path);
return path === '/v2/identity' ? { host_id: pkg.host_id } : { items: [{ id: 'device', imei: '123456789012345', number: 1, name: 'B2', active: true }] };
} }) });
const result = await service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, action: 'inventory' });
assert.deepEqual(calls, ['/v2/identity', `/v2/contours/${contour}/devices`]);
assert.equal(result.items[0].identifier.masked, '…12345');
assert.equal(result.hosts[0].reachable, true);
assert.equal(result.hosts[0].devices, 1);
const json = JSON.stringify(result);
for (const secret of [pkg.client_secret, source.secret_ref, '123456789012345', otherProject]) assert.equal(json.includes(secret), false);
assert.equal('online' in result.items[0], false);
});
test('unreachable or mismatched host is reported as unavailable, not an empty healthy fleet', async () => {
for (const fail of [false, true]) {
const repo = repository(); const db = await repo.pool.connect(); const original = db.query;
db.query = (sql, values) => sql.includes('from device_b2_hosts') ? { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [] }] } : original(sql, values);
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call() { if (fail) throw Error('contains-private-details'); return { host_id: 'wrong-host' }; } }) });
const result = await service.execute(actor, { projectRef: `project:${projectId}`, action: 'inventory' });
assert.equal(result.hosts[0].reachable, false); assert.equal(result.hosts[0].devices, null);
assert.deepEqual(result.items, []); assert.equal(JSON.stringify(result).includes('private-details'), false);
}
});
test('project connection generates stable contour identity and links it without user codes', async () => {
const repo = repository(); const calls = []; const contour = 'c'.repeat(32);
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
calls.push({ path, body });
return path === '/v2/management/contours' ? { id: contour } : { items: [{ id: contour }] };
} }) });
const result = await service.execute(actor, { action: 'project-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, targetProjectRef: `project:${projectId}` }, 'a'.repeat(32));
assert.equal(result.linked, true);
assert.equal(calls[0].body.key, 'dc-' + projectId);
assert.equal(calls[0].body.name, 'Test project');
assert.equal(repo.writes.filter((x) => x.sql.includes('device_b2_contour_links')).length, 1);
});
test('connecting an already linked project does not create another contour', async () => {
const contour = 'c'.repeat(32); const repo = repository({ links: [{ contour_id: contour, project_id: projectId }] });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
assert.equal(path, '/v2/contours'); return { items: [{ id: contour }] };
} }) });
const result = await service.execute(actor, { action: 'project-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}` }, 'a'.repeat(32));
assert.equal(result.contourId, contour);
});
test('application creation and issuance use one server-generated request identity', async () => {
const contour = 'c'.repeat(32); const repo = repository({ links: [{ contour_id: contour, project_id: projectId }] });
const calls = []; const requestId = 'd'.repeat(32); const app = 'e'.repeat(32);
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
calls.push({ path, body }); return path.endsWith('applications') ? { id: app } : { synthetic: true };
} }) });
const result = await service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Partner', contourId: contour }, requestId);
assert.equal(calls[0].body.key, 'app-' + requestId);
assert.equal(calls[1].body.request_id, requestId);
assert.equal(result.id, app);
assert.ok(result.connection);
assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false);
await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32), access: 'host' }, requestId), /b2_request_invalid/);
assert.equal(calls.length, 2);
});
test('host catalogue includes external unlinked contours without creating local projects', async () => {
const repo = repository();
const contours = [{ id: 'a'.repeat(32), key: 'external', name: 'External fleet' }];
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async () => ({ contours }) }) });
const result = await service.execute(actor, { action: 'status', projectRef: `project:${projectId}`, hostRef: `host:${hostId}` });
assert.deepEqual(result.contours, contours);
assert.deepEqual(result.links, []);
assert.equal(result.sharedProjects, true);
assert.deepEqual(repo.writes, []);
});
test('second project can share a contour after migration and old foundation fails explicitly', async () => {
for (const sharedProjects of [true, false]) {
const contour = 'c'.repeat(32);
const repo = repository({ sharedProjects, links: [{ contour_id: contour, project_id: otherProject }] });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async () => ({ items: [{ id: contour }] }) }) });
const result = service.execute(actor, { action: 'link', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, contourId: contour });
if (sharedProjects) {
assert.equal((await result).linked, true);
assert.equal(repo.writes.filter(item => item.sql.includes('device_b2_contour_links')).length, 1);
} else {
await assert.rejects(result, /b2_shared_projects_migration_required/);
assert.deepEqual(repo.writes, []);
}
}
});
test('new contour retries retain remote identity and authorize target before creation', async () => {
const contour = 'c'.repeat(32), calls = [], requestId = 'd'.repeat(32);
const repo = repository();
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async (path, body) => {
calls.push({ path, body }); return path.endsWith('/management/contours') ? { id: contour } : { items: [{ id: contour }] };
} }) });
const input = { action: 'contour-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'New fleet' };
assert.equal((await service.execute(actor, input, requestId)).contourId, contour);
assert.equal((await service.execute(actor, input, requestId)).contourId, contour);
assert.equal(calls[0].body.key, calls[2].body.key);
assert.equal(calls[0].body.key, 'dc-' + requestId);
});
test('tracker settings keep project and contour authority across remote calls', async () => {
const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = [];
const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect();
let released = false; const original = db.query;
db.release = () => { released = true; };
db.query = async (sql, values) => {
if (sql.includes('from device_b2_hosts')) {
assert.match(sql, /l.project_id=v.project_id/);
assert.match(sql, /h.lifecycle_state='active'/);
assert.deepEqual(values, [hostId, projectId, contour]);
return { rows: [source] };
}
return original(sql, values);
};
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
assert.equal(released, true); calls.push({path,body});
return path === '/v2/identity' ? {host_id:pkg.host_id} : {revision:1};
} }) });
const input = {action:'tracker',projectRef:`project:${projectId}`,hostRef:`host:${hostId}`,contourId:contour,deviceId:device,request:{action:'state'}};
assert.deepEqual(await service.execute({...actor,hubRole:'member'},input), {revision:1});
assert.equal(calls[1].path, `/v2/contours/${contour}/devices/${device}/settings`);
for (const action of ['save','apply','read','command','cancel','firmware-upload','profile-save']) {
await assert.rejects(service.execute({...actor,hubRole:'member'},{...input,request:{action}}));
}
assert.equal(calls.length,2);
db.query = async (sql,values) => sql.includes('from device_b2_hosts') ? {rows:[]} : original(sql,values);
await assert.rejects(service.execute(actor,input), /b2_access_denied/);
assert.equal(calls.length,2);
});
test('VPS onboarding rejects invalid or application-only credentials without creating a host', async () => {
for (const input of ['bad-json', JSON.stringify({ ...pkg, authority: 'contours' }), JSON.stringify(pkg)]) {
const repo = repository(); let secrets = 0;
const service = new B2Infrastructure({ pool: repo.pool,
secrets: { save: async () => { secrets += 1; return 'private-ref'; } },
clientFactory: () => ({ call: async (path) => path === '/v2/identity' ? { host_id: input === JSON.stringify(pkg) ? 'foreign-host' : pkg.host_id } : { items: [] } }) });
await assert.rejects(service.execute(actor, { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: input }, 'a'.repeat(32)));
assert.equal(secrets, 0); assert.deepEqual(repo.writes, []);
}
});
test('VPS onboarding reuses the project host and audits no credential material', async () => {
const queries = []; let existing = false;
const base = repository(); const db = await base.pool.connect(); const original = db.query.bind(db);
db.query = async (sql, values) => {
queries.push({ sql, values });
if (sql.includes('pg_advisory_xact_lock')) return { rows: [] };
if (sql.startsWith('insert into device_b2_hosts')) return { rows: [{ id: source.id }] };
if (sql.startsWith('select h.host_key')) return { rows: existing ? [{ host_key: 'b2-existing-project-view' }] : [] };
if (sql.startsWith('insert into device_infrastructure_hosts')) return { rows: [{ id: hostId, host_key: values[3],
display_name: values[4], project_id: projectId, owner_scope_id: ownerId, lifecycle_state: 'active', created: !existing }] };
if (sql.startsWith('insert into device_b2_host_views')) { existing = true; return { rows: [] }; }
return original(sql, values);
};
const service = new B2Infrastructure({ pool: base.pool, secrets: { save: async () => 'private-ref' },
clientFactory: () => ({ call: async () => ({ host_id: pkg.host_id }) }) });
const input = { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: JSON.stringify(pkg) };
const first = await service.execute(actor, input, 'a'.repeat(32));
const second = await service.execute(actor, input, 'b'.repeat(32));
assert.equal(first.hostRef, second.hostRef);
assert.equal(queries.filter((q) => q.sql === 'commit').length, 2);
const hosts = queries.filter((q) => q.sql.startsWith('insert into device_infrastructure_hosts'));
assert.equal(hosts[0].values[3], `b2-${source.id}`);
assert.equal(hosts[1].values[3], 'b2-existing-project-view');
const audit = queries.filter((q) => q.sql.includes('insert into device_audit_events'));
assert.ok(audit.length > 0);
assert.ok(!JSON.stringify(audit).includes(pkg.client_secret));
});
test('application deletion requires company and credential authority and forwards only the application ID', async () => {
const repo = repository(); const calls = [];
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg },
clientFactory: () => ({ async call(path, body) { calls.push({ path, body }); return { deleted: true, id: body.integration_id }; } }) });
const input = { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'application-delete', integrationId: 'c'.repeat(32) };
await assert.rejects(service.execute({ ...actor, hubRole: 'member', ownerScopes: [] }, input, '1'.repeat(32)), /device_owner_scope_access_denied/);
await assert.rejects(service.execute(actor, { ...input, integrationId: '../foreign' }, '1'.repeat(32)), /b2_identifier_invalid/);
await assert.rejects(service.execute(actor, { ...input, force: true }, '1'.repeat(32)), /b2_unexpected_field/);
assert.equal(calls.length, 0);
assert.deepEqual(await service.execute(actor, input, '1'.repeat(32)), { deleted: true, id: input.integrationId });
assert.deepEqual(calls, [{ path: '/v2/management/applications/delete', body: { integration_id: input.integrationId } }]);
assert.equal(repo.writes.at(-1).values[1], 'b2.application-delete');
});
test('enrollment options reveal only managed contours linked to the current active project', async () => {
const own = 'a'.repeat(32), foreign = 'b'.repeat(32); const repo = repository();
const db = await repo.pool.connect(), original = db.query; let released = false;
db.release = () => { released = true; };
db.query = async (sql, values) => {
if (sql.includes('from device_b2_hosts')) {
assert.match(sql, /l.project_id=v.project_id/); assert.match(sql, /h.lifecycle_state='active'/);
assert.deepEqual(values, [projectId]); return { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [own] }] };
}
return original(sql, values);
};
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
assert.ok(released);
return path === '/v2/identity' ? { host_id: pkg.host_id } : { items: [{ id: own, name: 'Own', access: 'manage' }, { id: foreign, name: 'Foreign', access: 'manage' }] };
} }) });
const result = await service.execute(actor, { projectRef: `project:${projectId}`, action: 'enrollment-options' });
assert.deepEqual(result.hosts[0].contours, [{ id: own, name: 'Own' }]); assert.ok(!JSON.stringify(result).includes('Foreign'));
});
test('enrollment validates project capability, active host and contour before forwarding USB', async () => {
const own = 'a'.repeat(32), foreign = 'b'.repeat(32); const repo = repository();
const db = await repo.pool.connect(), original = db.query; const calls = [];
db.query = async (sql, values) => {
if (sql.includes('from device_b2_hosts')) {
assert.match(sql, /l.project_id=v.project_id/); assert.match(sql, /h.lifecycle_state='active'/);
return { rows: values[0] === hostId && values[1] === projectId && values[2] === own ? [source] : [] };
}
return original(sql, values);
};
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
calls.push(path); return path === '/v2/identity' ? { host_id: pkg.host_id } : { accepted: body.action };
} }) });
const input = { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'enrollment', contourId: own, request: { action: 'register', name: 'B2', imei: '323456789012345', number: 300 } };
await assert.rejects(service.execute(actor, { ...input, contourId: foreign }), /b2_access_denied/);
assert.deepEqual(calls, []);
assert.deepEqual(await service.execute(actor, input), { accepted: 'register' });
assert.deepEqual(calls, ['/v2/identity', `/v2/contours/${own}/enrollment`]);
const denied = new B2Infrastructure({ pool: repository({ role: 'viewer' }).pool, secrets: { read: async () => assert.fail('no credentials') } });
await assert.rejects(denied.execute({ ...actor, hubRole: 'member' }, input));
await assert.rejects(denied.execute({ ...actor, hubRole: 'member' }, { projectRef: input.projectRef, action: 'enrollment-options' }));
});
test('enrollment permission alone cannot claim a device into a project', async () => {
const repo = repository({ role: 'engineer' }), db = await repo.pool.connect(), original = db.query;
db.query = async (sql, values) => {
const result = await original(sql, values);
if (sql.includes('from device_project_grants')) result.rows[0].capability_deny = ['device.claim'];
return result;
};
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => assert.fail('no remote credentials') } });
await assert.rejects(service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'enrollment', contourId: 'a'.repeat(32), request: { action: 'register', imei: '323456789012345', number: 300, name: 'B2' } }));
});