Compare commits

Author SHA1 Message Date
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
DCCONSTRUCTIONS 8bd6009aaa Name B2 vault module consistently with deployment path policy
Device Core qualification / qualify (push) Failing after 7m55s
2026-09-30 17:29:26 +03:00
DCCONSTRUCTIONS 6e63b15769 Pin accepted B2 foundation runner for application releases 2026-09-30 17:26:28 +03:00
DCCONSTRUCTIONS fd290c55d2 Version B2 foundation003 for readiness-corrected installer 2026-09-30 17:00:03 +03:00
DCCONSTRUCTIONS a11dabe245 Version B2 foundation artifact after Compose proof correction 2026-09-30 16:29:40 +03:00
DCCONSTRUCTIONS 1828a05332 Manage shared ARNavi VPS contours and application keys from infrastructure 2026-09-30 15:34:39 +03:00
DCCONSTRUCTIONS 6ca6738bab Record accepted automatic r13 with network priority evidence
Device Core qualification / qualify (push) Successful in 5m55s
2026-09-30 12:28:29 +03:00
DCCONSTRUCTIONS 33cd08c7ab Qualify Device Core releases against accepted network priority contract
Device Core qualification / qualify (push) Successful in 6m21s
2026-09-30 12:14:28 +03:00
DCCONSTRUCTIONS b2660df9e2 Record accepted automatic release r11 and remaining drift investigation
Device Core qualification / qualify (push) Successful in 7m0s
2026-09-30 08:38:19 +03:00
DCCONSTRUCTIONS 70065fb74c Retry transient dependency downloads during source qualification
Device Core qualification / qualify (push) Successful in 6m3s
2026-09-30 08:26:20 +03:00
DCCONSTRUCTIONS 893cb6490c Qualify automatic releases against installed runtime diagnostics
Device Core qualification / qualify (push) Failing after 1m47s
2026-09-30 08:20:37 +03:00
DCCONSTRUCTIONS e912e6ffaf Document ordered release delivery and restart recovery
Device Core qualification / qualify (push) Successful in 8m54s
2026-09-29 21:40:51 +03:00
DCCONSTRUCTIONS 154f243cfd Pin installed autodeploy controller and document NAS delivery
Device Core qualification / qualify (push) Successful in 8m27s
2026-09-29 21:38:29 +03:00
DCCONSTRUCTIONS edf69068ec Pin deploy installer with mount-order recovery and versioned fingerprints
Device Core qualification / qualify (push) Successful in 8m56s
2026-09-29 20:20:35 +03:00
DCCONSTRUCTIONS 298debd1b9 Test release installer against real Core and Manager health handlers
Device Core qualification / qualify (push) Successful in 7m18s
2026-09-29 19:28:07 +03:00
DCCONSTRUCTIONS 67b2ae5863 fix(ci): bind the served UI digest independently of source maps
Device Core qualification / qualify (push) Successful in 6m13s
2026-09-29 18:29:14 +03:00
DCCONSTRUCTIONS 55ab76bfc5 fix(ci): publish REST-accessible immutable Gitea v4 artifacts
Device Core qualification / qualify (push) Successful in 6m18s
2026-09-29 18:16:44 +03:00
DCCONSTRUCTIONS 415d5e73d7 fix(ci): qualify on the pinned Python and retain immutable release bundles
Device Core qualification / qualify (push) Successful in 5m51s
2026-09-29 18:04:12 +03:00
DCCONSTRUCTIONS 784a371e3e docs(ci): record runner activation and published source dependencies
Device Core qualification / qualify (push) Failing after 5m38s
2026-09-29 17:52:20 +03:00
70 changed files with 4595 additions and 718 deletions
+13
View File
@@ -5,6 +5,9 @@ on:
branches: [main] branches: [main]
workflow_dispatch: workflow_dispatch:
permissions:
contents: read
jobs: jobs:
qualify: qualify:
runs-on: nodedc-node22-build runs-on: nodedc-node22-build
@@ -13,6 +16,8 @@ jobs:
- name: Check the exact pushed commit - name: Check the exact pushed commit
env: env:
SOURCE_COMMIT: ${{ gitea.sha }} SOURCE_COMMIT: ${{ gitea.sha }}
SOURCE_RUN_ID: ${{ gitea.run_id }}
SOURCE_RUN_NUMBER: ${{ gitea.run_number }}
run: | run: |
set -eu set -eu
python3 -c 'import os,re; assert re.fullmatch("[0-9a-f]{40}", os.environ["SOURCE_COMMIT"]), "full commit SHA required"' python3 -c 'import os,re; assert re.fullmatch("[0-9a-f]{40}", os.environ["SOURCE_COMMIT"]), "full commit SHA required"'
@@ -26,5 +31,13 @@ jobs:
git -C "$source_root" checkout --quiet --detach FETCH_HEAD git -C "$source_root" checkout --quiet --detach FETCH_HEAD
python3 "$source_root/infra/ci/qualify.py" fetch-dependencies --commit "$SOURCE_COMMIT" python3 "$source_root/infra/ci/qualify.py" fetch-dependencies --commit "$SOURCE_COMMIT"
python3 "$source_root/infra/ci/qualify.py" check --commit "$SOURCE_COMMIT" --report "$job_root/qualification.json" python3 "$source_root/infra/ci/qualify.py" check --commit "$SOURCE_COMMIT" --report "$job_root/qualification.json"
python3 "$source_root/infra/ci/package_release.py" --report "$job_root/qualification.json" --run-id "$SOURCE_RUN_ID" --run-number "$SOURCE_RUN_NUMBER" --output-dir "$GITHUB_WORKSPACE/release"
- name: Retain the qualified release in this Gitea run
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: device-core-release
path: release
if-no-files-found: error
retention-days: 30
# Production activation is separate: this job has no production access. # Production activation is separate: this job has no production access.
# Do not label a successful qualification as a successful deployment. # Do not label a successful qualification as a successful deployment.
+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` The accepted Device Core policy is automatic deployment after a push to `main`
passes its checks. See [Continuous deployment](docs/CONTINUOUS_DEPLOYMENT.md) passes its checks. See [Continuous deployment](docs/CONTINUOUS_DEPLOYMENT.md)
for the pinned source qualification workflow, Synology setup and activation for the pinned source qualification workflow, Synology setup and activation
status. Automatic production installation is not enabled yet. status. Automatic production installation is active: the Synology controller fetches
qualified releases over outbound HTTPS and invokes the canonical runner.
No operator Mac or new inbound port is required.
Artifact builders in `infra/deploy-runner` emit data-only tarballs. They never Artifact builders in `infra/deploy-runner` emit data-only tarballs. They never
orchestrate Docker or mutate a live host. Promotion remains the established orchestrate Docker or mutate a live host. Promotion remains the established
@@ -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());
});
@@ -63,6 +63,12 @@ export function createDeviceCoreClient({ baseUrl, token, fetchImpl = fetch } = {
return { return {
configured: true, configured: true,
async b2Infrastructure(actor, input, requestId) {
return request("/internal/v1/b2/infrastructure", actor, {
method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": requestId },
body: JSON.stringify(input),
}).then((body) => body.result);
},
async listProjects(actor) { async listProjects(actor) {
return request("/internal/v1/query/projects", actor) return request("/internal/v1/query/projects", actor)
.then((body) => body.projects); .then((body) => body.projects);
@@ -1297,7 +1303,7 @@ function normalizeBaseUrl(value) {
} }
function safeCoreError(value) { function safeCoreError(value) {
return typeof value === "string" && /^device_[a-z0-9._:-]{2,120}$/.test(value) return typeof value === "string" && /^(?:device|b2)_[a-z0-9._:-]{2,120}$/.test(value)
? value ? value
: "device_core_unavailable"; : "device_core_unavailable";
} }
@@ -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"')); 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( const client = await readFile(
new URL("../src/DeviceControlViews.tsx", import.meta.url), new URL("../src/DeviceControlViews.tsx", import.meta.url),
"utf8", "utf8",
@@ -99,21 +99,7 @@ test("VPS inventory and monitoring follow the Mission Core system workspace geom
); );
for (const expected of [ for (const expected of [
'className="infrastructure-system-workspace"',
'className="infrastructure-system-workspace host-monitoring-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-series-grid"',
'className="host-monitoring-hardware"', 'className="host-monitoring-hardware"',
'className="host-monitoring-hardware-facts"', 'className="host-monitoring-hardware-facts"',
@@ -136,7 +122,6 @@ test("VPS inventory and monitoring follow the Mission Core system workspace geom
".infrastructure-host-relations {", ".infrastructure-host-relations {",
"grid-template-columns: repeat(3, minmax(0, 1fr));", "grid-template-columns: repeat(3, minmax(0, 1fr));",
"grid-template-columns: repeat(4, minmax(0, 1fr));", "grid-template-columns: repeat(4, minmax(0, 1fr));",
"background: var(--infrastructure-panel-soft);",
".host-monitoring-series polyline {", ".host-monitoring-series polyline {",
"stroke: var(--nodedc-text-primary);", "stroke: var(--nodedc-text-primary);",
".host-monitoring-hardware-facts {", ".host-monitoring-hardware-facts {",
@@ -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('title="Deployments и endpoints"'));
assert.ok(!infrastructureSource.includes("ceiling={100}")); assert.ok(!infrastructureSource.includes("ceiling={100}"));
assert.ok(!infrastructureSource.includes("Канонический ontology catalog")); assert.ok(!infrastructureSource.includes("Канонический ontology catalog"));
assert.ok(!styles.includes("background: var(--infrastructure-panel-soft);"), "Functional panels must not add nested black surfaces");
assert.ok(!styles.includes(".host-telemetry-metric,")); assert.ok(!styles.includes(".host-telemetry-metric,"));
assert.ok(!styles.includes(".host-telemetry-facts")); assert.ok(!styles.includes(".host-telemetry-facts"));
}); });
@@ -171,6 +171,19 @@ export function createDeviceManagerServer({
const workspace = await coreClient.getWorkspace(context.actor, projectRef); const workspace = await coreClient.getWorkspace(context.actor, projectRef);
return sendJson(response, 200, { ok: true, workspace }); return sendJson(response, 200, { ok: true, workspace });
} }
if (request.method === "POST" && url.pathname === "/api/device-manager/b2/infrastructure") {
if (!coreClient.b2Infrastructure) throw serviceError("b2_infrastructure_unavailable", 503);
// This route handles keys. Require JSON and an explicit same-origin
// browser request in addition to the authenticated server-side session.
if (request.headers.origin !== `${auth.authRequired ? 'https:' : url.protocol}//${request.headers.host}` || !String(request.headers["content-type"] || "").startsWith("application/json")) {
throw serviceError("device_manager_origin_required", 403);
}
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, 128 * 1024);
const result = await coreClient.b2Infrastructure(context.actor, input, requestId);
return sendJson(response, 200, { ok: true, result });
}
const command = mutationRoutes.get(url.pathname); const command = mutationRoutes.get(url.pathname);
if (request.method === "POST" && command) { if (request.method === "POST" && command) {
const idempotencyKey = singleHeader(request.headers["idempotency-key"]); const idempotencyKey = singleHeader(request.headers["idempotency-key"]);
@@ -373,7 +386,7 @@ function normalizeStatus(value) {
function safeError(error) { function safeError(error) {
const value = String(error?.message || ""); const value = String(error?.message || "");
return /^(?:device|nodedc)_[a-z0-9._:-]{2,160}$/.test(value) return /^(?:device|nodedc|b2)_[a-z0-9._:-]{2,160}$/.test(value)
? value ? value
: "device_manager_internal_error"; : "device_manager_internal_error";
} }
@@ -207,3 +207,44 @@ async function postJson(url, body, headers = {}) {
assert.equal(payload.ok, true); assert.equal(payload.ok, true);
return payload; return payload;
} }
test('B2 key management rejects cross-origin requests and never caches returned credentials', async (t) => {
const auth = createDeviceManagerAuth({ env: { NODEDC_DEVICE_MANAGER_AUTH_REQUIRED: 'false' } });
const calls = [];
const coreClient = { ...createLocalPreviewDeviceCore(), async b2Infrastructure(actor, body, id) {
calls.push({ actor, body, id }); return { connection: { client_secret: 'synthetic-once-only' } };
} };
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}`;
const headers = { 'content-type': 'application/json', 'idempotency-key': 'a'.repeat(32) };
const body = JSON.stringify({ action: 'key-issue', projectRef: 'project:synthetic', hostRef: 'host:synthetic' });
for (const supplied of [undefined, 'https://attacker.invalid']) {
const denied = await fetch(origin + '/api/device-manager/b2/infrastructure', { method: 'POST', headers: { ...headers, ...(supplied ? { origin: supplied } : {}) }, body });
assert.equal(denied.status, 403);
}
assert.equal(calls.length, 0);
const response = await fetch(origin + '/api/device-manager/b2/infrastructure', { method: 'POST',
headers: { ...headers, origin, 'X-NODEDC-User-Ref': 'user:spoofed' }, body });
assert.equal(response.status, 200);
assert.match(response.headers.get('cache-control'), /no-store/);
assert.equal((await response.json()).result.connection.client_secret, 'synthetic-once-only');
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 { useEffect, useMemo, useRef, useState } from "react";
import { import {
Button, Button,
GlassSurface, FeatureSettingsWindow,
ConfirmationModal,
ResourceList,
ResourceRow,
Icon, Icon,
IconButton, IconButton,
Select, Select,
@@ -14,6 +17,7 @@ import {
createConfigurationRevision, createConfigurationRevision,
setDesiredConfiguration, setDesiredConfiguration,
updateDevice, updateDevice,
archiveDevice,
} from "./api"; } from "./api";
import { import {
accessLabel, accessLabel,
@@ -27,58 +31,16 @@ import type {
SessionView, SessionView,
} from "./types"; } from "./types";
import { B2TrackerSettings } from "./b2/B2TrackerSettings";
import type { TrackerRef } from "./b2/tracker";
import { useB2Inventory } from "./b2/useB2Inventory";
export type DeviceInventoryDetailState = { export type DeviceInventoryDetailState = {
deviceRef: string; deviceRef: string;
sectionId: string; sectionId: string;
editing: boolean; editing: boolean;
}; };
export function DeviceDetailHeaderTools({
device,
detail,
canEdit,
onDetailChange,
}: {
device: DeviceView;
detail: DeviceInventoryDetailState;
canEdit: boolean;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
const catalog = getDeviceProfileCatalog(device.modelProfileRef);
const activeSection = catalog.sections.find((section) => section.id === detail.sectionId)
?? catalog.sections[0];
return (
<div className="device-detail-header-tools">
<Select
className="device-detail-section-select"
label="Раздел устройства"
value={activeSection?.id ?? catalog.sections[0]?.id ?? "passport"}
options={catalog.sections.map((section) => ({
value: section.id,
label: section.label,
}))}
onChange={(sectionId) => onDetailChange({ ...detail, sectionId })}
placement="bottom-end"
minMenuWidth={320}
menuWidth="anchor"
variant="split"
/>
<IconButton
label={detail.editing ? "Завершить редактирование" : "Редактировать устройство"}
disabled={!canEdit}
data-active={detail.editing || undefined}
onClick={() => onDetailChange({
...detail,
editing: !detail.editing,
})}
>
<Icon name="edit" size={17} />
</IconButton>
</div>
);
}
export function DeviceInventoryView({ export function DeviceInventoryView({
workspace, workspace,
canClaim, canClaim,
@@ -100,15 +62,22 @@ export function DeviceInventoryView({
onError: (reason: unknown) => void; onError: (reason: unknown) => void;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void; onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) { }) {
const [tracker, setTracker] = useState<{ device: TrackerRef; projectRef: string; section: string } | null>(null);
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const [typeFilter, setTypeFilter] = useState("all");
const [archiveTarget, setArchiveTarget] = useState<DeviceView | null>(null);
const [archiving, setArchiving] = useState(false);
const [statusFilter, setStatusFilter] = useState("all"); const [statusFilter, setStatusFilter] = useState("all");
const [sortOrder, setSortOrder] = useState("activity"); const [sortOrder, setSortOrder] = useState("activity");
const selectedDevice = workspace.devices.find( const selectedDevice = workspace.devices.find(
(device) => device.deviceRef === detail?.deviceRef, (device) => device.deviceRef === detail?.deviceRef,
) ?? null; ) ?? null;
const pendingEnrollments = workspace.enrollments.filter( const pendingEnrollments = workspace.enrollments.filter(
(enrollment) => enrollment.lifecycleState !== "claimed", (enrollment) => ["pending", "observed"].includes(enrollment.lifecycleState),
); );
const deviceRows = useMemo(() => workspace.devices 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) => { .map((device) => {
const session = latestSession(workspace, device); const session = latestSession(workspace, device);
const online = session?.lifecycleState === "online" || device.session?.state === "online"; const online = session?.lifecycleState === "online" || device.session?.state === "online";
@@ -128,7 +97,7 @@ export function DeviceInventoryView({
return left.online ? -1 : 1; return left.online ? -1 : 1;
} }
return String(right.lastSeenAt || "").localeCompare(String(left.lastSeenAt || "")); return String(right.lastSeenAt || "").localeCompare(String(left.lastSeenAt || ""));
}), [sortOrder, statusFilter, workspace]); }), [sortOrder, statusFilter, typeFilter, workspace]);
useEffect(() => { useEffect(() => {
if (detail?.deviceRef && !selectedDevice) onDetailChange(null); if (detail?.deviceRef && !selectedDevice) onDetailChange(null);
@@ -143,32 +112,29 @@ export function DeviceInventoryView({
return () => window.clearInterval(timer); return () => window.clearInterval(timer);
}, [detail?.deviceRef, onError, onPoll]); }, [detail?.deviceRef, onError, onPoll]);
if (selectedDevice && detail) {
return (
<DeviceDetailView
device={selectedDevice}
detail={detail}
workspace={workspace}
canConfigure={canConfigure}
canManageProject={canManageProject}
onDetailChange={onDetailChange}
onSaved={onPoll}
onError={onError}
onBack={() => onDetailChange(null)}
/>
);
}
const remoteRows = (b2.data?.items || []).filter(() => !['pending', 'archived', 'active', 'inactive'].includes(statusFilter))
.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 ( return (
<div className="device-inventory"> <div className="device-inventory">
{tracker && tracker.projectRef===workspace.project.projectRef ? <B2TrackerSettings key={`${tracker.projectRef}:${tracker.device.id}`} projectRef={tracker.projectRef} device={tracker.device} initialSection={tracker.section} onClose={()=>setTracker(null)} onError={onError} onChanged={onPoll} canConfigure={canConfigure} canCommand={workspace.project.access.capabilities.includes('command.dispatch')} /> : null}
{selectedDevice && detail ? <DeviceDetailView key={selectedDevice.deviceRef} device={selectedDevice} detail={detail} workspace={workspace}
canConfigure={canConfigure} canManageProject={canManageProject} onDetailChange={onDetailChange} onSaved={onPoll} onError={onError} onBack={() => onDetailChange(null)} /> : null}
<ConfirmationModal open={Boolean(archiveTarget)} title={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить устройство?' : 'Перенести устройство в архив?'} description={archiveTarget?.displayName} confirmLabel={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => {
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 className="device-manager-panel-toolbar device-inventory__toolbar">
<div> <div>
<strong>Реестр устройств</strong> <strong>Реестр устройств</strong>
<p>{workspace.devices.length} зарегистрировано · {pendingEnrollments.length} ожидают подключения</p> <p>{count} зарегистрировано · {pendingEnrollments.length} ожидают подключения</p>
</div> </div>
</div> </div>
<div className="device-inventory__filters" aria-label="Фильтры устройств"> <div className="device-inventory__filters" aria-label="Фильтры устройств">
<Select label="Тип устройства" value={typeFilter} onChange={setTypeFilter} options={[{ value: 'all', label: 'Все типы' }, { value: 'arnavi', label: 'ARNavi B2' }]} />
<Select <Select
label="Состояние" label="Состояние"
value={statusFilter} value={statusFilter}
@@ -177,6 +143,7 @@ export function DeviceInventoryView({
{ value: "active", label: "Активные" }, { value: "active", label: "Активные" },
{ value: "inactive", label: "Неактивные" }, { value: "inactive", label: "Неактивные" },
{ value: "pending", label: "Ожидают подключения" }, { value: "pending", label: "Ожидают подключения" },
{ value: "archived", label: "Архив" },
]} ]}
onChange={setStatusFilter} onChange={setStatusFilter}
/> />
@@ -193,54 +160,22 @@ export function DeviceInventoryView({
/> />
</div> </div>
{statusFilter !== "pending" && !deviceRows.length ? ( {b2.error ? <p role="alert">{b2.error}</p> : null}
<GlassSurface className="device-manager-empty device-inventory__empty" padding="lg" tone="soft"> {b2.data?.hosts.filter((host) => !host.reachable).map((host) => <ResourceRow key={host.hostRef} title={host.name} status={<StatusBadge tone="warning">Нет связи с VPS</StatusBadge>} />)}
<Icon name="inbox" size={24} /> {statusFilter !== 'pending' ? <ResourceList>
<h3>{workspace.devices.length ? "Устройств с таким состоянием нет" : "В проекте пока нет устройств"}</h3> {remoteRows.map((device) => <li key={`${device.hostRef}:${device.id}`}><ResourceRow
<p>Добавьте разрешённый трекер через «плюс». Идентификатор попадёт в Device Core по защищённому процессу подключения.</p> icon={<Icon name="apps" />} title={device.name || `ARNavi B2 · ${device.number}`} metadata={`ARNavi B2 · ${device.number} · IMEI ${device.identifier.masked}`} description={device.hostName}
</GlassSurface> 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>)}
) : statusFilter !== "pending" ? ( {deviceRows.map(({ device, online, lastSeenAt }) => <li key={device.deviceRef}><ResourceRow
<GlassSurface className="device-inventory-table" padding="sm" tone="soft" role="table" aria-label="Устройства проекта"> icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`}
<div className="device-inventory-table__head" role="row"> description={lastSeenAt ? formatDate(lastSeenAt) : undefined}
<span role="columnheader">Устройство</span> status={<StatusBadge tone={online ? 'success' : 'neutral'}>{device.lifecycleState === 'suspended' ? 'В архиве' : online ? 'Онлайн' : 'Не в сети'}</StatusBadge>}
<span role="columnheader">Профиль</span> actions={<><IconButton label={`Настройки ${device.displayName}`} onClick={() => onDetailChange({ deviceRef: device.deviceRef, sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? 'passport', editing: false })}><Icon name="settings" /></IconButton>
<span role="columnheader">IMEI</span> {canManageProject && !online ? <Button size="compact" disabled={archiving} onClick={() => setArchiveTarget(device)}>{device.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button> : null}</>} /></li>)}
<span role="columnheader">ID интеграционного устройства</span> </ResourceList> : null}
<span role="columnheader">Канал</span> {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}
<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}
{(statusFilter === "all" || statusFilter === "pending") ? ( {(statusFilter === "pending" || statusFilter === "all" && pendingEnrollments.length > 0) ? (
<section className="device-inventory__pending" aria-label="Ожидают подключения"> <section className="device-inventory__pending" aria-label="Ожидают подключения">
<div className="device-inventory__section-heading"> <div className="device-inventory__section-heading">
<div> <div>
@@ -264,9 +199,9 @@ export function DeviceInventoryView({
<p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p> <p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p>
</SettingsCard> </SettingsCard>
)) : ( )) : (
<GlassSurface className="device-manager-panel-empty device-inventory__pending-empty" padding="md" tone="soft"> <div className="device-manager-panel-empty device-inventory__pending-empty">
Нет ожидающих подключений. Нет ожидающих подключений.
</GlassSurface> </div>
)} )}
</section> </section>
) : null} ) : null}
@@ -417,35 +352,21 @@ function DeviceDetailView({
}; };
return ( return (
<FeatureSettingsWindow open title="Настройки устройства" subtitle={workspace.project.name}
identity={{ title: device.displayName, subtitle: `${catalog.vendor} · ${catalog.model}`, avatarLabel: catalog.vendor.slice(0, 2) }}
sections={catalog.sections.map((section) => ({ id: section.id, label: section.label }))}
activeSection={activeSection.id} onSectionChange={(sectionId) => onDetailChange({ ...detail, sectionId })} onClose={onBack}
headerActions={<><IconButton label="Обновить устройство" disabled={saving} onClick={() => void onSaved().catch(onError)}><Icon name="refresh" /></IconButton>
{(canConfigure || canManageProject) ? <IconButton label={detail.editing ? 'Завершить редактирование' : 'Редактировать устройство'} disabled={saving} onClick={() => onDetailChange({ ...detail, editing: !detail.editing })}><Icon name="edit" /></IconButton> : null}</>}>
<div ref={detailRef} className="device-detail"> <div ref={detailRef} className="device-detail">
<div className="device-detail__header"> <div className="device-detail__connection">
<IconButton label="Вернуться к списку устройств" onClick={onBack}>
<Icon name="chevron-left" size={18} />
</IconButton>
<div className="device-detail__identity">
<small>{catalog.vendor} · {catalog.model}</small>
<h2>{device.displayName}</h2>
<p>{identifierDisplayValue || "Идентификатор не назначен"} · {device.modelProfileRef}</p>
</div>
<StatusBadge tone={session?.lifecycleState === "online" ? "success" : "neutral"}>
{session?.lifecycleState === "online" ? "Онлайн" : session?.lifecycleState || device.lifecycleState}
</StatusBadge>
</div>
<div className="device-detail__legend" aria-label="Режимы доступа">
<AccessBadge access="read-only" />
<AccessBadge access="managed" />
<AccessBadge access="protected" />
</div>
<GlassSurface className="device-detail__connection" padding="md" tone="soft">
<div><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div> <div><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div>
<div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div> <div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div>
<div><span>Протокол</span><strong>{session?.protocol || profile?.protocol || "Нет данных"}</strong></div> <div><span>Протокол</span><strong>{session?.protocol || profile?.protocol || "Нет данных"}</strong></div>
<div><span>Последняя активность</span><strong>{formatDate(session?.lastSeenAt || device.session?.lastSeenAt)}</strong></div> <div><span>Последняя активность</span><strong>{formatDate(session?.lastSeenAt || device.session?.lastSeenAt)}</strong></div>
<div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div> <div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div>
<div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div> <div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div>
</GlassSurface> </div>
<div className="device-detail__layout"> <div className="device-detail__layout">
<section className="device-detail-section"> <section className="device-detail-section">
@@ -475,7 +396,7 @@ function DeviceDetailView({
? draftValues[item.path] ? draftValues[item.path]
: readPath(context, item.path); : readPath(context, item.path);
return ( return (
<GlassSurface key={item.key} className="device-detail-field" padding="sm" tone="soft" data-access={access} data-editing={editable || undefined}> <div key={item.key} className="device-detail-field" data-access={access} data-editing={editable || undefined}>
{editable && item.valueKind === "boolean" ? ( {editable && item.valueKind === "boolean" ? (
<Switch <Switch
checked={Boolean(value)} checked={Boolean(value)}
@@ -503,7 +424,7 @@ function DeviceDetailView({
{item.description ? <small>{item.description}</small> : null} {item.description ? <small>{item.description}</small> : null}
</> </>
)} )}
</GlassSurface> </div>
); );
})} })}
</div> </div>
@@ -534,14 +455,15 @@ function DeviceDetailView({
) : null} ) : null}
<div className="device-detail-section__state"> <div className="device-detail-section__state">
<span>Desired</span> <span>Запрошенная конфигурация</span>
<strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong> <strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong>
<span>Applied</span> <span>Подтверждена устройством</span>
<strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong> <strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong>
</div> </div>
</section> </section>
</div> </div>
</div> </div>
</FeatureSettingsWindow>
); );
} }
@@ -614,12 +536,12 @@ function AccessNotice({
commandTransport: ProjectWorkspace["policies"]["commandTransport"]; commandTransport: ProjectWorkspace["policies"]["commandTransport"];
}) { }) {
if (access === "read-only") { if (access === "read-only") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></GlassSurface>; return <div className="device-detail-notice"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></div>;
} }
if (access === "protected") { if (access === "protected") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></GlassSurface>; return <div className="device-detail-notice"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></div>;
} }
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></GlassSurface>; return <div className="device-detail-notice"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></div>;
} }
function latestSession(workspace: ProjectWorkspace, device: DeviceView): SessionView | null { function latestSession(workspace: ProjectWorkspace, device: DeviceView): SessionView | null {
+64 -63
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState, type FormEvent } from "react"; import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { import {
AdminNavigationPanel, AdminNavigationPanel,
AppHeader, AppHeader,
@@ -9,6 +9,8 @@ import {
Dropdown, Dropdown,
FeatureSettingsWindow, FeatureSettingsWindow,
GlassSurface, GlassSurface,
ResourceList,
ResourceRow,
HeaderNavigation, HeaderNavigation,
HeaderProfile, HeaderProfile,
HeaderWorkspace, HeaderWorkspace,
@@ -56,12 +58,14 @@ import type {
ProjectWorkspace, ProjectWorkspace,
} from "./types"; } from "./types";
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor"; import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
import { B2AddDevice } from "./b2/B2AddDevice";
import { B2AddHost } from "./b2/B2AddHost";
import { useB2Inventory } from "./b2/useB2Inventory";
import { import {
DeviceControlView, DeviceControlView,
type ControlViewId, type ControlViewId,
} from "./DeviceControlViews"; } from "./DeviceControlViews";
import { import {
DeviceDetailHeaderTools,
DeviceInventoryView, DeviceInventoryView,
type DeviceInventoryDetailState, type DeviceInventoryDetailState,
} from "./DeviceInventoryView"; } from "./DeviceInventoryView";
@@ -99,13 +103,9 @@ const sectionNavigation: Record<PrimarySection, NavigationItem[]> = {
], ],
infrastructure: [ infrastructure: [
{ id: "hosts", label: "VPS и хосты", icon: "building", capability: "telemetry.observe" }, { id: "hosts", label: "VPS и хосты", icon: "building", capability: "telemetry.observe" },
{ id: "infrastructure", label: "Edges и маршруты", icon: "globe", capability: "telemetry.observe" },
{ id: "catalog", label: "Модели и адаптеры", icon: "database", capability: "project.read" },
], ],
management: [ management: [
{ id: "bindings", label: "Связи с Foundry", icon: "external", capability: "binding.manage" }, { id: "bindings", label: "Связи с Foundry", icon: "external", capability: "binding.manage" },
{ id: "commands", label: "Команды", icon: "target", capability: "command.plan" },
{ id: "settings", label: "Конфигурации", icon: "settings", capability: "configuration.read" },
], ],
administration: [ administration: [
{ id: "audit", label: "Аудит", icon: "clipboard", capability: "audit.read" }, { id: "audit", label: "Аудит", icon: "clipboard", capability: "audit.read" },
@@ -188,10 +188,14 @@ export function DeviceManagerApp() {
const [workspace, setWorkspace] = useState<ProjectWorkspace | null>(null); const [workspace, setWorkspace] = useState<ProjectWorkspace | null>(null);
const [activeOwnerRef, setActiveOwnerRef] = useState(""); const [activeOwnerRef, setActiveOwnerRef] = useState("");
const [activeProjectRef, setActiveProjectRef] = useState(""); const [activeProjectRef, setActiveProjectRef] = useState("");
const projectRefCurrent = useRef(activeProjectRef);
projectRefCurrent.current = activeProjectRef;
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [projectDialogOpen, setProjectDialogOpen] = useState(false); const [projectDialogOpen, setProjectDialogOpen] = useState(false);
const [collectionDialogOpen, setCollectionDialogOpen] = useState(false); const [collectionDialogOpen, setCollectionDialogOpen] = useState(false);
const [addHostOpen, setAddHostOpen] = useState(false);
const [addDeviceOpen, setAddDeviceOpen] = useState(false);
const [enrollmentDialogOpen, setEnrollmentDialogOpen] = useState(false); const [enrollmentDialogOpen, setEnrollmentDialogOpen] = useState(false);
const [claimEnrollment, setClaimEnrollment] = useState<EnrollmentView | null>(null); const [claimEnrollment, setClaimEnrollment] = useState<EnrollmentView | null>(null);
const [projectSettingsOpen, setProjectSettingsOpen] = useState(false); const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);
@@ -231,6 +235,7 @@ export function DeviceManagerApp() {
useEffect(() => { useEffect(() => {
applyNodedcTheme(document.documentElement, { applyNodedcTheme(document.documentElement, {
theme: presentation.environment.theme, theme: presentation.environment.theme,
appearance: "mission",
accent: hexToRgb(presentation.environment.accentHex), accent: hexToRgb(presentation.environment.accentHex),
}); });
}, [presentation.environment.accentHex, presentation.environment.theme]); }, [presentation.environment.accentHex, presentation.environment.theme]);
@@ -286,9 +291,11 @@ export function DeviceManagerApp() {
}, [activeOwnerRef, activeProjectRef, visibleProjects]); }, [activeOwnerRef, activeProjectRef, visibleProjects]);
const selectProject = (projectRef: string) => { const selectProject = (projectRef: string) => {
if (projectRef === activeProjectRef) return;
setInventoryDetail(null); setInventoryDetail(null);
projectRefCurrent.current = projectRef;
setWorkspace(null);
setActiveProjectRef(projectRef); setActiveProjectRef(projectRef);
shell.closeView();
}; };
const openSection = (section: PrimarySection) => { const openSection = (section: PrimarySection) => {
@@ -305,14 +312,17 @@ export function DeviceManagerApp() {
}; };
const selectOwner = (ownerRef: string) => { const selectOwner = (ownerRef: string) => {
if (ownerRef === activeOwnerRef) return;
setActiveOwnerRef(ownerRef); setActiveOwnerRef(ownerRef);
setInventoryDetail(null); setInventoryDetail(null);
setWorkspace(null);
const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef); const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef);
if (nextProject) { if (nextProject) {
projectRefCurrent.current = nextProject.projectRef;
setActiveProjectRef(nextProject.projectRef); setActiveProjectRef(nextProject.projectRef);
shell.closeView();
} }
else { else {
projectRefCurrent.current = "";
setActiveProjectRef(""); setActiveProjectRef("");
setWorkspace(null); setWorkspace(null);
shell.closeView(); shell.closeView();
@@ -322,6 +332,7 @@ export function DeviceManagerApp() {
const refreshWorkspace = async () => { const refreshWorkspace = async () => {
if (!activeProjectRef) return; if (!activeProjectRef) return;
const next = await loadWorkspace(activeProjectRef); const next = await loadWorkspace(activeProjectRef);
if (projectRefCurrent.current !== activeProjectRef) return;
setWorkspace(next); setWorkspace(next);
await refreshProjects(); await refreshProjects();
}; };
@@ -329,17 +340,14 @@ export function DeviceManagerApp() {
const pollWorkspace = async () => { const pollWorkspace = async () => {
if (!activeProjectRef) return; if (!activeProjectRef) return;
const next = await loadWorkspace(activeProjectRef); const next = await loadWorkspace(activeProjectRef);
setWorkspace(next); if (projectRefCurrent.current === activeProjectRef) setWorkspace(next);
}; };
if (loading || !session) { if (loading || !session) {
return <div className="device-manager-boot">Подключаем Device Core…</div>; return <div className="device-manager-boot">Подключаем Device Core…</div>;
} }
const activeView = shell.activeView; const activeView = visibleNavigationItems.some((item) => item.id === shell.activeView) ? shell.activeView : null;
const selectedInventoryDevice = inventoryDetail
? workspace?.devices.find((device) => device.deviceRef === inventoryDetail.deviceRef) ?? null
: null;
return ( return (
<> <>
<ApplicationShell <ApplicationShell
@@ -405,8 +413,8 @@ export function DeviceManagerApp() {
{activeSection === "devices" && activeProject ? ( {activeSection === "devices" && activeProject ? (
<IconButton <IconButton
label="Подключить устройство" label="Подключить устройство"
disabled={!canEnroll || !workspace?.routes.some((route) => route.lifecycleState === "active")} disabled={!canEnroll}
onClick={() => setEnrollmentDialogOpen(true)} onClick={() => setAddDeviceOpen(true)}
> >
<Icon name="plus" size={16} /> <Icon name="plus" size={16} />
</IconButton> </IconButton>
@@ -482,21 +490,18 @@ export function DeviceManagerApp() {
expanded={shell.contentExpanded} expanded={shell.contentExpanded}
onExpandedChange={shell.setContentExpanded} onExpandedChange={shell.setContentExpanded}
onClose={shell.closeView} onClose={shell.closeView}
headerTools={activeView === "inventory" && selectedInventoryDevice && inventoryDetail ? ( utilityActions={[...(activeView === 'inventory' && canEnroll ? [{
<DeviceDetailHeaderTools label: 'Добавить устройство', icon: 'plus' as const, onClick: () => setAddDeviceOpen(true),
device={selectedInventoryDevice} }] : []), ...(activeView === 'hosts' && capabilities.has('infrastructure.manage') ? [{
detail={inventoryDetail} label: 'Добавить VPS', icon: 'plus' as const, onClick: () => setAddHostOpen(true),
canEdit={canConfigure || canManageProject} }] : []), {
onDetailChange={setInventoryDetail}
/>
) : undefined}
utilityActions={[{
label: "Обновить данные", label: "Обновить данные",
icon: "refresh", icon: "refresh",
onClick: () => refreshWorkspace().catch((reason) => setError(errorText(reason))), onClick: () => refreshWorkspace().catch((reason) => setError(errorText(reason))),
}]} }]}
> >
<ProjectView <ProjectView
key={activeProjectRef}
view={activeView} view={activeView}
workspace={workspace} workspace={workspace}
canManageCollections={canManageCollections} canManageCollections={canManageCollections}
@@ -548,6 +553,8 @@ export function DeviceManagerApp() {
}} }}
onError={(reason) => setError(errorText(reason))} onError={(reason) => setError(errorText(reason))}
/> />
{addDeviceOpen && workspace ? <B2AddDevice key={activeProjectRef} workspace={workspace} onClose={() => setAddDeviceOpen(false)} onCreated={async () => { setAddDeviceOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} onLegacy={workspace.routes.some(route => route.lifecycleState === 'active') ? () => { setAddDeviceOpen(false); setEnrollmentDialogOpen(true); } : undefined} /> : null}
{addHostOpen && activeProject ? <B2AddHost key={activeProjectRef} open projectRef={activeProjectRef} onClose={() => setAddHostOpen(false)} onCreated={async () => { setAddHostOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} /> : null}
<EnrollmentDialog <EnrollmentDialog
open={enrollmentDialogOpen} open={enrollmentDialogOpen}
workspace={workspace} workspace={workspace}
@@ -773,16 +780,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 }: { function ProjectView({ view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: {
view: ViewId; view: ViewId;
workspace: ProjectWorkspace | null; workspace: ProjectWorkspace | null;
@@ -826,7 +823,7 @@ function ProjectView({ view, workspace, canManageCollections, canClaim, canConfi
if (view === "collections") return ( if (view === "collections") return (
<div className="device-manager-stack"> <div className="device-manager-stack">
<div className="device-manager-panel-toolbar"> <div className="device-manager-panel-toolbar">
<p>Коллекции группируют устройства для последующих bindings и задач.</p> <p>Группы устройств проекта.</p>
<Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button> <Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button>
</div> </div>
<EntityList <EntityList
@@ -841,17 +838,27 @@ function ProjectView({ view, workspace, canManageCollections, canClaim, canConfi
/> />
</div> </div>
); );
return <ProjectOverview key={workspace.project.projectRef} workspace={workspace} />;
}
function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) {
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const incomplete = !b2.data || b2.data.hosts.some((host) => !host.reachable);
const deviceCount = incomplete ? null : workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + b2.data!.items.length;
const deviceDetail = !incomplete ? 'В реестре' : (b2.error || b2.data) ? 'Данные VPS недоступны' : 'Загрузка…';
const metrics = [
{ label: 'Устройства', value: deviceCount, detail: deviceDetail },
{ label: 'Ожидают проверки', value: workspace.discoveries.filter((item) => item.lifecycleState === 'quarantine').length, detail: 'Обнаружены' },
{ label: 'Коллекции', value: workspace.collections.length, detail: 'Группы устройств' },
];
return ( return (
<div className="device-manager-overview-grid"> <ResourceList>
<Metric label="Устройства" value={workspace.devices.length} detail="inventory" /> {metrics.map((metric) => (
<Metric label="Quarantine" value={workspace.discoveries.filter((item) => item.lifecycleState === "quarantine").length} detail="safe projection" /> <li key={metric.label}>
<Metric label="Коллекции" value={workspace.collections.length} detail="bindings ready" /> <ResourceRow title={metric.label} metadata={metric.detail} status={<StatusBadge>{metric.value ?? '—'}</StatusBadge>} />
<SettingsCard title="Права проекта" description={workspace.project.access.projectRole || "read"}> </li>
<div className="device-manager-capabilities"> ))}
{workspace.project.access.capabilities.map((capability) => <StatusBadge key={capability}>{capability}</StatusBadge>)} </ResourceList>
</div>
</SettingsCard>
</div>
); );
} }
@@ -934,7 +941,7 @@ function ProjectSettingsDialog({ open, workspace, presentation, onClose, onSaved
avatarUrl: iconPreview ?? undefined, avatarUrl: iconPreview ?? undefined,
}} }}
sections={[ sections={[
{ id: "identity", label: "Идентичность", icon: "profile", group: "Проект" }, { id: "identity", label: "Основное", icon: "profile", group: "Проект" },
{ id: "media", label: "Медиа", icon: "image", group: "Оформление" }, { id: "media", label: "Медиа", icon: "image", group: "Оформление" },
]} ]}
activeSection={section} activeSection={section}
@@ -1233,13 +1240,9 @@ function EnvironmentSettingsDialog({ open, presentation, onClose, onSaved, onErr
function EntityList({ items, empty }: { items: Array<{ id: string; title: string; subtitle: string; status: string; tone: "neutral" | "success" | "warning" }>; empty: string }) { function EntityList({ items, empty }: { items: Array<{ id: string; title: string; subtitle: string; status: string; tone: "neutral" | "success" | "warning" }>; empty: string }) {
if (!items.length) return <div className="device-manager-panel-empty">{empty}</div>; if (!items.length) return <div className="device-manager-panel-empty">{empty}</div>;
return <div className="device-manager-entity-list">{items.map((item) => ( return <ResourceList>{items.map((item) => <li key={item.id}><ResourceRow
<GlassSurface key={item.id} className="device-manager-entity" padding="md" tone="soft"> icon={<Icon name="folder" />} title={item.title} description={item.subtitle}
<span className="device-manager-entity__icon"><Icon name="circle" /></span> status={<StatusBadge tone={item.tone}>{item.status}</StatusBadge>} /></li>)}</ResourceList>;
<span className="device-manager-entity__body"><strong>{item.title}</strong><small>{item.subtitle}</small></span>
<StatusBadge tone={item.tone}>{item.status}</StatusBadge>
</GlassSurface>
))}</div>;
} }
function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: { function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: {
@@ -1279,17 +1282,17 @@ function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated,
await onCreated(); await onCreated();
} catch (reason) { onError(reason); } finally { setPending(false); } } catch (reason) { onError(reason); } finally { setPending(false); }
}; };
return <Window open={open} title="Новый Device Project" subtitle={ownerScope?.displayName || "Owner scope недоступен"} onClose={onClose} footer={ return <Window open={open} title="Новый проект" subtitle={ownerScope?.displayName || "Компания недоступна"} onClose={onClose} footer={
<WindowFooterActions><Button variant="ghost" onClick={onClose}>Отмена</Button><Button type="submit" form="device-project-form" variant="primary" disabled={pending || !ownerScope}>{pending ? "Создаём…" : "Создать"}</Button></WindowFooterActions> <WindowFooterActions><Button variant="ghost" onClick={onClose}>Отмена</Button><Button type="submit" form="device-project-form" variant="primary" disabled={pending || !ownerScope}>{pending ? "Создаём…" : "Создать"}</Button></WindowFooterActions>
}> }>
<form id="device-project-form" className="device-manager-form" onSubmit={submit}> <form id="device-project-form" className="device-manager-form" onSubmit={submit}>
<Select <Select
label="Контур проекта" label="Владелец проекта"
value={ownerRef} value={ownerRef}
options={ownerScopes.map((scope) => ({ options={ownerScopes.map((scope) => ({
value: scope.ownerRef, value: scope.ownerRef,
label: scope.displayName, label: scope.displayName,
description: scope.scopeKind === "company" ? "Коммерческий контур" : "Личный контур", description: scope.scopeKind === "company" ? "Компания" : "Личное пространство",
}))} }))}
onChange={setOwnerRef} onChange={setOwnerRef}
/> />
@@ -1353,7 +1356,6 @@ function ClaimDialog({ enrollment, project, onClose, onClaimed, onError }: {
<form id="device-claim-form" className="device-manager-form" onSubmit={submit}> <form id="device-claim-form" className="device-manager-form" onSubmit={submit}>
<TextField label="Название устройства" value={name} onChange={(event) => setName(event.target.value)} required maxLength={160} /> <TextField label="Название устройства" value={name} onChange={(event) => setName(event.target.value)} required maxLength={160} />
<TextField label="Ключ устройства" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" /> <TextField label="Ключ устройства" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<p className="device-manager-card-copy">Claim использует только ссылки на enrollment и discovery. Исходный идентификатор не запрашивается повторно.</p>
</form> </form>
</Window>; </Window>;
} }
@@ -1432,7 +1434,6 @@ function EnrollmentDialog({ open, workspace, onClose, onCreated, onError }: {
<TextField label="Ключ enrollment" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" /> <TextField label="Ключ enrollment" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<TextField label="IMEI" value={imei} onChange={(event) => setImei(event.target.value.replace(/\D/g, "").slice(0, 15))} required pattern="[0-9]{15}" inputMode="numeric" autoComplete="off" /> <TextField label="IMEI" value={imei} onChange={(event) => setImei(event.target.value.replace(/\D/g, "").slice(0, 15))} required pattern="[0-9]{15}" inputMode="numeric" autoComplete="off" />
<TextField label="Истекает" type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} description="Опционально. Время будет сохранено в UTC." /> <TextField label="Истекает" type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} description="Опционально. Время будет сохранено в UTC." />
<p className="device-manager-card-copy">IMEI передаётся один раз по HTTPS в Device Control Core. В базе, audit и ответе останутся только HMAC и маска.</p>
</form> </form>
</Window>; </Window>;
} }
@@ -1458,11 +1459,11 @@ function viewTitle(view: ViewId) {
collections: "Коллекции", collections: "Коллекции",
catalog: "Модели и адаптеры", catalog: "Модели и адаптеры",
hosts: "VPS и хосты", hosts: "VPS и хосты",
infrastructure: "Edges и маршруты", infrastructure: "Узлы и маршруты",
sessions: "Gateway sessions", sessions: "Подключения устройств",
bindings: "Data bindings", bindings: "Связи с Foundry",
commands: "Command ledger", commands: "Команды",
audit: "Immutable audit", audit: "Аудит",
access: "Доступ к проекту", access: "Доступ к проекту",
settings: "Настройки и конфигурации", settings: "Настройки и конфигурации",
})[view]; })[view];
+7
View File
@@ -442,3 +442,10 @@ async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
} }
return body as 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>;
}
@@ -0,0 +1,226 @@
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, type B2Application } from './api';
import './b2.css';
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>('contours');
const [status, setStatus] = useState<B2Status | null>(null);
const [pending, setPending] = useState('load');
const [connection, setConnection] = useState(''), [importOpen, setImportOpen] = useState(false);
const connectionFile = useRef<HTMLInputElement>(null);
const [projects, setProjects] = useState<ProjectSummary[]>([]);
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> = {}, 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;
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
if (!active) return;
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]);
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?: { 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>;
}
return <>
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
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></>}>
<div className="b2-settings" aria-busy={busy}>
{syncError ? <p role="status">{syncError}</p> : null}
{section === 'connection' ? <>
<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' ? <>
<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={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; }
+42
View File
@@ -0,0 +1,42 @@
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_shared_projects_migration_required: 'На сервере Device Core ещё не установлена миграция общих контуров. До её установки контур можно связать только с одним проектом.',
b2_connection_identity_conflict: 'Этот хост уже подключён другим приложением или ключом сервера.',
b2_certificate_mismatch: 'Сертификат VPS не соответствует ключу подключения.',
b2_private_storage_unavailable: 'Закрытое хранилище ключей ещё не настроено на Device Core.',
b2_connection_invalid: 'Не удалось прочитать ключ подключения ARNavi VPS.',
b2_company_mismatch: 'Выберите проект той же компании.',
device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.',
};
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': requestId },
body: JSON.stringify({ projectRef, hostRef, action, ...fields }),
});
const body = await response.json().catch(() => null);
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
View File
@@ -0,0 +1,21 @@
.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 { .device-control-toolbar {
align-items: center; align-items: center;
padding: 2px 0 14px; padding: 2px 0 14px;
border-bottom: 1px solid var(--nodedc-glass-outline);
} }
.device-control-toolbar > p { .device-control-toolbar > p {
@@ -42,8 +41,8 @@
.device-control-resource-grid { .device-control-resource-grid {
display: grid; display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--nodedc-space-3);
gap: 12px; grid-template-columns: minmax(0, 1fr);
} }
.device-control-row { .device-control-row {
@@ -122,9 +121,7 @@
} }
.device-control-form { .device-control-form {
max-height: min(62vh, 680px); min-width: 0;
overflow-y: auto;
padding-right: 3px;
} }
.infrastructure-system-workspace { .infrastructure-system-workspace {
@@ -142,55 +139,9 @@
.infrastructure-assets-block { .infrastructure-assets-block {
min-width: 0; min-width: 0;
border-radius: var(--nodedc-radius-card); border-radius: var(--nodedc-radius-card);
background: var(--infrastructure-panel-soft);
padding: 1rem; padding: 1rem;
} }
.infrastructure-system-workspace .nodedc-status {
min-height: auto;
justify-content: flex-start;
gap: 0.42rem;
border-radius: 0;
background: transparent;
color: var(--nodedc-text-primary);
padding: 0;
font-size: var(--nodedc-font-size-sm);
font-weight: var(--nodedc-font-weight-medium);
}
.infrastructure-system-workspace .nodedc-status::before {
width: 0.42rem;
height: 0.42rem;
flex: 0 0 0.42rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
content: "";
}
.infrastructure-system-workspace .nodedc-status[data-tone="success"],
.infrastructure-system-workspace .nodedc-status[data-tone="warning"],
.infrastructure-system-workspace .nodedc-status[data-tone="danger"],
.infrastructure-system-workspace .nodedc-status[data-tone="accent"] {
background: transparent;
color: var(--nodedc-text-primary);
}
.infrastructure-system-workspace .nodedc-status[data-tone="success"]::before {
background: rgb(var(--nodedc-success-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="warning"]::before {
background: rgb(var(--nodedc-warning-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="danger"]::before {
background: rgb(var(--nodedc-danger-rgb));
}
.infrastructure-system-workspace .nodedc-status[data-tone="accent"]::before {
background: var(--nodedc-text-primary);
}
.infrastructure-eyebrow { .infrastructure-eyebrow {
display: block; display: block;
color: var(--nodedc-text-muted); color: var(--nodedc-text-muted);
@@ -264,7 +215,6 @@
.host-monitoring-series { .host-monitoring-series {
min-width: 0; min-width: 0;
border-radius: var(--nodedc-radius-card); border-radius: var(--nodedc-radius-card);
background: var(--infrastructure-panel-soft);
} }
.infrastructure-count-card { .infrastructure-count-card {
@@ -425,7 +375,6 @@
margin: 0; margin: 0;
padding: 0.72rem; padding: 0.72rem;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
} }
.infrastructure-host-card__facts > div { .infrastructure-host-card__facts > div {
@@ -464,7 +413,6 @@
gap: 0.55rem; gap: 0.55rem;
padding: 0.72rem; padding: 0.72rem;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
} }
.infrastructure-host-relations > section > header { .infrastructure-host-relations > section > header {
@@ -573,7 +521,6 @@
gap: 0.9rem; gap: 0.9rem;
padding: 0.72rem 0.8rem; padding: 0.72rem 0.8rem;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
} }
.infrastructure-registry-row > div, .infrastructure-registry-row > div,
@@ -610,7 +557,6 @@
.infrastructure-empty { .infrastructure-empty {
padding: 0.8rem; padding: 0.8rem;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
color: var(--nodedc-text-muted); color: var(--nodedc-text-muted);
font-size: 0.65rem; font-size: 0.65rem;
line-height: 1.5; line-height: 1.5;
@@ -696,7 +642,6 @@
margin: 0; margin: 0;
gap: 0; gap: 0;
border-radius: var(--nodedc-radius-control); border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-panel-soft);
} }
.host-monitoring-hardware-facts dl > div { .host-monitoring-hardware-facts dl > div {
@@ -1277,16 +1222,6 @@ body {
white-space: nowrap; white-space: nowrap;
} }
.device-manager-overview-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.9rem;
}
.device-manager-overview-grid .nodedc-settings-card {
grid-column: 1 / -1;
}
.device-manager-capabilities { .device-manager-capabilities {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
@@ -1309,8 +1244,8 @@ body {
.device-inventory__filters { .device-inventory__filters {
display: grid; display: grid;
max-width: 620px; max-width: 960px;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.75rem; gap: 0.75rem;
} }
@@ -1319,7 +1254,6 @@ body {
gap: 0.75rem; gap: 0.75rem;
margin-top: 0.45rem; margin-top: 0.45rem;
padding-top: 1rem; padding-top: 1rem;
border-top: 1px solid var(--nodedc-glass-border);
} }
.device-inventory__section-heading { .device-inventory__section-heading {
@@ -1441,7 +1375,6 @@ body {
align-items: center; align-items: center;
gap: 0.9rem; gap: 0.9rem;
padding-bottom: 1rem; padding-bottom: 1rem;
border-bottom: 1px solid var(--nodedc-glass-border);
} }
.device-detail__identity { .device-detail__identity {
@@ -1604,7 +1537,6 @@ body {
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
gap: 0.55rem; gap: 0.55rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem; padding-top: 0.85rem;
} }
@@ -1640,7 +1572,6 @@ body {
display: grid; display: grid;
grid-template-columns: auto minmax(0, 1fr); grid-template-columns: auto minmax(0, 1fr);
gap: 0.35rem 0.7rem; gap: 0.35rem 0.7rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem; padding-top: 0.85rem;
color: var(--nodedc-text-secondary); color: var(--nodedc-text-secondary);
font-size: 0.65rem; font-size: 0.65rem;
@@ -1705,14 +1636,6 @@ body {
flex-direction: column; flex-direction: column;
} }
.device-manager-overview-grid {
grid-template-columns: 1fr;
}
.device-manager-overview-grid .nodedc-settings-card {
grid-column: auto;
}
.device-inventory-table__head { .device-inventory-table__head {
display: none; display: none;
} }
@@ -1750,3 +1673,10 @@ body {
} }
} }
/* Domain groups use the panel canvas; shared ResourceRow/SettingsCard own surfaces. */
.device-inventory__empty { min-height: 12rem; }
.device-manager-empty h3 { font-size: var(--nodedc-font-size-md); }
.device-control-disclosure__body { padding: var(--nodedc-space-4); color: var(--nodedc-text-secondary); }
.device-control-disclosure__body p { margin-top: 0; }
+10
View File
@@ -0,0 +1,10 @@
{
"schemaVersion": "nodedc.device-b2-foundation.v1",
"releaseId": "device-b2-foundation-v1-20260930-003",
"baselineReleaseId": "device-core-release-v1-r14-6ca6738bab22d0fdef714b90c68959363106ee5b",
"baselineSha256": "385c2fec8fce300cb80a93edfbcb0d537e34755b0ccc35294c0102b3c4a7f724",
"sqlSha256": "dc5608eccb8f628aab49390d245e6758505bb8a459a49705c375c3ca59b3e03b",
"transition": "add-private-vault-and-three-tables",
"runtime": "same-image-core-only",
"newPorts": false
}
+44
View File
@@ -0,0 +1,44 @@
begin;
-- One remote host identity per company. Project hosts are views of this source;
-- an imported credential never chooses the local company or project.
create table device_b2_hosts (
id uuid primary key,
owner_scope_id uuid not null references device_owner_scopes(id),
remote_host_id text not null,
endpoint text not null,
fingerprint text not null check (fingerprint ~ '^[a-f0-9]{64}$'),
integration_id text not null check (integration_id ~ '^[a-f0-9]{32}$'),
authority text not null check (authority in ('host','contours')),
secret_ref text not null,
revision bigint not null default 1,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
unique(owner_scope_id, remote_host_id),
unique(id, owner_scope_id)
);
create table device_b2_host_views (
host_id uuid not null,
project_id uuid not null,
owner_scope_id uuid not null,
source_id uuid not null,
primary key(host_id),
foreign key(host_id, project_id, owner_scope_id)
references device_infrastructure_hosts(id, project_id, owner_scope_id),
foreign key(source_id, owner_scope_id) references device_b2_hosts(id, owner_scope_id)
);
create table device_b2_contour_links (
source_id uuid not null,
contour_id text not null check (contour_id ~ '^[a-f0-9]{32}$'),
project_id uuid not null,
owner_scope_id uuid not null,
created_by_ref text not null,
created_at timestamptz not null default now(),
primary key(source_id, contour_id),
foreign key(source_id, owner_scope_id) references device_b2_hosts(id, owner_scope_id),
foreign key(project_id, owner_scope_id) references device_projects(id, owner_scope_id)
);
comment on table device_b2_hosts is 'nodedc.device-b2-foundation/v1';
comment on table device_b2_host_views is 'nodedc.device-b2-foundation/v1';
comment on table device_b2_contour_links is 'nodedc.device-b2-foundation/v1';
commit;
@@ -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;
+11
View File
@@ -0,0 +1,11 @@
services:
device-control-core:
environment:
DEVICE_B2_SECRET_ROOT: /run/nodedc-b2-connections
volumes:
- type: bind
source: /volume1/docker/nodedc-device-plane/private-b2-connections
target: /run/nodedc-b2-connections
read_only: false
bind:
create_host_path: false
+181
View File
@@ -0,0 +1,181 @@
# Shared ARNavi VPS and Device Core infrastructure
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
is a durable, multi-application receiver owned by
`NODEDC_MISSION_CORE_ARNAVI-VPS`. It is not an instance of that old Edge protocol.
Its TCP acknowledgement follows its own durable journal commit. Device Core
initiates all HTTPS requests; this integration adds no inbound Synology port.
## Operator workflow
1. Create a project host in Infrastructure / VPS and hosts, or use its existing
entry. Open the settings gear.
2. Import the connection package generated on the VPS. The package binds the
host identity, endpoint, exact TLS certificate fingerprint, OAuth application
identity and replaceable client credential.
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 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. 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.
A key shown by issuance is not retrievable later; losing it requires reissue.
Console and interface call the same VPS domain and provider routines. Only root
on the VPS can create the initial host administrator. Remote management cannot
promote a fleet application into a host administrator or revoke the current
host administrator. Host-key recovery uses the root console and package import.
## Local authority and ownership
A company has one `device_b2_hosts` connection per remote host identity.
`device_b2_host_views` exposes it through project infrastructure records.
`device_b2_contour_links` maps each remote contour to exactly one project in
that company. Access to a project never implies access to other project fleets.
The ordinary device read path filters links by authorized project before
requesting snapshots, including when its backend credential can administer the
whole remote host.
Global VPS management additionally requires company ownership authority from
Hub and the current project's infrastructure capability. Secret import,
issuance and revocation also require `credential.manage`. Browser visibility
is convenience only; all authority is checked by Core and then the VPS.
The connection secret lives behind an opaque reference in a dedicated directory
owned by the Core container UID, mode 0700; files are exclusive-created 0600,
fsynced and protected against symlinks. Back up that directory privately along
with Postgres. A failed DB transaction can leave an unreferenced secret file;
it is not automatically bound and must not be imported by scanning the folder.
## Protocol and credentials
Hydra owns OAuth issuance and validation. Device Core uses the pinned
`oauth4webapi` 3.8.8 implementation of client_credentials. A transport adapter
completes TLS and verifies the imported SHA-256 fingerprint before writing any
HTTP credential. It permits only public IPv4 endpoints, the imported origin,
`/oauth2/token` and `/v2/` routes, and never follows redirects or uses ambient
proxies. Raw Hydra administration remains loopback-only on the VPS.
A credential-issue request is reserved durably at the VPS before generation.
Replaying its ID does not mint a second credential or replay a saved secret.
If the response is lost, inspect current credentials, revoke the orphan if
necessary, and deliberately issue another key. Ordinary contour/application
creation is idempotent by its immutable human-readable key.
## Deployment boundary
The separate canonical `device-b2-foundation-v1.sql` migration only adds metadata
tables and constraints. It is applied by the registered foundation transition;
the ordinary application startup migration list remains unchanged. Activation also needs
one private Core mount and one environment path. This changes the current
release foundation and therefore requires a separate canonical deployment
transition before the normal commit-to-main release pipeline can accept it.
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.
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
The NAS accepted `device-b2-foundation-v1-20260930-003` at
2026-09-30T14:20:21Z (canonical applied journal 394), artifact SHA-256
`d3c365551aa0e984647b745aaba40ff356010c0e8956d36784130e4d80807aea`.
The root installer accepted the private vault and three tables with the same
Core image and preserved ports. The matching archive and backup
`device-b2-foundation-device-b2-foundation-v1-20260930-003-20260930-171850`
were independently checked through SMB. No repeat apply is needed.
The installed runner018 is SHA-256
`2a669d8a3313321c44212494518fe0c9e2c07caa802626599df3379839fbdcd9`,
published Platform commit `39a2239563de686d8a854627cae15339f1f2a4d9`.
CI pins that exact source so ordinary releases retain the accepted B2 mount
and migration receipt. The original failed002 remains in the failed journal;
its restored r14 baseline was proved by the separate metadata-only
reconciliation001 at14:15:19Z (journal393), without runtime or database writes.
Runner018 waits for readiness before taking its strict healthy snapshot;
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. 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
17 existing migrations, the new SQL, and the actual connection/link repository
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.
Работающее подключение не требует повторного импорта. Это отдельно от ключей
приложений внутри контуров; обновление доступа не устанавливает ПО на сервер.
+152 -21
View File
@@ -7,14 +7,85 @@ Device Core; other repositories keep their existing policy until onboarded.
## Current implementation status ## Current implementation status
The source qualification workflow is implemented in `.gitea/workflows/ci.yml`. As of 2026-09-30, the first automatic application release using the accepted
It does **not** deploy. The persistent Synology runner, deployment controller, network-priority override is r13/source
normal recurring release transition and live end-to-end acceptance are still `33cd08c7ab4b1ee87e8c943fca4a30f38c782aae`, accepted at09:25:33Z in canonical
pending. A green qualification is not a deployment receipt. ledger391 with archive SHA
`5fa322be2619ddfe2ad91f9e7d2c9d2cd1b3f8d91d34b7a2e5650eb9b617fc98`.
Backup:
`device-core-release-device-core-release-v1-r13-33cd08c7ab4b1ee87e8c943fca4a30f38c782aae-20260930-122207`.
Its predecessor was accepted r12; earlier r11/r12 remain canonical ledgers388/389.
Gitea qualification alone is not a deployment receipt.
Live inspection on 2026-09-29 found Gitea 1.27.2, Device Core Actions disabled The installed root runner015 has SHA
and no repo-level runners. The instance-wide runner list was not accessible `7a213b7d086225ac9677f52e1bde99dd4b57d77da7c548aadb11793336911cf2`,
with the current account (403); no conclusion about global runners is implied. from published Platform `50dc3b1a2cb1191484f5b90de2d2702b14127425`.
The operator confirmed its exact verify-install receipt and Python3.8.15.
Source qualification now pins this same Platform commit. The branch containing
that commit is `fix/device-core-network-priority-20260930`; the full SHA, not
its moving branch tip, remains the source identity.
Canonical metadata transition `device-core-network-priority-v1-20260930-002`
was accepted at09:12:12Z on30September (ledger390), archive SHA
`5ee23f440ef4a5ef7593c5c35b27b17d93d556453df69e152caee1ddd41e8c7b`.
Backup:
`device-core-network-priority-device-core-network-priority-v1-20260930-002-20260930-121204`.
Its plan identified the actual NAS Compose as `2.20.1-6047-g6817716`.
The installer proved unchanged running services, databases, volumes, ports and
secrets; it wrote only the exact descriptor and recurring-release Compose override.
The installed private primary network is now explicitly preferred for both Core
and Manager on future normal updates and their automatic rollback. NetworkMode,
all other configuration fields and runtime fingerprint v2 remain strict.
Run13 passed265 application tests,25 CI tests and170 artifact cases
(17 historical skips), then installed without manual NAS commands. Its before
snapshot names r12 and hashes the accepted override; canonical apply retained
strict runtime fingerprint v2, including both private primary networks.
The independent CI receipt, applied archive and unique journal record agree;
backup exists, lifecycle is terminal_success, with no failed record/warnings.
After installation, public GET health returned HTTP200 and all three health
flags true. The authenticated UI retained DC SUDO, DCTOUCH and
Robot2B — Moscow Trike Delivery. No user/device data was changed in this check.
This documentation update triggers the second ordered application release.
Its future result must be recorded in Ops and the Platform acceptance report;
this commit does not claim its own unobserved deployment succeeded.
Earlier r9 passed CI but failed Manager runtime-configuration acceptance and
successfully rolled back to r8. Its exact differing field was not retained, so
it remains unproven historical evidence. Runner013 introduced field-level hashes
before rollback. Subsequent work independently reproduced Compose's random
primary-network choice at equal priorities and corrected that contract. This
reproduction does not retroactively establish the precise r9 cause.
The first metadata plan001, under014, also exposed a parser coverage gap:
Compose emits a bare network endpoint as null. Version015 includes a regression
using full real Compose JSON, preserves exact raw config hashes and accepts only
the local null/empty-endpoint equivalence. Old001 was never applied and must not
be replayed. See Platform `infra/device-core-deploy/NETWORK_PRIORITY_20260930.md`.
The controller bootstrap was accepted on29September at18:35:52Z (ledger386),
artifact `device-core-autodeploy-v1-20260929-001`, SHA
`fe9298baa5f41a35c2705ee9946b730ff2de7d5b5c9b2b8eb1b4cca0bc8ed12b`.
Its baseline was r7/source `edf69068ec64e3d105d5324d39b8eaeface21215`;
run8 was the first eligible automatic run. Historical terminal runs are not replayed.
An actual Gitea API interruption before r8 reservation recovered without operator
intervention. Run10 failed in npm installation before creating an artifact.
Frozen dependency installation now retries at most three times for explicit
ECONNRESET/ETIMEDOUT/EAI_AGAIN only, with5/10second pauses; integrity, auth,
lockfile, other/mixed errors and test/build failures still fail immediately.
A real ECONNRESET in r12 recovered through that rule, then qualification and
installation passed. An exhausted install cannot produce a qualification receipt.
Pushes may originate from any computer. The Mac, SMB session, SSH session and
Worker006 are not dependencies of recurring delivery. The native outbound timer
runs30seconds after the previous cycle completes. The root-private read token,
SQLite queue and status live under `/var/lib/nodedc-device-autodeploy`, outside
build jobs and application artifacts. No extra inbound port was introduced.
The repo-scoped `synology-device-core-build` runner is id1. Its dependency pins
must all exist in their remotes: the initial Launcher failure was resolved by
publishing its exact existing commit without changing Launcher main or runtime.
Canonical receipts, archive digests, backups and separate product checks are
recorded in Ops DCPLATFORM-37; DCPLATFORM-21 defines the deployment contract.
The full historical report is Platform `infra/device-core-deploy/ACCEPTANCE_20260929.md`.
## Host and network ## Host and network
@@ -39,12 +110,19 @@ entry, branch policy, release contract and acceptance tests.
## Reproduce source qualification ## Reproduce source qualification
Runner label: `nodedc-node22-build`; Node 22.21.0, npm 10.9.4, Python >=3.9 and Runner label: `nodedc-node22-build`; Node 22.21.0, npm 10.9.4, Python >=3.9 and
Git must be available in the reviewed build image. The workflow does not Git must be available in the reviewed build image. The workflow fetches the
download third-party Actions. It fetches the exact pushed SHA from our Gitea. exact pushed SHA from our Gitea. After qualification it uses the upstream
Gitea-compatible `ChristopherHX/gitea-upload-artifact` v4 implementation
pinned to commit `81f940d004763f986ba3582c007fd842dd5cb0d7` to retain the bundle in **our Gitea**.
The upload uses the job's short-lived artifact credential, not a production
credential. The workflow's repository token has read-only content access.
`infra/ci/sources.lock.json` pins Design Guideline, Platform and Launcher to full commits; `infra/ci/sources.lock.json` pins Design Guideline, Platform and Launcher to full commits;
following their current `main` branches would make old releases unreproducible. following their current `main` branches would make old releases unreproducible.
Launcher sources are required by the existing Hub trust/session artifact tests; Launcher sources are required by the existing Hub trust/session artifact tests;
the Launcher application is not installed or deployed by this workflow. the Launcher application is not installed or deployed by this workflow.
Every pinned commit must be published to its declared remote before a Device
Core revision depending on it is pushed. A local checkout passing tests does
not prove that a clean Linux worker can fetch its dependencies.
Dependencies are fetched into fresh sibling directories. Existing directories Dependencies are fetched into fresh sibling directories. Existing directories
are rejected, never reset or deleted by the qualification script. are rejected, never reset or deleted by the qualification script.
@@ -64,15 +142,36 @@ hashes and the UI output hash. It contains `deployed: false` deliberately.
The qualification report is evidence, not an authorization token or substitute The qualification report is evidence, not an authorization token or substitute
for independently checking Gitea job identity and the deploy artifact. for independently checking Gitea job identity and the deploy artifact.
`infra/ci/package_release.py` runs only after all qualification steps pass. It
checks the source and build hashes again, then emits a deterministic `.tgz`
and `release.json` receipt. The archive declares `device-core-release.v1` with
the exact source SHA, run id/number and file digests. It cannot choose Compose
files, host roots, install commands or database operations. This artifact
type is accepted only by the registered Platform recurring-release domain.
Run 3 (commit `415d5e73d7ca0cc283deb9b79a9f5f99fec54ed7`) passed all
qualification steps on Synology. Its legacy v3 upload succeeded but is not
returned by the Gitea REST artifact API. Therefore the publication step now
uses the Gitea-compatible v4 uploader; successful REST retrieval and digest
verification are separate acceptance gates.
Bundles remain in Gitea for 30 days; installed releases will additionally be
retained by the canonical NAS journal/archive. Expiry is not a successful
deployment and must never be silently ignored by the controller.
Linux qualification also exercises the standalone Edge/VPS archive readers.
These materialize validated regular files explicitly, without `extractall`,
so they work with the pinned image's Python while retaining path/link/mode
checks. No Edge/VPS runtime is changed by running these tests.
Local focused tests: `python3 -m unittest discover -s infra/ci -p 'test_*.py'`. Local focused tests: `python3 -m unittest discover -s infra/ci -p 'test_*.py'`.
The full artifact suite belongs on the bounded Linux build worker; there is no The full artifact suite belongs on the bounded Linux build worker; there is no
requirement to start Docker or run load tests on an operator Mac. requirement to start Docker or run load tests on an operator Mac.
## Production activation contract still to implement ## Installed production contract
1. Verify the installed runner digest, applied journals, current manager/core 1. The root installer verifies its installed identity, applied journals, current
release descriptors and preserved runtime state on Synology. manager/core release descriptors and preserved runtime state on Synology.
2. Introduce a versioned **normal update** transition for repeat releases. 2. The versioned **normal update** transition handles repeat releases.
Historical recovery descriptors and fixed predecessor guards remain intact. Historical recovery descriptors and fixed predecessor guards remain intact.
Reusing the v13 manager or v4 core recovery identity is not a CI strategy. Reusing the v13 manager or v4 core recovery identity is not a CI strategy.
3. Persist each admitted `main` revision, run identity and artifact digest in a 3. Persist each admitted `main` revision, run identity and artifact digest in a
@@ -82,13 +181,15 @@ requirement to start Docker or run load tests on an operator Mac.
4. Link exact source commits to immutable data-only deploy artifacts. Retain 4. Link exact source commits to immutable data-only deploy artifacts. Retain
existing `manifest.env`, `files.txt`, `payload/...` validation and fixed existing `manifest.env`, `files.txt`, `payload/...` validation and fixed
component/service selection. Exclude secrets, DB state and executable hooks. component/service selection. Exclude secrets, DB state and executable hooks.
5. Under the deploy lock, check the current predecessor, obtain and validate a 5. Obtain a fresh canonical plan, reserve the verified artifact in the durable
fresh canonical plan, then apply that exact digest automatically. Record queue, then apply with predecessor and payload checks under the deploy lock. Record
commit, run, artifact, plan, receipt and backup. The controller's allowlist commit, run, artifact, plan, receipt and backup. The controller's allowlist
is root-owned and cannot be expanded by a workflow artifact. is root-owned and cannot be expanded by a workflow artifact.
6. Before activation verify push success, failed tests, wrong SHA/repo/branch, 6. Source tests cover wrong SHA/repo/branch, failed/pending checks, duplicate
duplicate events, overlapping pushes, restart recovery and failed-health events, pagination changes, overlapping runs, restart reconciliation and
rollback. Verify that no new host ports or production mounts are exposed. canonical rollback. Bootstrap acceptance proves timer identity, private token
import and unchanged existing applications. Live automatic release acceptance
is recorded separately in Ops; unit tests alone do not prove NAS delivery.
Build/test failures leave production untouched. Runtime installation failures Build/test failures leave production untouched. Runtime installation failures
follow the canonical runner's rollback policy; an ambiguous or failed rollback follow the canonical runner's rollback policy; an ambiguous or failed rollback
@@ -97,9 +198,12 @@ deployed. User/device data and tokens survive application updates.
## Operator view ## Operator view
Normal use after activation: push to `main`, then watch Gitea **Actions**. Normal use: push to `main`, then watch Gitea **Actions** for qualification.
Deployment status must separately show the installed commit and receipt. A red `/volume1/docker/nodedc-device-autodeploy/runtime-status.json` is a sanitized
check means the candidate did not qualify; it must not show a green deploy. controller observation available through the existing SMB share. Canonical
`nodedc-deploy/state/applied.jsonl`, its matching archive and backup establish the
installed release. A waiting status does not replace the latest applied receipt.
A red qualification means the candidate did not qualify; it is not a deployment.
For emergency pause, stop admitting new deployments without cancelling an For emergency pause, stop admitting new deployments without cancelling an
in-progress apply. Recovery/rollback remains a recorded canonical transition. in-progress apply. Recovery/rollback remains a recorded canonical transition.
@@ -109,3 +213,30 @@ This deployment mechanism does not mix Device Core and Mission Core inventories.
References: [Gitea Actions](https://docs.gitea.com/usage/actions/overview/), References: [Gitea Actions](https://docs.gitea.com/usage/actions/overview/),
[runner configuration](https://docs.gitea.com/runner/configuration/). [runner configuration](https://docs.gitea.com/runner/configuration/).
## Release ordering and interruptions
Each successful main push keeps its own source SHA and CI run identity. A pending
older run holds the delivery queue; a later successful run cannot overtake it.
After a clean CI failure, the next qualified revision may proceed. Multiple
pushes are therefore admitted in order, including pushes from different machines.
The build runner and production installer each execute one job at a time.
A network outage before installation retains the queued candidate. Before apply,
the controller records its reservation in SQLite. After restart it reconciles
that reservation with the canonical journal, archive checksum and backup. A
confirmed applied release is never installed again. A confirmed rollback is
terminal for that artifact; a new corrected commit gets a new release identity.
An uncertain outcome or failed rollback blocks later installs for diagnosis.
The installed revision must be an ancestor of the candidate, and the candidate
must remain an ancestor of current main. Divergent/force-pushed history does not
silently replace production. CI artifacts expire after30days; an expired artifact
raises an explicit source error rather than being credited as delivered. Keep
qualified artifacts available until delivery has a canonical receipt.
The sanitized status file can return to `waiting` after delivery. Read the latest
matching `device-core-release` row in the canonical applied journal to identify
the installed source; do not infer deployment solely from a green CI run or from
a single polling status. Infrastructure changes, schema migrations and another
repository's onboarding still require their own registered deployment contract.
+40
View File
@@ -0,0 +1,40 @@
# Device Core: UI and UX contract
Device Core remains a separate application with its own companies, projects,
device registry, infrastructure, access rules and management functions. Mission
Core is the reference for interaction and presentation, not its domain model.
The existing home video and media configuration are preserved.
## Components
Consume the pinned NODEDC_DESIGN_GUIDELINE packages. Use ResourceRow for
registries, FeatureSettingsWindow for entity settings, SettingsCard for coherent
forms, and canonical controls and status indicators. Domain wrappers only arrange
these exports; they must not reproduce their visual styles. Avoid nested canvas
surfaces. Keep refresh beside close in the window header. Expand related items
in place instead of replacing the settings page with a back-navigation stack.
## VPS and projects
Existing Device Core projects are the list shown under a VPS. Connecting a
project requests a contour on that VPS using a stable project-derived identity,
then saves the link. Retries reuse that identity. No second project registry is
created. Explicit linking is available for a pre-existing remote contour.
Applications and their keys expand under their project. Creating an application
requires its human-readable name only. Device Core generates its technical ID;
VPS generates the credential. A lost response retains the same creation request
ID in the open form. The status refresh exposes partially completed issuance;
use explicit reissue when a one-time secret was lost. Key IDs are public IDs,
never secrets. Issued means a credential exists, not that the client is online.
Legacy Mission Core access is visible as a compatible connection.
## Acceptance
- Check all five application sections and their empty, populated and error states.
- Verify project switches retain the selected section while clearing entity state.
- Verify project, host, contour and credential isolation with unauthorized actors.
- Verify inline expansion, keyboard focus, Escape, top refresh and narrow layouts.
- Verify the existing home video/media survives releases.
- Full B2 command/settings parity remains a distinct domain integration task;
a UI release or successful deployment must not be recorded as its completion.
+42
View File
@@ -0,0 +1,42 @@
# Device Core · Mission Core visual reference
Reference inspected in the running Mission Core on 2026-09-30: environment
settings; VPS settings; B2 identity, connection, commands, firmware and every
profile section. The actual application is authoritative for appearance; its
rover domain is not imported into Device Core.
The shared `appearance: "mission"` profile lives in Design Guideline/ui-core.
Device Core applies it on documentElement so portals inherit it. Existing Window,
FeatureSettingsWindow, SettingsCard, ResourceRow, Select, Button and StatusBadge
remain the component source. No application-local replica of the modal is added.
Reference measurements in dark mode: modal rgba(15,15,17,.97), radius28px,
plain avatar, selected navigation rgba(247,248,244,.14), control height46px,
settings-card padding16px, status dot6.72px. The material rim and gradient are
removed from this opt-in profile. Light mode keeps the same neutral hierarchy.
Other applications retain their previous appearance unless opting in.
| Surface | Device Core behavior |
| --- | --- |
| B2 inventory | terminal and gear at right; no redundant registered badge |
| B2 settings | persistent left navigation, identity, connection, commands, firmware,86parameters |
| VPS settings | same window; project contours expand inline; refresh at top |
| Keys | application belongs to expanded project contour; server generates identity |
| Project switch | retained active application section; no foreign project device window |
| Product model | company/project permissions remain Device Core's |
| Overview | existing yellow video retained |
Network settings go through the VPS product API documented in the server repo's
TRACKER_SETTINGS_API.md. The backend checks capability, linked project/contour and
server identity. Unknown/private configuration records and recovery endpoint are
preserved. Saving a portable profile is separate from applying it to a tracker.
The web app has no connection to the operator's local USB. USB provisioning stays
in local Mission Core; new network-reachable devices support initial config read
with their installed firmware and configuration password. Firmware controls match
the reference archive/import/download scope; no network flashing is advertised.
Validation: Device Core TypeScript/production build,286server/application tests,
15B2permission/transport tests; VPS298tests; Mission Core71compatibility tests.
Live deployment and UI acceptance are recorded in Ops MISSIONCOR-86 after release;
these local results are not a production acceptance claim.
+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
закрывают настройки целиком. Переключение вкладок сохраняет выбор команды,
фильтр и идентификатор незавершённой отправки; возврат обновляет журнал.
Кнопка обновления в шапке на вкладке команд обновляет журнал и состояние трекера.
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Produce a deterministic data-only release from the exact qualified checkout."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path, PurePosixPath
import re
import stat
import tarfile
import qualify
ENTRY = "deployment/device-core-release-v1.json"
ENTRIES = (
".dockerignore", "package.json", "package-lock.json",
"packages/device-protocol-contract", "packages/device-edge-channel-contract",
"packages/infrastructure-telemetry-contract", "services/device-control-core",
"services/device-manager", ENTRY,
)
STEPS = [
"design-install", "design-core", "design-react", "device-install",
"unit-tests", "ci-contract", "build", "artifact-contracts",
]
EXCLUDED = {"node_modules", ".git", ".DS_Store", "test", "__pycache__"}
DENIED = {"secrets", "credentials", "runtime", "runtime-data", "uploads", "logs", "data"}
def encoded(value):
return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode()
def source_files(path, destination):
"""Do not traverse ignored trees; reject links and unexpected state elsewhere."""
result = {}
mode = path.lstat()
if stat.S_ISLNK(mode.st_mode) or (stat.S_ISREG(mode.st_mode) and mode.st_nlink != 1):
raise ValueError("linked_source:" + destination)
if stat.S_ISDIR(mode.st_mode):
for child in sorted(path.iterdir()):
name = child.name
if name in EXCLUDED or name.endswith((".test.mjs", ".map", ".tsbuildinfo")):
continue
if name in DENIED or name.startswith((".env", "._")) or name.endswith((".pem", ".key", ".sqlite", ".db", ".log")):
raise ValueError("runtime_source_rejected:" + destination + "/" + name)
result.update(source_files(child, destination + "/" + name))
elif stat.S_ISREG(mode.st_mode):
if mode.st_size > 16 * 1024 * 1024:
raise ValueError("oversized_source:" + destination)
result[destination] = path.read_bytes()
else:
raise ValueError("nonregular_source:" + destination)
return result
def packaged_dist_digest(files):
digest = hashlib.sha256()
prefix = "services/device-manager/dist/"
for path, data in sorted(files.items()):
if path.startswith(prefix):
name = path[len(prefix):].encode()
digest.update(len(name).to_bytes(8, "big") + name)
digest.update(len(data).to_bytes(8, "big") + data)
return digest.hexdigest()
def bundle(root, report, run_id, run_number):
if type(run_id) is not int or type(run_number) is not int or not 0 < run_id < 2**53 or not 0 < run_number < 2**53:
raise ValueError("invalid_run_identity")
commit = report.get("sourceCommit", "")
if not re.fullmatch(r"[0-9a-f]{40}", commit):
raise ValueError("invalid_source_commit")
lock = qualify.read_lock(root)
if (report.get("schema") != "nodedc.device-core.qualification.v1"
or report.get("status") != "qualified" or report.get("deployed") is not False
or report.get("steps") != STEPS or report.get("sources") != lock):
raise ValueError("qualification_required")
for name, path in (
("sourceLockSha256", root / "infra/ci/sources.lock.json"),
("packageLockSha256", root / "package-lock.json"),
):
if report.get(name) != hashlib.sha256(path.read_bytes()).hexdigest():
raise ValueError("qualification_source_changed:" + name)
if report.get("managerDistSha256") != qualify.tree_digest(root / "apps/device-manager/dist"):
raise ValueError("qualified_dist_changed")
files = {}
for entry in ENTRIES[:-2]:
files.update(source_files(root / entry, entry))
for source, target in (
("services/device-manager/Dockerfile", "services/device-manager/Dockerfile"),
("apps/device-manager/server", "services/device-manager/server"),
("apps/device-manager/dist", "services/device-manager/dist"),
):
files.update(source_files(root / source, target))
if sum(map(len, files.values())) > 64 * 1024 * 1024:
raise ValueError("release_too_large")
release_id = "device-core-release-v1-r" + str(run_id) + "-" + commit
descriptor = {
"schemaVersion": "nodedc.device-core.release.v1",
"releaseId": release_id,
"repository": "SILVER/NODEDC_DEVICE_CORE",
"repositoryId": 38,
"branch": "main",
"sourceCommit": commit,
"runId": run_id,
"runNumber": run_number,
"qualification": report,
"packagedManagerDistSha256": packaged_dist_digest(files),
"filesSha256": {name: hashlib.sha256(value).hexdigest() for name, value in sorted(files.items())},
}
files[ENTRY] = encoded(descriptor)
members = {
"manifest.env": ("id=" + release_id + "\ncomponent=device-core-release\ntype=app-overlay\n").encode(),
"files.txt": ("\n".join(ENTRIES) + "\n").encode(),
**{"payload/" + name: value for name, value in files.items()},
}
output = io.BytesIO()
with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode="w", format=tarfile.PAX_FORMAT) as archive:
directories = {"payload"}
for name in members:
directories.update(str(p) for p in PurePosixPath(name).parents if str(p) != ".")
for name in sorted(directories):
info = tarfile.TarInfo(name)
info.type, info.mode = tarfile.DIRTYPE, 0o755
archive.addfile(info)
for name, value in sorted(members.items()):
info = tarfile.TarInfo(name)
info.mode, info.size = 0o644, len(value)
archive.addfile(info, io.BytesIO(value))
return release_id, output.getvalue()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--report", type=Path, required=True)
parser.add_argument("--run-id", type=int, required=True)
parser.add_argument("--run-number", type=int, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args()
root = Path(__file__).resolve().parents[2]
report = json.loads(args.report.read_text())
qualify.verify_sources(root, report["sourceCommit"], qualify.read_lock(root))
output = args.output_dir.resolve()
for checkout in (root, *(root.parent / name for name in qualify.DEPENDENCIES)):
if output == checkout or checkout in output.parents:
raise ValueError("release_output_must_be_outside_sources")
identity, data = bundle(root, report, args.run_id, args.run_number)
output.mkdir(parents=True, exist_ok=True)
path = output / ("nodedc-" + identity + ".tgz")
with path.open("xb") as stream:
stream.write(data)
receipt = {"artifact": path.name, "sha256": hashlib.sha256(data).hexdigest(),
"sourceCommit": report["sourceCommit"], "runId": args.run_id,
"runNumber": args.run_number, "deployed": False}
with (output / "release.json").open("xb") as stream:
stream.write(encoded(receipt))
print(json.dumps(receipt))
if __name__ == "__main__":
main()
+45 -1
View File
@@ -7,8 +7,11 @@ import json
import os import os
from pathlib import Path from pathlib import Path
import re import re
import shutil
import subprocess import subprocess
import sys import sys
import tempfile
import time
SHA = re.compile(r"[0-9a-f]{40}") SHA = re.compile(r"[0-9a-f]{40}")
@@ -19,15 +22,50 @@ DEPENDENCIES = {
} }
def run(args, cwd, capture=False): def run(args, cwd, capture=False, capture_errors=False):
return subprocess.run( return subprocess.run(
args, cwd=cwd, check=True, text=True, args, cwd=cwd, check=True, text=True,
stdout=subprocess.PIPE if capture else None, stdout=subprocess.PIPE if capture else None,
stderr=subprocess.STDOUT if capture_errors else None,
env={**os.environ, "GIT_TERMINAL_PROMPT": "0", "CI": "true", env={**os.environ, "GIT_TERMINAL_PROMPT": "0", "CI": "true",
"NODEDC_LAUNCHER_REPO": str(Path(__file__).resolve().parents[3] / "NODEDC_LAUNCHER")}, "NODEDC_LAUNCHER_REPO": str(Path(__file__).resolve().parents[3] / "NODEDC_LAUNCHER")},
).stdout ).stdout
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:
output = run(command, cwd, capture=True, capture_errors=True)
except subprocess.CalledProcessError as error:
output = error.output or ""
print(output, end="", flush=True)
codes = set(re.findall(r"^npm (?:error|ERR!) code ([A-Z][A-Z0-9_]*)\s*$",
output, re.MULTILINE))
if attempt == 3 or not codes or not codes.issubset(transient):
raise
print("ci_dependency_retry=" + str(attempt) + ";codes=" + ",".join(sorted(codes)), flush=True)
time.sleep(5 * attempt)
else:
print(output or "", end="", flush=True)
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): def read_lock(root):
lock = json.loads((root / "infra/ci/sources.lock.json").read_text()) lock = json.loads((root / "infra/ci/sources.lock.json").read_text())
if lock.get("schema") != "nodedc.device-core.ci-sources.v1": if lock.get("schema") != "nodedc.device-core.ci-sources.v1":
@@ -126,6 +164,12 @@ def qualify(root, commit, lock, report):
completed = [] completed = []
for name, cwd, command in steps: for name, cwd, command in steps:
print("ci_step=" + name, flush=True) 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) run(command, cwd)
completed.append(name) completed.append(name)
verify_sources(root, commit, lock) verify_sources(root, commit, lock)
+2 -2
View File
@@ -5,7 +5,7 @@
"dependencies": { "dependencies": {
"NODEDC_DESIGN_GUIDELINE": { "NODEDC_DESIGN_GUIDELINE": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git", "url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"commit": "1b63366d2e7a911e18a293d30cddb0c95e0ba653" "commit": "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2"
}, },
"NODEDC_LAUNCHER": { "NODEDC_LAUNCHER": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git", "url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
@@ -13,7 +13,7 @@
}, },
"platform": { "platform": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git", "url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
"commit": "11b73e64681f83aa2ebfd89ef266d3be2869f7e1" "commit": "27c155276a703dd4fd39385011fc5e3f86afcae4"
} }
} }
} }
+132
View File
@@ -0,0 +1,132 @@
import hashlib
import io
import json
import os
from pathlib import Path
import tarfile
import tempfile
import unittest
import package_release as release
import qualify
class ReleaseTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
lock = qualify.read_lock(Path(__file__).resolve().parents[2])
self.write("infra/ci/sources.lock.json", json.dumps(lock))
for name in (".dockerignore", "package.json", "package-lock.json",
"services/device-manager/Dockerfile", "apps/device-manager/server/app.mjs",
"apps/device-manager/dist/index.html", "services/device-control-core/src/app.mjs",
"packages/device-protocol-contract/package.json",
"packages/device-edge-channel-contract/package.json",
"packages/infrastructure-telemetry-contract/package.json"):
self.write(name, "fixture")
self.report = {
"schema": "nodedc.device-core.qualification.v1", "status": "qualified",
"deployed": False, "steps": release.STEPS, "sources": lock,
"sourceCommit": "a" * 40,
"sourceLockSha256": self.digest("infra/ci/sources.lock.json"),
"packageLockSha256": self.digest("package-lock.json"),
"managerDistSha256": qualify.tree_digest(self.root / "apps/device-manager/dist"),
}
def write(self, path, value):
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(value)
return target
def digest(self, path):
return hashlib.sha256((self.root / path).read_bytes()).hexdigest()
def build(self):
return release.bundle(self.root, self.report, 14, 9)
def test_exact_deterministic_payload_without_runtime_authority(self):
identity, first = self.build()
os.utime(self.root / "apps/device-manager/server/app.mjs", (100, 100))
self.assertEqual(first, self.build()[1])
with tarfile.open(fileobj=io.BytesIO(first), mode="r:gz") as archive:
names = archive.getnames()
self.assertEqual(archive.extractfile("files.txt").read().decode().splitlines(), list(release.ENTRIES))
descriptor = json.load(archive.extractfile("payload/" + release.ENTRY))
self.assertEqual(descriptor["releaseId"], identity)
self.assertEqual(descriptor["runId"], 14)
self.assertEqual(descriptor["runNumber"], 9)
self.assertEqual(descriptor["repositoryId"], 38)
for member in archive.getmembers():
self.assertTrue(member.isfile() or member.isdir())
self.assertEqual(member.mtime, 0)
self.assertEqual(member.uid, 0)
files = descriptor["filesSha256"]
for name, digest in files.items():
self.assertEqual(hashlib.sha256(archive.extractfile("payload/" + name).read()).hexdigest(), digest)
self.assertIn("payload/services/device-manager/server/app.mjs", names)
self.assertFalse(any("compose" in name or (name.startswith("payload/") and name.endswith(".env")) for name in names))
def test_packaged_ui_digest_covers_served_files_without_source_maps(self):
self.write("apps/device-manager/dist/assets/app.js", "code")
self.write("apps/device-manager/dist/assets/app.js.map", "source map")
self.report["managerDistSha256"] = qualify.tree_digest(self.root / "apps/device-manager/dist")
with tarfile.open(fileobj=io.BytesIO(self.build()[1]), mode="r:gz") as archive:
descriptor = json.load(archive.extractfile("payload/" + release.ENTRY))
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
prefix = "payload/services/device-manager/dist/"
for member in archive:
if member.isfile() and member.name.startswith(prefix):
path = root / member.name[len(prefix):]
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(archive.extractfile(member).read())
self.assertFalse(any(p.suffix == ".map" for p in root.rglob("*")))
self.assertEqual(descriptor["packagedManagerDistSha256"], qualify.tree_digest(root))
self.assertNotEqual(descriptor["packagedManagerDistSha256"], self.report["managerDistSha256"])
def test_incomplete_or_forged_qualification_rejected(self):
for key, value in [("status", "failed"), ("deployed", True), ("steps", release.STEPS[:-1]),
("sourceCommit", "../main"), ("sources", {}), ("packageLockSha256", "0" * 64)]:
with self.subTest(key=key):
previous = self.report[key]
self.report[key] = value
with self.assertRaises(ValueError): self.build()
self.report[key] = previous
def test_dist_modified_after_tests_rejected(self):
self.write("apps/device-manager/dist/index.html", "changed")
with self.assertRaisesRegex(ValueError, "qualified_dist_changed"): self.build()
def test_source_symlink_rejected(self):
(self.root / "services/device-control-core/src/escape").symlink_to("/etc/passwd")
with self.assertRaisesRegex(ValueError, "linked_source"): self.build()
def test_hardlink_rejected(self):
os.link(self.root / "package.json", self.root / "services/device-control-core/src/linked")
with self.assertRaisesRegex(ValueError, "linked_source"): self.build()
def test_runtime_files_rejected_instead_of_bundled(self):
for name in [".env.production", "secrets/key", "data/device.json", "local.pem", "snapshot.db"]:
with self.subTest(name=name):
target = self.write("services/device-control-core/" + name, "private-fixture")
with self.assertRaisesRegex(ValueError, "runtime_source_rejected"): self.build()
target.unlink()
if target.parent.name in release.DENIED: target.parent.rmdir()
def test_tests_and_dependencies_not_in_runtime_bundle(self):
self.write("services/device-control-core/test/example.mjs", "test")
self.write("services/device-control-core/node_modules/lib/index.mjs", "dependency")
self.write("apps/device-manager/server/app.test.mjs", "test")
with tarfile.open(fileobj=io.BytesIO(self.build()[1]), mode="r:gz") as archive:
self.assertFalse(any("test" in name or "node_modules" in name for name in archive.getnames()))
def test_run_identity_strict(self):
for value in [True, 0, -1, "1", 2**53]:
with self.subTest(value=value):
with self.assertRaises(ValueError): release.bundle(self.root, self.report, value, 1)
if __name__ == "__main__":
unittest.main()
+80
View File
@@ -1,5 +1,7 @@
import importlib.util import importlib.util
import io
import json import json
from contextlib import redirect_stdout
from pathlib import Path from pathlib import Path
import subprocess import subprocess
import tempfile import tempfile
@@ -107,6 +109,84 @@ class QualificationTests(unittest.TestCase):
CI.qualify(self.root, self.commit, {}, report) CI.qualify(self.root, self.commit, {}, report)
self.assertEqual(json.loads(report.read_text())["sourceCommit"], "old") self.assertEqual(json.loads(report.read_text())["sourceCommit"], "old")
def test_network_install_error_recovers_using_the_same_frozen_command(self):
failure = subprocess.CalledProcessError(152, "npm", output="npm error code ECONNRESET\n")
with mock.patch.object(CI, "run", side_effect=[failure, "installed\n"]) as execute, \
mock.patch.object(CI.time, "sleep") as pause, redirect_stdout(io.StringIO()):
CI.install_dependencies(self.root)
self.assertEqual(execute.call_count, 2)
self.assertEqual(execute.call_args_list[0], execute.call_args_list[1])
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",
"npm error code ECONNRESET\nnpm error code E403\n", ""):
with self.subTest(output=output), mock.patch.object(
CI, "run", side_effect=subprocess.CalledProcessError(1, "npm", output=output)
) as execute, mock.patch.object(CI.time, "sleep") as pause, redirect_stdout(io.StringIO()):
with self.assertRaises(subprocess.CalledProcessError):
CI.install_dependencies(self.root)
execute.assert_called_once()
pause.assert_not_called()
def test_install_retries_are_bounded_and_do_not_publish_a_report(self):
report = self.root.parent / "result.json"
failure = subprocess.CalledProcessError(1, "npm", output="npm error code ETIMEDOUT\n")
with mock.patch.object(CI, "verify_sources"), mock.patch.object(
CI, "run", side_effect=["v22.21.0\n", "10.9.4\n", failure, failure, failure]
) as execute, mock.patch.object(CI.time, "sleep") as pause, redirect_stdout(io.StringIO()):
with self.assertRaises(subprocess.CalledProcessError):
CI.qualify(self.root, self.commit, {"node": "v22.21.0", "npm": "10.9.4"}, report)
self.assertEqual(execute.call_count, 5)
self.assertEqual(pause.call_args_list, [mock.call(5), mock.call(10)])
self.assertFalse(report.exists())
def test_build_failure_is_not_retried_as_an_install(self):
report = self.root.parent / "result.json"
failure = subprocess.CalledProcessError(1, "npm", output="npm error code ECONNRESET\n")
with mock.patch.object(CI, "verify_sources"), mock.patch.object(
CI, "run", side_effect=["v22.21.0\n", "10.9.4\n", "installed\n", failure]
) as execute, mock.patch.object(CI.time, "sleep") as pause, redirect_stdout(io.StringIO()):
with self.assertRaises(subprocess.CalledProcessError):
CI.qualify(self.root, self.commit, {"node": "v22.21.0", "npm": "10.9.4"}, report)
self.assertEqual(execute.call_count, 4)
pause.assert_not_called()
self.assertFalse(report.exists())
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Build the three-file, secret-free canonical B2 foundation artifact."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT = Path(__file__).resolve().parents[2]
ENTRIES = ('docker-compose.device-b2-foundation.yml', 'deployment/device-b2-foundation-v1.sql',
'deployment/device-b2-foundation-v1.json')
IDENTITY = 'device-b2-foundation-v1-20260930-003'
SQL_SHA = 'dc5608eccb8f628aab49390d245e6758505bb8a459a49705c375c3ca59b3e03b'
def build(destination):
files = {name: (ROOT / name).read_bytes() for name in ENTRIES}
descriptor = json.loads(files[ENTRIES[2]])
if descriptor['releaseId'] != IDENTITY or descriptor['sqlSha256'] != SQL_SHA or hashlib.sha256(files[ENTRIES[1]]).hexdigest() != SQL_SHA:
raise ValueError('foundation identity or SQL digest mismatch')
payload = {'manifest.env': f'id={IDENTITY}\ncomponent=device-b2-foundation\ntype=app-overlay\n'.encode(),
'files.txt': ('\n'.join(ENTRIES)+'\n').encode(), **{'payload/'+p:v for p,v 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=len(data);member.mode=0o644;member.mtime=0
archive.addfile(member,io.BytesIO(data))
return {'component':'device-b2-foundation','id':IDENTITY,'artifact':str(destination),
'sha256':hashlib.sha256(destination.read_bytes()).hexdigest(),'entries':ENTRIES,
'services':['device-control-core'],'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,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,39 @@
// Real application handlers; only external dependencies are replaced in this fixture.
import { createControlCoreApp } from "../../services/device-control-core/src/app.mjs";
import { createDeviceManagerServer } from "../../apps/device-manager/server/device-manager-server.mjs";
const servers = [];
const urls = {};
for (const mode of ["healthy", "database", "discovery", "management", "transport", "auth", "coreClient"]) {
const core = createControlCoreApp({
repository: {
health: async () => mode === "database" ? "unavailable" : "ready",
upsertQuarantineDiscovery() {}, acceptAdapterMessage() {}, executeManagementCommand() {},
},
gatewayToken: "fixture-only-".repeat(4), identifierPepper: "fixture-only-".repeat(4),
managementToken: "fixture-only-".repeat(4),
discoveryIngestEnabled: mode !== "discovery", managementApiEnabled: mode !== "management",
gatewayIngest: { observeDiscovery() {}, acceptMessage() {} },
typedCommandRuntime: mode === "transport" ? null : { planServicePing() {}, status() {} },
edgeChannelStatusProvider: () => ({ enabled: true, configured: 1, accepted: 1, degraded: 0 }),
});
const manager = createDeviceManagerServer({
auth: { authRequired: mode !== "auth", authorize() {} },
coreClient: { configured: mode !== "coreClient", listProjects() {} },
presentationStore: {},
});
urls[mode] = [];
for (const server of [core, manager]) {
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
servers.push(server);
urls[mode].push(`http://127.0.0.1:${server.address().port}/healthz`);
}
}
process.stdout.write(JSON.stringify(urls) + "\n");
process.stdin.resume();
process.stdin.on("end", async () => {
await Promise.all(servers.map(server => new Promise(resolve => server.close(resolve))));
});
+36 -1
View File
@@ -550,6 +550,41 @@ def validate_payload(payload: Path, phase: str):
return descriptor return descriptor
def extract_validated_files(archive, extraction_root):
"""Materialize only regular data, also on Python before tar filters existed."""
if extraction_root.is_symlink() or not extraction_root.is_dir() or any(extraction_root.iterdir()):
die("artifact extraction requires an empty private directory")
root = extraction_root.resolve(strict=True)
members = archive.getmembers()
if len(members) > 65536 or sum(item.size for item in members) > MAX_ARTIFACT_BYTES:
die("artifact expanded size/count rejected")
normalized = set()
files = set()
for member in members:
safe_tar_member(member)
path = PurePosixPath(member.name)
name = path.as_posix()
if member.name.rstrip("/") != name or name in normalized:
die("artifact contains noncanonical or duplicate paths")
normalized.add(name)
if member.isfile():
files.add(name)
for member in members:
if any(str(parent) in files for parent in PurePosixPath(member.name).parents):
die("artifact file is used as a directory")
# All members are checked before any output. Never apply archive ownership,
# links, devices or special mode bits; never invoke extract/extractall.
for member in members:
destination = root.joinpath(*PurePosixPath(member.name).parts)
if member.isdir():
destination.mkdir(parents=True, exist_ok=True, mode=0o755)
else:
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
with archive.extractfile(member) as source, destination.open("xb") as output:
shutil.copyfileobj(source, output)
destination.chmod(0o755 if member.mode & 0o111 else 0o644)
def load_artifact(artifact: Path, extraction_root: Path): def load_artifact(artifact: Path, extraction_root: Path):
artifact = artifact.resolve(strict=True) artifact = artifact.resolve(strict=True)
if artifact.parent != INBOX_ROOT.resolve(strict=True): if artifact.parent != INBOX_ROOT.resolve(strict=True):
@@ -570,7 +605,7 @@ def load_artifact(artifact: Path, extraction_root: Path):
die("artifact top-level contract is incomplete") die("artifact top-level contract is incomplete")
if any(name.split("/", 1)[0] not in required for name in seen): if any(name.split("/", 1)[0] not in required for name in seen):
die("artifact contains an unexpected top-level member") die("artifact contains an unexpected top-level member")
archive.extractall(extraction_root, filter="data") extract_validated_files(archive, extraction_root)
manifest = parse_manifest( manifest = parse_manifest(
(extraction_root / "manifest.env").read_text(encoding="utf-8") (extraction_root / "manifest.env").read_text(encoding="utf-8")
+36 -1
View File
@@ -228,6 +228,41 @@ def safe_tar_member(member: tarfile.TarInfo):
die("artifact contains AppleDouble metadata") die("artifact contains AppleDouble metadata")
def extract_validated_files(archive, extraction_root):
"""Materialize only regular data, also on Python before tar filters existed."""
if extraction_root.is_symlink() or not extraction_root.is_dir() or any(extraction_root.iterdir()):
die("artifact extraction requires an empty private directory")
root = extraction_root.resolve(strict=True)
members = archive.getmembers()
if len(members) > 65536 or sum(item.size for item in members) > MAX_ARTIFACT_BYTES:
die("artifact expanded size/count rejected")
normalized = set()
files = set()
for member in members:
safe_tar_member(member)
path = PurePosixPath(member.name)
name = path.as_posix()
if member.name.rstrip("/") != name or name in normalized:
die("artifact contains noncanonical or duplicate paths")
normalized.add(name)
if member.isfile():
files.add(name)
for member in members:
if any(str(parent) in files for parent in PurePosixPath(member.name).parents):
die("artifact file is used as a directory")
# All members are checked before any output. Never apply archive ownership,
# links, devices or special mode bits; never invoke extract/extractall.
for member in members:
destination = root.joinpath(*PurePosixPath(member.name).parts)
if member.isdir():
destination.mkdir(parents=True, exist_ok=True, mode=0o755)
else:
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
with archive.extractfile(member) as source, destination.open("xb") as output:
shutil.copyfileobj(source, output)
destination.chmod(0o755 if member.mode & 0o111 else 0o644)
def load_artifact(artifact: Path, extraction_root: Path): def load_artifact(artifact: Path, extraction_root: Path):
artifact = artifact.resolve(strict=True) artifact = artifact.resolve(strict=True)
if artifact.parent != INBOX_ROOT.resolve(strict=True): if artifact.parent != INBOX_ROOT.resolve(strict=True):
@@ -248,7 +283,7 @@ def load_artifact(artifact: Path, extraction_root: Path):
die("artifact top-level contract is incomplete") die("artifact top-level contract is incomplete")
if any(name.split("/", 1)[0] not in required for name in seen): if any(name.split("/", 1)[0] not in required for name in seen):
die("artifact contains an unexpected top-level member") die("artifact contains an unexpected top-level member")
archive.extractall(extraction_root, filter="data") extract_validated_files(archive, extraction_root)
manifest = parse_manifest( manifest = parse_manifest(
(extraction_root / "manifest.env").read_text(encoding="utf-8") (extraction_root / "manifest.env").read_text(encoding="utf-8")
@@ -0,0 +1,84 @@
"""Exercise the real standalone loaders without Python's newer tar filter API."""
import importlib.machinery
import importlib.util
import io
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest.mock import patch
def load(name):
loader = importlib.machinery.SourceFileLoader(name, str(Path(__file__).parent / name))
spec = importlib.util.spec_from_loader(name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNERS = [load("nodedc-edge-deploy"), load("nodedc-b2-vps-deploy")]
def archive(items):
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode="w") as output:
for name, kind in items:
info = tarfile.TarInfo(name)
info.type, info.mode, info.uid, info.gid = kind, 0o6777, 123, 456
info.linkname = "/tmp/outside"
if kind == tarfile.REGTYPE:
info.size = 4
output.addfile(info, io.BytesIO(b"data"))
else:
output.addfile(info)
buffer.seek(0)
return tarfile.open(fileobj=buffer, mode="r")
class PortableExtractionTests(unittest.TestCase):
def test_no_extractall_and_no_special_modes(self):
for runner in RUNNERS:
with self.subTest(runner=runner.__name__), tempfile.TemporaryDirectory() as directory:
with archive([("payload", tarfile.DIRTYPE), ("payload/app.mjs", tarfile.REGTYPE)]) as value:
with patch.object(tarfile.TarFile, "extractall", side_effect=AssertionError("unfiltered extraction forbidden")):
runner.extract_validated_files(value, Path(directory))
target = Path(directory) / "payload/app.mjs"
self.assertEqual(target.read_bytes(), b"data")
self.assertEqual(target.stat().st_mode & 0o7777, 0o755)
def test_every_member_checked_before_any_write(self):
for runner in RUNNERS:
for name, kind in [("../escape", tarfile.REGTYPE), ("/absolute", tarfile.REGTYPE),
("payload/link", tarfile.SYMTYPE), ("payload/link", tarfile.LNKTYPE),
("payload/pipe", tarfile.FIFOTYPE), ("payload/.env", tarfile.REGTYPE),
("payload//alias", tarfile.REGTYPE), ("payload/./alias", tarfile.REGTYPE),
("payload/a", tarfile.REGTYPE), ("payload/a/child", tarfile.REGTYPE)]:
with self.subTest(runner=runner.__name__, name=name, kind=kind), tempfile.TemporaryDirectory() as directory:
with archive([("payload/a", tarfile.REGTYPE), (name, kind)]) as value:
with self.assertRaises(runner.DeployError): runner.extract_validated_files(value, Path(directory))
self.assertEqual(list(Path(directory).iterdir()), [])
def test_existing_output_and_symlink_root_rejected(self):
for runner in RUNNERS:
with self.subTest(runner=runner.__name__), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "existing").write_text("preserve")
with archive([("payload/a", tarfile.REGTYPE)]) as value:
with self.assertRaises(runner.DeployError): runner.extract_validated_files(value, root)
(root / "target").mkdir()
(root / "linked").symlink_to(root / "target", target_is_directory=True)
with archive([("payload/a", tarfile.REGTYPE)]) as value:
with self.assertRaises(runner.DeployError): runner.extract_validated_files(value, root / "linked")
self.assertEqual((root / "existing").read_text(), "preserve")
def test_expanded_size_bounded(self):
for runner in RUNNERS:
with self.subTest(runner=runner.__name__), tempfile.TemporaryDirectory() as directory:
with archive([("payload/a", tarfile.REGTYPE)]) as value, patch.object(runner, "MAX_ARTIFACT_BYTES", 3):
with self.assertRaises(runner.DeployError): runner.extract_validated_files(value, Path(directory))
self.assertFalse(list(Path(directory).iterdir()))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,41 @@
import hashlib
import importlib.util
import json
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest import mock
spec=importlib.util.spec_from_file_location('b2_builder',Path(__file__).with_name('build_device_b2_foundation.py'))
B=importlib.util.module_from_spec(spec);spec.loader.exec_module(B)
class Artifact(unittest.TestCase):
def test_deterministic_exact_three_files_and_no_overwrite(self):
with tempfile.TemporaryDirectory() as tmp:
first=Path(tmp)/'one.tgz';second=Path(tmp)/'two.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() for m in archive))
manifest=archive.extractfile('manifest.env').read().decode()
self.assertIn('component=device-b2-foundation\n',manifest)
sql=archive.extractfile('payload/'+B.ENTRIES[1]).read()
self.assertEqual(hashlib.sha256(sql).hexdigest(),B.SQL_SHA)
self.assertNotIn(b'drop table',sql.lower())
def test_changed_sql_is_rejected_before_archive_exists(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp)/'source';root.mkdir()
for name in B.ENTRIES:
path=root/name;path.parent.mkdir(exist_ok=True);path.write_bytes((B.ROOT/name).read_bytes())
(root/B.ENTRIES[1]).write_bytes(b'drop table existing;')
target=Path(tmp)/'bad.tgz'
with mock.patch.object(B,'ROOT',root),self.assertRaises(ValueError):B.build(target)
self.assertFalse(target.exists())
if __name__=='__main__':unittest.main()
@@ -0,0 +1,44 @@
import importlib.util
import json
from pathlib import Path
import shutil
import tarfile
import tempfile
import unittest
from unittest import mock
spec = importlib.util.spec_from_file_location('shared_builder', Path(__file__).with_name('build_device_b2_shared_contours.py'))
B = importlib.util.module_from_spec(spec)
spec.loader.exec_module(B)
class SharedContoursArtifact(unittest.TestCase):
def test_deterministic_data_only_exact_payload_no_overwrite(self):
with tempfile.TemporaryDirectory() as tmp:
first, second = Path(tmp)/'a.tgz', Path(tmp)/'b.tgz'
B.build(first); B.build(second)
self.assertEqual(first.read_bytes(), second.read_bytes())
with self.assertRaises(FileExistsError): B.build(first)
with tarfile.open(first) as archive:
self.assertEqual(set(archive.getnames()), {'manifest.env', 'files.txt', *('payload/'+p for p in B.ENTRIES)})
self.assertTrue(all(m.isfile() and m.mode == 0o644 for m in archive))
self.assertEqual(archive.extractfile('files.txt').read().decode().splitlines(), list(B.ENTRIES))
def test_mutated_forward_reverse_descriptor_and_symlink_rejected(self):
for name in B.ENTRIES:
for mode in ('changed', 'symlink'):
with self.subTest(name=name, mode=mode), tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)/'source'; (root/'deployment').mkdir(parents=True)
for p in B.ENTRIES: shutil.copyfile(B.ROOT/p, root/p)
if mode == 'symlink':
(root/name).unlink(); (root/name).symlink_to(B.ROOT/name)
elif name == B.DESCRIPTOR:
d = json.loads((root/name).read_text()); d['services'] = ['device-postgres']
(root/name).write_text(json.dumps(d))
else: (root/name).write_text('drop table device_b2_hosts;')
target = Path(tmp)/'bad.tgz'
with mock.patch.object(B, 'ROOT', root), self.assertRaises(ValueError): B.build(target)
self.assertFalse(target.exists())
if __name__ == '__main__': unittest.main()
@@ -0,0 +1,81 @@
"""Exercise the pinned production installer against real Core/Manager HTTP handlers."""
import importlib.machinery
import importlib.util
import json
import os
from pathlib import Path
import select
import subprocess
import unittest
import urllib.request
from unittest import mock
HERE = Path(__file__).resolve().parent
RUNNER_PATH = Path(os.environ.get("NODEDC_DEPLOY_RUNNER", HERE.parents[2] / "platform/infra/deploy-runner/nodedc-deploy"))
loader = importlib.machinery.SourceFileLoader("release_health_runner", str(RUNNER_PATH))
spec = importlib.util.spec_from_loader(loader.name, loader)
R = importlib.util.module_from_spec(spec)
loader.exec_module(R)
class ActualApplicationHealthContractTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.process = subprocess.Popen(
["node", str(HERE / "health-contract-servers.mjs")],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
)
cls.addClassCleanup(cls.stop_servers)
if not select.select([cls.process.stdout], [], [], 15)[0]:
raise AssertionError("health fixture did not listen within 15 seconds")
line = cls.process.stdout.readline()
if not line:
raise AssertionError("health fixture failed: " + cls.process.stderr.read())
cls.urls = json.loads(line)
@classmethod
def stop_servers(cls):
cls.process.stdin.close()
try:
cls.process.wait(timeout=5)
except subprocess.TimeoutExpired:
cls.process.kill()
cls.process.wait(timeout=5)
cls.process.stdout.close()
cls.process.stderr.close()
def check_actual_handlers(self, mode):
health = R.healthcheck_url
calls = []
def local_check(check):
index = 0 if check["url"].endswith(":18120/healthz") else 1
calls.append(index)
return health({**check, "url": self.urls[mode][index]})
with mock.patch.object(R, "healthcheck_compose_service_with_grace"), \
mock.patch.object(R, "healthcheck_url", side_effect=local_check), \
mock.patch.object(R.time, "sleep"), \
mock.patch.object(R, "NO_REDIRECT_OPENER", urllib.request.build_opener(urllib.request.ProxyHandler({}))):
# Real release selection and real HTTP contract comparison, not a copied expectation.
R.run_healthchecks("device-core-release", R.DEVICE_RELEASE_ENTRIES, R.DEVICE_RELEASE_SERVICES)
return calls
def test_enabled_production_foundation_passes_actual_installer(self):
self.assertEqual(self.check_actual_handlers("healthy"), [0, 1])
def test_unavailable_database_fails(self):
with self.assertRaisesRegex(R.DeployError, "contract mismatch"):
self.check_actual_handlers("database")
def test_disabled_required_core_capabilities_fail(self):
for mode in ["discovery", "management", "transport"]:
with self.subTest(mode=mode), self.assertRaisesRegex(R.DeployError, "contract mismatch"):
self.check_actual_handlers(mode)
def test_manager_without_auth_or_core_fails(self):
for mode in ["auth", "coreClient"]:
with self.subTest(mode=mode), self.assertRaisesRegex(R.DeployError, "contract mismatch"):
self.check_actual_handlers(mode)
if __name__ == "__main__":
unittest.main()
+10
View File
@@ -1648,6 +1648,15 @@
"node": ">=18" "node": ">=18"
} }
}, },
"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": { "node_modules/pg": {
"version": "8.22.0", "version": "8.22.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz", "resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
@@ -2136,6 +2145,7 @@
"name": "@nodedc/device-control-core", "name": "@nodedc/device-control-core",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"oauth4webapi": "3.8.8",
"pg": "8.22.0" "pg": "8.22.0"
}, },
"engines": { "engines": {
+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)
+83
View File
@@ -0,0 +1,83 @@
// Bounded SQL qualification, not a fleet simulator or a production DB connection.
// npm install --prefix /private/tmp/ndc-b2-sql-check --ignore-scripts --save-exact @electric-sql/pglite@0.5.8
// node scripts/qualify-b2-foundation.mjs /private/tmp/ndc-b2-sql-check/node_modules/@electric-sql/pglite/dist/index.js /private/tmp/b2-schema-proof.json
import assert from 'node:assert/strict';
import { readFile, readdir, writeFile, mkdtemp, rm } from 'node:fs/promises';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { resolve } from 'node:path';
import { tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
import { B2Infrastructure } from '../services/device-control-core/src/b2/infrastructure.mjs';
import { B2Secrets } from '../services/device-control-core/src/b2/vault.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
const { PGlite } = await import(pathToFileURL(resolve(process.argv[2])));
const db = new PGlite();
try {
const directory = resolve(root, 'services/device-control-core/migrations');
const migrations = (await readdir(directory)).filter((name) => name.endsWith('.sql')).sort();
for (const name of migrations) await db.exec(await readFile(resolve(directory, name), 'utf8'));
assert.equal(migrations.length, 17);
await db.exec(await readFile(resolve(root, 'deployment/device-b2-foundation-v1.sql'), 'utf8'));
const ownerA = '11111111-1111-4111-8111-111111111111'; const ownerB = '22222222-2222-4222-8222-222222222222';
const projectA = '33333333-3333-4333-8333-333333333333'; const projectB = '44444444-4444-4444-8444-444444444444';
const source = '55555555-5555-4555-8555-555555555555'; const host = '66666666-6666-4666-8666-666666666666';
for (const [owner, project] of [[ownerA, projectA], [ownerB, projectB]]) {
await db.query('insert into device_owner_scopes(id,scope_kind,owner_ref,display_name,created_by_ref) values($1,$2,$3,$4,$5)', [owner,'company','company:'+owner,'SQL fixture','user:fixture']);
await db.query('insert into device_projects(id,owner_scope_id,project_key,name,created_by_ref) values($1,$2,$3,$4,$5)', [project,owner,'fixture-project','SQL fixture','user:fixture']);
}
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)`, [source,ownerA,'fixture-vps','https://vps.invalid','a'.repeat(64),'b'.repeat(32),'host','b2-secret:fixture']);
await db.query(`insert into device_infrastructure_hosts(id,owner_scope_id,project_id,host_key,display_name,created_by_ref)
values($1,$2,$3,$4,$5,$6)`, [host,ownerA,projectA,'fixture-host','SQL fixture','user:fixture']);
await db.query('insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id) values($1,$2,$3,$4)', [host,projectA,ownerA,source]);
await assert.rejects(db.query('insert into device_b2_contour_links values($1,$2,$3,$4,$5,now())', [source,'c'.repeat(32),projectB,ownerA,'user:fixture']), (error) => error.code === '23503');
await db.query('insert into device_b2_contour_links values($1,$2,$3,$4,$5,now())', [source,'c'.repeat(32),projectA,ownerA,'user:fixture']);
await assert.rejects(db.query('insert into device_b2_contour_links values($1,$2,$3,$4,$5,now())', [source,'c'.repeat(32),projectA,ownerA,'user:fixture']), (error) => error.code === '23505');
// Execute the actual domain repository against PostgreSQL, not mocked SQL.
const projectA2 = '77777777-7777-4777-8777-777777777777';
await db.query('insert into device_projects(id,owner_scope_id,project_key,name,created_by_ref) values($1,$2,$3,$4,$5)', [projectA2,ownerA,'second-project','Second SQL fixture','user:fixture']);
for (const project of [projectA,projectA2,projectB]) await db.query(
'insert into device_project_grants(id,project_id,principal_kind,principal_ref,project_role,created_by_ref) values($1,$2,$3,$4,$5,$6)',
[randomUUID(),project,'user','user:fixture','owner','user:fixture']);
const secretRoot = await mkdtemp(resolve(tmpdir(),'b2-sql-secrets-'));
try {
const packageValue = { schema:'nodedc.b2-connection/v2',endpoint:'https://vps.invalid',host_id:'fixture-vps',
fingerprint:'a'.repeat(64),integration_id:'b'.repeat(32),authority:'host',issuer:'https://vps.invalid/',
audience:'https://vps.invalid/v2',scope:'b2',client_id:'b2_fixture',client_secret:'synthetic-sql-test-secret' };
const remote = { async call(path) {
if (path==='/v2/identity') return {host_id:packageValue.host_id};
if (path==='/v2/management') return {host_id:packageValue.host_id,contours:[],applications:[]};
if (path==='/v2/contours') return {items:[{id:'d'.repeat(32)}]};
if (path.endsWith('/devices')) return {items:[]};
throw new Error('unexpected test remote operation');
} };
const service = new B2Infrastructure({ pool:{connect:async()=>({query:(...args)=>db.query(...args),release(){}})},
secrets:new B2Secrets(secretRoot),clientFactory:()=>remote });
const actor = {userRef:'user:fixture',hubRole:'owner',groupRefs:[],ownerScopes:[{scopeKind:'company',ownerRef:'company:'+ownerA}]};
const common = {projectRef:'project:'+projectA,hostRef:'host:'+host};
const connect = await service.execute(actor,{...common,action:'connect',connection:packageValue},'a'.repeat(32));
assert.equal(connect.connected,true);
await service.execute(actor,{...common,action:'link',contourId:'d'.repeat(32),targetProjectRef:'project:'+projectA2},'b'.repeat(32));
const linkedViews = (await db.query('select * from device_b2_host_views where source_id=$1',[source])).rows;
assert.equal(linkedViews.length,2);
assert.equal(linkedViews.filter((view)=>view.project_id===projectA2).length,1);
await assert.rejects(service.execute(actor,{...common,action:'link',contourId:'d'.repeat(32),targetProjectRef:'project:'+projectB},'c'.repeat(32)), /b2_company_mismatch/);
const stored = (await db.query('select secret_ref from device_b2_hosts where id=$1',[source])).rows[0];
assert.match(stored.secret_ref,/^b2-secret:/);
const audit = JSON.stringify((await db.query('select payload from device_audit_events')).rows);
assert.equal(audit.includes(packageValue.client_secret),false);
} finally { await rm(secretRoot,{recursive:true,force:true}); }
const schema = (await db.query(`select c.relname as name,obj_description(c.oid) as marker,
(select count(*)::int from pg_attribute a where a.attrelid=c.oid and a.attnum>0 and not a.attisdropped) as columns,
(select count(*)::int from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as constraints,
(select bool_and(k.convalidated) from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as validated,
(select json_agg(json_build_array(a.attname,format_type(a.atttypid,a.atttypmod),a.attnotnull) order by a.attnum)
from pg_attribute a where a.attrelid=c.oid and a.attnum>0 and not a.attisdropped) as fields,
(select json_agg(pg_get_constraintdef(k.oid) order by pg_get_constraintdef(k.oid)) from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as definitions
from pg_class c join pg_namespace n on n.oid=c.relnamespace where n.nspname='public'
and c.relname in ('device_b2_hosts','device_b2_host_views','device_b2_contour_links') order by c.relname`)).rows;
if (process.argv[3]) await writeFile(process.argv[3],JSON.stringify(schema,null,2)+'\n');
console.log(JSON.stringify({ ok:true,engine:'PGlite 0.5.8 PostgreSQL WASM',migrations:migrations.length,
checks:['existing schema compatibility','new tables','same-company link','cross-company FK denial','one-contour-one-project uniqueness','actual connect/link repository','private key storage','shared host view in second project','audit excludes secrets'],
productionAcceptance:false,rows:schema.map(({name,columns,constraints})=>({name,columns,constraints})) }));
} finally { await db.close(); }
+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", "name": "@nodedc/device-control-core",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"oauth4webapi": "3.8.8",
"pg": "8.22.0" "pg": "8.22.0"
}, },
"engines": { "engines": {
"node": ">=20" "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": { "node_modules/pg": {
"version": "8.22.0", "version": "8.22.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz", "resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
@@ -8,6 +8,7 @@
"test": "node --test test/*.test.mjs" "test": "node --test test/*.test.mjs"
}, },
"dependencies": { "dependencies": {
"oauth4webapi": "3.8.8",
"pg": "8.22.0" "pg": "8.22.0"
}, },
"engines": { "engines": {
+12
View File
@@ -81,6 +81,7 @@ export function createControlCoreApp({
gatewayIngest = null, gatewayIngest = null,
edgeChannelStatusProvider = null, edgeChannelStatusProvider = null,
typedCommandRuntime = null, typedCommandRuntime = null,
b2Infrastructure = null,
} = {}) { } = {}) {
if (!repository || typeof repository.health !== "function") { if (!repository || typeof repository.health !== "function") {
throw new TypeError("device_repository_required"); throw new TypeError("device_repository_required");
@@ -204,6 +205,17 @@ export function createControlCoreApp({
}); });
} }
if (request.method === "POST" && requestUrl.pathname === "/internal/v1/b2/infrastructure") {
if (!managementApiEnabled || !b2Infrastructure) return writeJson(response, 503, { ok: false, error: "b2_infrastructure_unavailable" });
if (!matchesBearer(request.headers.authorization, managementToken)) return writeJson(response, 401, { ok: false, error: "device_management_auth_required" });
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, 128 * 1024);
const result = await b2Infrastructure.execute(actor, input, requestId);
return writeJson(response, 200, { ok: true, result });
}
const managementCommandKind = managementRoutes.get(requestUrl.pathname); const managementCommandKind = managementRoutes.get(requestUrl.pathname);
if (request.method === "POST" && managementCommandKind) { if (request.method === "POST" && managementCommandKind) {
if (!managementApiEnabled) { if (!managementApiEnabled) {
@@ -0,0 +1,161 @@
import { createHash, timingSafeEqual } from 'node:crypto';
import { lookup } from 'node:dns/promises';
import { request, Agent } from 'node:https';
import { connect } from 'node:tls';
import { isIP } from 'node:net';
import * as oauth from 'oauth4webapi';
export function b2Error(code, statusCode = 400) {
return Object.assign(new Error(code), { statusCode });
}
export function connectionPackage(value) {
if (!value || value.schema !== 'nodedc.b2-connection/v2') throw b2Error('b2_connection_invalid');
const url = new URL(value.endpoint);
if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
throw b2Error('b2_endpoint_invalid');
}
if (!/^[a-f0-9]{64}$/.test(value.fingerprint) || !/^[A-Za-z0-9_-]{1,128}$/.test(value.client_id)
|| typeof value.client_secret !== 'string' || value.client_secret.length < 16 || value.client_secret.length > 1024
|| !/^[a-f0-9]{32}$/.test(value.integration_id) || typeof value.host_id !== 'string'
|| value.host_id.length > 160 || !['host', 'contours'].includes(value.authority)
|| value.issuer !== url.origin + '/' || value.audience !== url.origin + '/v2' || value.scope !== 'b2') {
throw b2Error('b2_connection_invalid');
}
return Object.freeze({ schema: value.schema, endpoint: url.origin, fingerprint: value.fingerprint,
issuer: value.issuer, audience: value.audience, scope: 'b2', host_id: value.host_id,
integration_id: value.integration_id, client_id: value.client_id, client_secret: value.client_secret,
authority: value.authority });
}
export function isPublicIPv4(value) {
if (isIP(value) !== 4) return false;
const [a, b, c] = value.split('.').map(Number);
return !(a === 0 || a === 10 || a === 127 || a >= 224
|| (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254)
|| (a === 172 && b >= 16 && b <= 31) || (a === 192 && (b === 168 || b === 0 || b === 2))
|| (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100)))
|| (a === 203 && b === 0 && c === 113));
}
export function pinnedFetch(pkg, { lookupImpl = lookup, connectImpl = connect, requestImpl = request, timeoutMs = 8000 } = {}) {
return async (input, init = {}) => {
const url = new URL(input instanceof Request ? input.url : input);
if (url.origin !== pkg.endpoint || !(/^\/v2(?:\/|$)/.test(url.pathname) || url.pathname === '/oauth2/token')) {
throw b2Error('b2_endpoint_invalid');
}
const started = Date.now();
let dnsTimer;
let cancelDNS;
let addresses;
try {
addresses = await Promise.race([
lookupImpl(url.hostname, { all: true, family: 4 }),
new Promise((_, reject) => {
cancelDNS = () => reject(b2Error('b2_request_timeout', 504));
dnsTimer = setTimeout(cancelDNS, timeoutMs);
init.signal?.addEventListener('abort', cancelDNS, { once: true });
if (init.signal?.aborted) cancelDNS();
}),
]);
} catch (error) {
if (error?.message?.startsWith('b2_')) throw error;
throw b2Error('b2_host_unavailable', 502);
} finally {
clearTimeout(dnsTimer); init.signal?.removeEventListener('abort', cancelDNS);
}
if (!addresses.length || addresses.some(({ address }) => !isPublicIPv4(address))) throw b2Error('b2_public_endpoint_required');
// Complete and verify TLS before handing the socket to HTTP. No credentials
// are written to a peer whose certificate does not match the imported pin.
const socket = connectImpl({ host: addresses[0].address, port: Number(url.port || 443),
servername: isIP(url.hostname) ? undefined : url.hostname, rejectUnauthorized: false });
const abort = () => socket.destroy(b2Error('b2_request_timeout', 504));
const timer = setTimeout(abort, Math.max(1, timeoutMs - (Date.now() - started)));
init.signal?.addEventListener('abort', abort, { once: true });
try {
if (init.signal?.aborted) throw b2Error('b2_request_timeout', 504);
await new Promise((resolve, reject) => {
socket.once('error', reject);
socket.once('secureConnect', () => {
try {
const cert = socket.getPeerCertificate();
if (!cert.raw || !timingSafeEqual(createHash('sha256').update(cert.raw).digest(), Buffer.from(pkg.fingerprint, 'hex'))) {
throw b2Error('b2_certificate_mismatch', 502);
}
resolve();
} catch (error) { reject(error); }
});
});
return await new Promise((resolve, reject) => {
const headers = Object.fromEntries(new Headers(init.headers));
const body = init.body == null ? null : String(init.body);
if (body) headers['content-length'] = String(Buffer.byteLength(body));
const agent = new Agent({ keepAlive: false, maxSockets: 1 });
agent.createConnection = () => socket;
const req = requestImpl(url, { method: init.method || 'GET', headers, agent }, (res) => {
const chunks = []; let length = 0;
res.on('data', (chunk) => {
length += chunk.length;
if (length > 1024 * 1024) { req.destroy(b2Error('b2_response_too_large', 502)); return; }
chunks.push(chunk);
});
res.on('error', reject);
res.on('end', () => resolve(new Response(Buffer.concat(chunks), {
status: res.statusCode, headers: res.headers,
})));
});
req.on('error', reject);
req.end(body);
});
} catch (error) {
if (error?.message?.startsWith('b2_')) throw error;
throw b2Error('b2_host_unavailable', 502);
} finally {
clearTimeout(timer); init.signal?.removeEventListener('abort', abort); socket.destroy();
}
};
}
export function createB2Client(input, { fetchImpl } = {}) {
const pkg = connectionPackage(input);
const transport = fetchImpl || pinnedFetch(pkg);
const server = { issuer: pkg.issuer, token_endpoint: pkg.endpoint + '/oauth2/token' };
const client = { client_id: pkg.client_id };
let token = null; let expires = 0; let pending = null;
async function accessToken() {
if (token && Date.now() < expires) return token;
if (!pending) pending = (async () => {
const response = await oauth.clientCredentialsGrantRequest(server, client,
oauth.ClientSecretBasic(pkg.client_secret), { scope: 'b2', audience: pkg.audience },
{ [oauth.customFetch]: transport });
const value = await oauth.processClientCredentialsResponse(server, client, response);
token = value.access_token;
expires = Date.now() + Math.max(0, Math.min(value.expires_in || 0, 300) - 15) * 1000;
return token;
})().finally(() => { pending = null; });
return pending;
}
return {
package: pkg,
async call(path, body) {
if (!/^\/v2\//.test(path)) throw b2Error('b2_resource_invalid');
let bearer;
try { bearer = await accessToken(); } catch { throw b2Error('b2_key_rejected', 502); }
const res = await transport(pkg.endpoint + path, {
method: body === undefined ? 'GET' : 'POST',
headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
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);
return value;
},
};
}
@@ -0,0 +1,390 @@
import { randomUUID } from 'node:crypto';
import { applyOntologyManagementCommand } from '../ontology-repository.mjs';
import { normalizeOntologyManagementCommand } from '../ontology-management.mjs';
import { findProjectWithCapability } from '../lifecycle-repository.mjs';
import { assertActorCanManageOwnerScope } from '../project-management.mjs';
import { b2Error, connectionPackage, createB2Client } from './connection.mjs';
function ref(value, prefix) {
if (typeof value !== 'string' || !new RegExp(`^${prefix}:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`).test(value)) throw b2Error('b2_reference_invalid');
return value.slice(prefix.length + 1);
}
function opaque(value) {
if (typeof value !== 'string' || !/^[a-f0-9]{32}$/.test(value)) throw b2Error('b2_identifier_invalid');
return value;
}
function fields(input, names) {
if (Object.keys(input).some((key) => !['projectRef', 'hostRef', 'action', ...names].includes(key))) throw b2Error('b2_unexpected_field');
}
export class B2Infrastructure {
constructor({ pool, secrets, clientFactory = createB2Client }) {
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.
const cached = this.clients.get(source.secret_ref);
if (cached) return cached;
const client = this.clientFactory(await this.secrets.read(source.secret_ref));
if (this.clients.size >= 64) this.clients.delete(this.clients.keys().next().value);
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;
const readOnly = ['status', 'devices'].includes(action);
const db = await this.pool.connect();
try {
await db.query('begin');
const project = await findProjectWithCapability(db, actor, projectId, readOnly ? 'infrastructure.read' : 'infrastructure.manage');
// 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', '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',
[hostId, projectId, 'retired'])).rows[0];
if (!host) throw b2Error('b2_project_host_not_found', 404);
const source = (await db.query(`select s.* from device_b2_hosts s join device_b2_host_views v on v.source_id=s.id
where v.host_id=$1 and v.project_id=$2 ${readOnly ? '' : 'for update of s'}`, [hostId, projectId])).rows[0];
let result;
if (action === 'connect') {
fields(input, ['connection']);
const pkg = connectionPackage(typeof input.connection === 'string' ? JSON.parse(input.connection) : input.connection);
if (source && (source.remote_host_id !== pkg.host_id || source.integration_id !== pkg.integration_id)) {
throw b2Error('b2_connection_identity_conflict', 409);
}
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 = 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 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]);
result = { connected: true, endpoint: pkg.endpoint, authority: pkg.authority };
} else if (!source) {
if (action !== 'status') throw b2Error('b2_host_not_connected', 409);
result = { connected: false };
} else {
const remote = await this.clientFor(source);
const links = (await db.query('select contour_id,project_id from device_b2_contour_links where source_id=$1 order by contour_id', [source.id])).rows;
if (action === 'status') {
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 (['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);
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);
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 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];
if (!related) {
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name,
providerRef: host.provider_ref, externalRef: source.remote_host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]);
}
}
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
}
} else if (action === 'devices') {
fields(input, []);
const contours = links.filter((link) => link.project_id === projectId);
const items = [];
for (const link of contours) {
const snapshot = await remote.call(`/v2/contours/${link.contour_id}/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: link.contour_id })));
}
result = { items };
} else {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
if (action === 'contour-create') {
fields(input, ['key', 'name']);
result = await remote.call('/v2/management/contours', { key: input.key, name: input.name });
} else if (action === 'application-create') {
fields(input, ['key', 'name', 'contourId']);
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');
// Server reserves this request before generation. No automatic replay.
const packageValue = await remote.call('/v2/management/credentials', {
integration_id: opaque(input.integrationId), replace: input.replace, request_id: requestId,
});
result = { connection: packageValue };
} else if (action === 'key-revoke') {
fields(input, ['clientId']);
if (!/^[A-Za-z0-9_-]{1,128}$/.test(input.clientId)) throw b2Error('b2_client_invalid');
result = await remote.call('/v2/management/credentials/revoke', { client_id: input.clientId });
} else throw b2Error('b2_action_invalid');
}
}
if (!readOnly) 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.' + action, actor.userRef,
JSON.stringify({ projectRef: input.projectRef, hostRef: input.hostRef, requestId }), projectId]);
await db.query('commit');
return result;
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
}
}
@@ -0,0 +1,43 @@
import { constants } from 'node:fs';
import { open, lstat } from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { b2Error, connectionPackage } from './connection.mjs';
// Dedicated persistent private mount provisioned by the canonical installer.
// It is not served, included in images, stored in audit payloads or returned by reads.
export class B2Secrets {
constructor(root) { this.root = root; }
async directory() {
if (!this.root) throw b2Error('b2_private_storage_unavailable', 503);
const info = await lstat(this.root);
if (!info.isDirectory() || info.isSymbolicLink() || (info.mode & 0o077) || info.uid !== process.getuid()) {
throw b2Error('b2_private_storage_invalid', 503);
}
}
path(ref) {
if (!/^b2-secret:[a-f0-9-]{36}$/.test(ref)) throw b2Error('b2_secret_reference_invalid');
return join(this.root, ref.slice(10) + '.json');
}
async save(input) {
const value = connectionPackage(input);
await this.directory();
const ref = 'b2-secret:' + randomUUID();
const file = await open(this.path(ref), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
try { await file.writeFile(JSON.stringify(value)); await file.sync(); } finally { await file.close(); }
const directory = await open(this.root, 'r');
try { await directory.sync(); } finally { await directory.close(); }
return ref;
}
async read(ref) {
await this.directory();
const file = await open(this.path(ref), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
try {
const info = await file.stat();
if (!info.isFile() || info.nlink !== 1 || info.uid !== process.getuid() || (info.mode & 0o077) || info.size > 16384) {
throw b2Error('b2_private_storage_invalid', 503);
}
return connectionPackage(JSON.parse(await file.readFile('utf8')));
} finally { await file.close(); }
}
}
@@ -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") { if (kind === "device.update") {
assertAllowedKeys(input, [ assertAllowedKeys(input, [
"projectRef", "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) { async function updateDevice(client, actor, command) {
if (typeof command.archived === "boolean") return archiveDevice(client, actor, command);
const project = await findProjectWithCapability( const project = await findProjectWithCapability(
client, client,
actor, 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") { if (kind === "infrastructure_host.ensure") {
assertAllowedKeys(input, [ assertAllowedKeys(input, [
"projectRef", "hostKey", "displayName", "providerRef", "externalRef", "projectRef", "hostKey", "displayName", "providerRef", "externalRef",
@@ -201,7 +201,18 @@ async function closeAssetBinding(client, actor, project, command) {
return { closed: true, assetBinding: assetBindingView(row) }; 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) { async function ensureHost(client, actor, project, command) {
if (typeof command.archived === "boolean") return archiveHost(client, actor, project, command);
const result = await client.query( const result = await client.query(
`insert into device_infrastructure_hosts ( `insert into device_infrastructure_hosts (
id, owner_scope_id, project_id, host_key, display_name, provider_ref, id, owner_scope_id, project_id, host_key, display_name, provider_ref,
@@ -15,6 +15,9 @@ import { createDeviceGatewayIngest } from "./gateway-ingest.mjs";
import { PostgresDeviceRepository } from "./postgres-repository.mjs"; import { PostgresDeviceRepository } from "./postgres-repository.mjs";
import { createTypedCommandRuntime } from "./typed-command-runtime.mjs"; import { createTypedCommandRuntime } from "./typed-command-runtime.mjs";
import { B2Infrastructure } from "./b2/infrastructure.mjs";
import { B2Secrets } from "./b2/vault.mjs";
const config = await readConfig(); const config = await readConfig();
const repository = new PostgresDeviceRepository({ const repository = new PostgresDeviceRepository({
databaseUrl: config.databaseUrl, databaseUrl: config.databaseUrl,
@@ -57,6 +60,9 @@ const server = createControlCoreApp({
? () => edgeChannelSupervisor.status() ? () => edgeChannelSupervisor.status()
: null, : null,
typedCommandRuntime, typedCommandRuntime,
b2Infrastructure: process.env.DEVICE_B2_SECRET_ROOT ? new B2Infrastructure({
pool: repository.pool, secrets: new B2Secrets(process.env.DEVICE_B2_SECRET_ROOT),
}) : null,
}); });
server.listen(config.port, config.host, () => { server.listen(config.port, config.host, () => {
@@ -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/);
});
@@ -0,0 +1,414 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { mkdtemp, chmod, rm, readFile, symlink } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { connectionPackage, createB2Client, isPublicIPv4, pinnedFetch } from '../src/b2/connection.mjs';
import { B2Secrets } from '../src/b2/vault.mjs';
import { B2Infrastructure } from '../src/b2/infrastructure.mjs';
const pkg = { schema: 'nodedc.b2-connection/v2', endpoint: 'https://vps.example.invalid:19443',
fingerprint: 'a'.repeat(64), issuer: 'https://vps.example.invalid:19443/',
audience: 'https://vps.example.invalid:19443/v2', scope: 'b2', host_id: 'synthetic-host',
integration_id: 'b'.repeat(32), client_id: 'b2_test', client_secret: 'synthetic-test-secret-not-production', authority: 'host' };
const projectId = '11111111-1111-4111-8111-111111111111';
const otherProject = '22222222-2222-4222-8222-222222222222';
const hostId = '33333333-3333-4333-8333-333333333333';
const ownerId = '44444444-4444-4444-8444-444444444444';
const actor = { userRef: 'user:operator', hubRole: 'owner', groupRefs: [], ownerScopes: [{ scopeKind: 'company', ownerRef: 'company:example' }] };
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, 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,
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 }] };
if (sql.includes('from device_b2_hosts')) return { rows: [source] };
if (sql.includes('from device_b2_contour_links')) return { rows: links };
if (sql.startsWith('insert')) { writes.push({ sql, values }); return { rows: [] }; }
throw new Error('unexpected test query: ' + sql);
} };
return { pool: { connect: async () => db }, writes };
}
test('connection import fixes issuer, audience and authority to the supplied host', () => {
assert.equal(connectionPackage(pkg).endpoint, pkg.endpoint);
for (const change of [{ endpoint: 'http://vps.example.invalid' }, { issuer: 'https://other.invalid/' },
{ audience: 'https://other.invalid/v2' }, { fingerprint: 'x' }, { authority: 'owner' }]) {
assert.throws(() => connectionPackage({ ...pkg, ...change }));
}
});
test('standard OAuth client caches access token and does not log or return credentials', async () => {
let tokens = 0; let calls = 0;
const client = createB2Client(pkg, { fetchImpl: async (url, init) => {
if (String(url).endsWith('/oauth2/token')) {
tokens += 1;
const headers = new Headers(init.headers);
assert.match(headers.get('authorization'), /^Basic /);
const body = new URLSearchParams(init.body);
assert.equal(body.get('grant_type'), 'client_credentials');
assert.equal(body.get('audience'), pkg.audience);
return new Response(JSON.stringify({ access_token: 'opaque-test-token', token_type: 'Bearer', expires_in: 300 }), { headers: { 'content-type': 'application/json' } });
}
calls += 1;
assert.equal(new Headers(init.headers).get('authorization'), 'Bearer opaque-test-token');
return new Response('{"items":[]}');
} });
await Promise.all([client.call('/v2/contours'), client.call('/v2/contours')]);
assert.equal(tokens, 1); assert.equal(calls, 2);
await assert.rejects(client.call('/admin/clients'));
});
test('outbound adapter rejects private networks, redirects and foreign origins before TLS', async () => {
for (const address of ['127.0.0.1', '10.1.2.3', '172.16.1.1', '192.168.1.3', '169.254.169.254', '::1', '100.64.1.1']) assert.equal(isPublicIPv4(address), false);
const fetcher = pinnedFetch(pkg, { lookupImpl: async () => [{ address: '127.0.0.1' }], connectImpl: () => assert.fail('must not connect') });
await assert.rejects(fetcher(pkg.endpoint + '/v2/contours'), /b2_public_endpoint_required/);
await assert.rejects(fetcher('https://other.invalid/v2/contours'), /b2_endpoint_invalid/);
await assert.rejects(fetcher(pkg.endpoint + '/admin/clients'), /b2_endpoint_invalid/);
});
test('private file store uses unique 0600 files and rejects permissive roots and symlinks', async () => {
const root = await mkdtemp(join(tmpdir(), 'ndc-b2-secrets-'));
try {
await chmod(root, 0o700);
const store = new B2Secrets(root);
const ref = await store.save(pkg);
assert.equal((await store.read(ref)).client_secret, pkg.client_secret);
assert.equal(JSON.parse(await readFile(store.path(ref), 'utf8')).client_id, pkg.client_id);
const bad = 'b2-secret:66666666-6666-4666-8666-666666666666';
await symlink(store.path(ref), store.path(bad));
await assert.rejects(store.read(bad));
await chmod(root, 0o755);
await assert.rejects(store.read(ref), /b2_private_storage_invalid/);
await assert.rejects(store.save(pkg), /b2_private_storage_invalid/);
} finally { await rm(root, { recursive: true, force: true }); }
});
test('DNS resolution consumes the same bounded request deadline and respects cancellation', async () => {
const stalled = pinnedFetch(pkg, { timeoutMs: 20, lookupImpl: () => new Promise(() => {}),
connectImpl: () => assert.fail('no connection after DNS timeout') });
await assert.rejects(stalled(pkg.endpoint + '/v2/identity'), /b2_request_timeout/);
const controller = new AbortController(); controller.abort();
await assert.rejects(stalled(pkg.endpoint + '/v2/identity', { signal: controller.signal }), /b2_request_timeout/);
});
test('service reuses tokens only for the same immutable secret reference', async () => {
let reads = 0; let created = 0;
const service = new B2Infrastructure({ pool: {}, secrets: { read: async () => { reads += 1; return pkg; } },
clientFactory: () => ({ generation: ++created }) });
assert.equal((await service.clientFor(source)).generation, 1);
assert.equal((await service.clientFor(source)).generation, 1);
assert.equal((await service.clientFor({ ...source, secret_ref: 'new-private-ref' })).generation, 2);
assert.equal(reads, 2);
});
test('project reader sees only explicitly linked fleet, even with a host-management connection', async () => {
const own = 'a'.repeat(32); const other = 'b'.repeat(32);
const repo = repository({ role: 'viewer', links: [{ contour_id: own, project_id: projectId }, { contour_id: other, project_id: otherProject }] });
const calls = [];
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) { calls.push(path); return { items: [] }; } }) });
assert.deepEqual(await service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'devices' }, '1'.repeat(32)), { items: [] });
assert.deepEqual(calls, [`/v2/contours/${own}/devices`]);
await assert.rejects(service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'contour-create', key: 'foreign', name: 'Foreign' }, '2'.repeat(32)));
});
test('company management refuses linking to another company before any remote request', async () => {
const repo = repository({ otherOwner: '77777777-7777-4777-8777-777777777777' });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: () => assert.fail('no remote mutation') }) });
await assert.rejects(service.execute(actor, { action: 'link', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`,
targetProjectRef: `project:${otherProject}`, contourId: 'c'.repeat(32) }, '3'.repeat(32)), /b2_company_mismatch/);
assert.deepEqual(repo.writes, []);
});
test('TLS pin is verified before any HTTP credential reaches the peer', async () => {
const { execFileSync } = await import('node:child_process');
const { createServer } = await import('node:https');
const tls = await import('node:tls');
const { X509Certificate, createHash } = await import('node:crypto');
const root = await mkdtemp(join(tmpdir(), 'ndc-b2-tls-'));
let server;
try {
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=unit.invalid',
'-keyout', join(root, 'key.pem'), '-out', join(root, 'cert.pem')], { stdio: 'ignore' });
const key = await readFile(join(root, 'key.pem')); const cert = await readFile(join(root, 'cert.pem'));
let received = 0;
server = createServer({ key, cert }, (req, res) => {
received += 1;
assert.equal(req.headers.authorization, 'Bearer synthetic-token');
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"ok":true}');
});
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
const deps = { lookupImpl: async () => [{ address: '8.8.8.8' }],
connectImpl: (options) => tls.connect({ ...options, host: '127.0.0.1', port: server.address().port }) };
const good = { ...pkg, fingerprint: createHash('sha256').update(new X509Certificate(cert).raw).digest('hex') };
const response = await pinnedFetch(good, deps)(pkg.endpoint + '/v2/contours', { headers: { Authorization: 'Bearer synthetic-token' } });
assert.equal(response.status, 200); assert.equal(received, 1);
await assert.rejects(pinnedFetch(pkg, deps)(pkg.endpoint + '/v2/contours', { headers: { Authorization: 'Bearer must-never-arrive' } }), /b2_certificate_mismatch/);
assert.equal(received, 1);
} finally {
if (server?.listening) await new Promise((resolve) => server.close(resolve));
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' } }));
});