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
DCCONSTRUCTIONS 25f8942f1c Pin Launcher source used by integration artifact tests 2026-09-29 13:12:26 +03:00
DCCONSTRUCTIONS 684922a099 Include telemetry workspace in clean install lockfile 2026-09-29 13:09:04 +03:00
DCCONSTRUCTIONS 1900257fd3 Add pinned Device Core CI qualification for main 2026-09-29 13:05:19 +03:00
DCCONSTRUCTIONS 9ff6feebcf Link Device Core B2 integration planning to the standalone VPS repository 2026-09-29 12:45:50 +03:00
DCCONSTRUCTIONS ebc264eb60 feat(device-core): ship host telemetry and scalable VPS inventory 2026-08-23 11:58:58 +03:00
DCCONSTRUCTIONS 5d58dd6c37 fix(deploy): add replay checkpoint recovery 2026-08-22 23:58:17 +03:00
DCCONSTRUCTIONS 11ddacd9cd test(deploy): pin replay recovery predecessor 2026-08-22 23:11:10 +03:00
DCCONSTRUCTIONS 7d03e87954 test(deploy): execute migration audit preflight 2026-08-22 22:37:37 +03:00
DCCONSTRUCTIONS 71da1dd42a chore(deploy): add migration invariant audit 2026-08-22 22:11:35 +03:00
DCCONSTRUCTIONS 79140ee7bf fix(device-core): make migration replay recovery safe 2026-08-22 21:12:21 +03:00
DCCONSTRUCTIONS 65c99613e5 chore(deploy): add plan-only Core incident audit 2026-08-22 20:44:15 +03:00
DCCONSTRUCTIONS 6dad30c565 fix(deploy): add exact-image Core v3 recovery 2026-08-22 19:49:36 +03:00
DCCONSTRUCTIONS d12b172569 fix(deploy): pin VPS telemetry predecessor hash 2026-08-22 17:48:03 +03:00
DCCONSTRUCTIONS 23ea96fbb2 feat(telemetry): add canonical VPS host monitoring 2026-08-22 17:29:30 +03:00
DCCONSTRUCTIONS a3e7a015de chore(release): add canonical ontology manager v8 2026-08-22 15:32:17 +03:00
DCCONSTRUCTIONS 088686d67f feat(manager): manage ontology assets and infrastructure 2026-08-22 15:04:32 +03:00
DCCONSTRUCTIONS b302b6ba1a feat(core): add ontology-backed asset and host runtime 2026-08-22 14:47:44 +03:00
DCCONSTRUCTIONS 6ed4414a97 feat(manager): expose safe VPS edge health 2026-08-22 13:08:04 +03:00
DCCONSTRUCTIONS 07ffb22d38 fix(manager): ship canonical NODE.DC favicon set 2026-08-22 10:49:52 +03:00
DCCONSTRUCTIONS 06cb780777 fix(manager): match Mission Core landing geometry 2026-08-22 10:23:07 +03:00
DCCONSTRUCTIONS 506d786ee6 fix(manager): persist environment presentation and media 2026-08-22 09:47:57 +03:00
DCCONSTRUCTIONS 40cd637f72 test(deploy): pin Manager v3 runtime acceptance 2026-08-22 09:09:32 +03:00
DCCONSTRUCTIONS b601b4ea46 deploy: advance manager v3 to recovered Core 2026-08-22 02:10:42 +03:00
152 changed files with 15340 additions and 487 deletions
+43
View File
@@ -0,0 +1,43 @@
name: Device Core qualification
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
jobs:
qualify:
runs-on: nodedc-node22-build
timeout-minutes: 45
steps:
- name: Check the exact pushed commit
env:
SOURCE_COMMIT: ${{ gitea.sha }}
SOURCE_RUN_ID: ${{ gitea.run_id }}
SOURCE_RUN_NUMBER: ${{ gitea.run_number }}
run: |
set -eu
python3 -c 'import os,re; assert re.fullmatch("[0-9a-f]{40}", os.environ["SOURCE_COMMIT"]), "full commit SHA required"'
job_root=$(mktemp -d)
trap 'rm -rf "$job_root"' EXIT
source_root="$job_root/NODEDC_DEVICE_CORE"
mkdir "$source_root"
git -C "$source_root" init --quiet
git -C "$source_root" remote add origin https://git.dcserve.ru/SILVER/NODEDC_DEVICE_CORE.git
git -C "$source_root" fetch --quiet --depth=1 origin "$SOURCE_COMMIT"
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" 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.
# Do not label a successful qualification as a successful deployment.
+12 -1
View File
@@ -55,6 +55,13 @@ platform runner registry is validated separately in `NODEDC_PLATFORM`.
## Deployment ownership
The accepted Device Core policy is automatic deployment after a push to `main`
passes its checks. See [Continuous deployment](docs/CONTINUOUS_DEPLOYMENT.md)
for the pinned source qualification workflow, Synology setup and activation
status. Automatic production installation is active: the Synology controller fetches
qualified releases over outbound HTTPS and invokes the canonical runner.
No operator Mac or new inbound port is required.
Artifact builders in `infra/deploy-runner` emit data-only tarballs. They never
orchestrate Docker or mutate a live host. Promotion remains the established
two-step workflow:
@@ -66,4 +73,8 @@ sudo /usr/local/sbin/nodedc-deploy apply /volume1/docker/nodedc-deploy/inbox/<ar
See [Repository boundary](docs/REPOSITORY_BOUNDARY.md) and
[Implementation baseline](docs/IMPLEMENTATION_BASELINE.md) for the security,
runtime and rollout constraints.
runtime and rollout constraints. The provider-neutral VPS/host expansion is
tracked as an explicit
[ontology candidate](docs/DEVICE_INFRASTRUCTURE_HOST_ONTOLOGY_CANDIDATE.md)
until the official ontology owner publishes canonical host, deployment,
service and health concepts.
+11 -2
View File
@@ -20,8 +20,17 @@ behavior; projects, inventory, collections and access remain shared Device Core
The project workspace covers inventory, discovery, collections, adapter/profile metadata,
Edges, routes, sessions, bindings, configuration state, the honest command ledger, immutable
audit metadata and project grants. Navigation and actions are derived from effective project
capabilities. Global adapter/profile/Edge mutation is additionally restricted to a Hub owner.
audit metadata and project grants. It also joins the official ontology projection for stable
Assets, temporal Device-to-Asset bindings, provider-neutral Hosts, endpoints, deployments,
service instances and freshness-bounded health observations. Navigation and actions are
derived from effective project capabilities. Global adapter/profile/Edge mutation is
additionally restricted to a Hub owner.
Host credentials are accepted only as opaque `secret-ref:*` values by the server-side Core
command. The browser projection receives only `managementCredentialConfigured`; it never
receives the reference or secret. Missing or expired health evidence is rendered as
`unobserved`, never inferred as `unreachable`. Arbitrary WebSSH remains disabled pending a
separate short-lived management-session and break-glass design.
Command planning and transport intentionally have no Device Manager mutation route yet.
The UI never presents `sent` as success: `acknowledged` and `verified` remain different
+6
View File
@@ -4,6 +4,12 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#101114" />
<link rel="icon" type="image/svg+xml" sizes="any" href="/favicon/icon-adaptive.svg" />
<link rel="icon" type="image/x-icon" href="/favicon/favicon.ico" />
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" />
<link rel="icon" type="image/png" sizes="192x192" href="/favicon/icon-192.png" />
<link rel="icon" type="image/png" sizes="512x512" href="/favicon/icon-512.png" />
<link rel="manifest" href="/favicon/manifest.webmanifest.json" />
<title>NODE.DC Device Core</title>
</head>
<body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,13 @@
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
.icon-fav-01 { fill: #333334; } /* Тёмный цвет для светлого таб-бара */
@media (prefers-color-scheme: dark) {
.icon-fav-01 { fill: #FEFEFE; } /* Светлый цвет для тёмного таб-бара */
}
@media (prefers-color-scheme: light) {
.icon-fav-01 { fill: #000000; } /* Тёмный цвет для светлого таб-бара (для явности) */
}
</style>
<path class="icon-fav-01" d="M17.8738 15.9159L16.0002 18.9718L14.1267 15.9159H17.8738ZM23.6307 12.7864H8.36914L15.9999 25.2308L23.6307 12.7864Z"/>
<path class="icon-fav-01" d="M10.9793 19.4872L6.67269 11.5918H25.5344L21.2281 19.4872H25.0581L31.2614 8H0.738281L7.16244 19.4872H10.9793Z"/>
</svg>

After

Width:  |  Height:  |  Size: 852 B

@@ -0,0 +1,29 @@
{
"theme_color": "#eeeff4",
"background_color": "#eeeff4",
"display": "browser",
"scope": "/",
"start_url": "/",
"icons": [
{
"src": "icon-adaptive.svg",
"type": "image/svg+xml",
"sizes": "any"
},
{
"src": "icon-192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "icon-512.png",
"type": "image/png",
"sizes": "512x512"
},
{
"src": "apple-touch-icon.png",
"type": "image/png",
"sizes": "180x180"
}
]
}
@@ -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());
});
@@ -13,6 +13,14 @@ const commandRoutes = new Map([
["enrollment-intents:ensure", "/internal/v1/management/enrollment-intents:ensure"],
["devices:claim", "/internal/v1/management/devices:claim"],
["devices:update", "/internal/v1/management/devices:update"],
["assets:ensure", "/internal/v1/management/assets:ensure"],
["asset-bindings:ensure", "/internal/v1/management/asset-bindings:ensure"],
["asset-bindings:close", "/internal/v1/management/asset-bindings:close"],
["infrastructure-hosts:ensure", "/internal/v1/management/infrastructure-hosts:ensure"],
["infrastructure-endpoints:ensure", "/internal/v1/management/infrastructure-endpoints:ensure"],
["infrastructure-deployments:ensure", "/internal/v1/management/infrastructure-deployments:ensure"],
["infrastructure-service-instances:ensure", "/internal/v1/management/infrastructure-service-instances:ensure"],
["health-observations:record", "/internal/v1/management/health-observations:record"],
["device-bindings:ensure", "/internal/v1/management/device-bindings:ensure"],
["device-bindings:revoke", "/internal/v1/management/device-bindings:revoke"],
[
@@ -55,14 +63,25 @@ export function createDeviceCoreClient({ baseUrl, token, fetchImpl = fetch } = {
return {
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) {
return request("/internal/v1/query/projects", actor)
.then((body) => body.projects);
},
async getWorkspace(actor, projectRef) {
const projectId = entityId(projectRef, "project");
return request(`/internal/v1/query/projects/${projectId}/workspace`, actor)
.then((body) => body.workspace);
const [workspace, ontology] = await Promise.all([
request(`/internal/v1/query/projects/${projectId}/workspace`, actor)
.then((body) => body.workspace),
request(`/internal/v1/query/projects/${projectId}/ontology`, actor)
.then((body) => body.projection),
]);
return { ...workspace, ontology };
},
async execute(command, actor, input, idempotencyKey) {
const pathname = commandRoutes.get(command);
@@ -100,6 +119,13 @@ export function createLocalPreviewDeviceCore({ fixture = null } = {}) {
const configurationStates = new Map();
const auditEvents = [];
const commands = new Map();
const assets = new Map();
const assetBindings = new Map();
const hosts = new Map();
const endpoints = new Map();
const deployments = new Map();
const serviceInstances = new Map();
const healthObservations = new Map();
function now() {
return new Date().toISOString();
@@ -166,6 +192,56 @@ export function createLocalPreviewDeviceCore({ fixture = null } = {}) {
identifierProjection: fixture === "arusnavi-b2" ? "authorized-full" : "masked-only",
auditPayloadProjection: "metadata-only",
},
ontology: ontologyProjection(projectRef),
};
}
function ontologyProjection(projectRef) {
const projectHosts = projectValues(hosts, projectRef);
const projectServices = projectValues(serviceInstances, projectRef);
const withHealth = (subjectKind, value, subjectRef) => ({
...value,
health: latestPreviewHealth(projectRef, subjectKind, subjectRef),
});
return {
ontology: {
catalogHash: "229c61c02a790906",
packages: ["asset", "device", "infrastructure", "observation"],
},
assets: projectValues(assets, projectRef),
assetBindings: projectValues(assetBindings, projectRef),
hosts: projectHosts.map((host) => ({
...withHealth("host", host, host.hostRef),
telemetry: host.telemetry ?? emptyPreviewHostTelemetry(),
})),
endpoints: projectValues(endpoints, projectRef),
deployments: projectValues(deployments, projectRef),
serviceInstances: projectServices.map((service) =>
withHealth("service-instance", service, service.serviceInstanceRef)),
policies: {
restrictedIdentifiers: "masked-only",
managementCredentials: "opaque-reference-only",
missingHealthEvidence: "unobserved-not-unhealthy",
arbitraryConsole: "disabled",
},
};
}
function latestPreviewHealth(projectRef, subjectKind, subjectRef) {
const values = projectValues(healthObservations, projectRef)
.filter((item) => item.subjectKind === subjectKind && item.subjectRef === subjectRef)
.sort((left, right) => right.observedAt.localeCompare(left.observedAt));
const latest = values[0];
if (!latest) return { state: "unobserved", freshness: "missing", observationRef: null };
const fresh = new Date(latest.expiresAt).valueOf() > Date.now();
return {
state: fresh ? latest.observedState : "unobserved",
freshness: fresh ? "fresh" : "stale",
lastObservedState: latest.observedState,
evidenceClass: latest.evidenceClass,
observedAt: latest.observedAt,
expiresAt: latest.expiresAt,
observationRef: latest.healthObservationRef,
};
}
@@ -178,6 +254,10 @@ export function createLocalPreviewDeviceCore({ fixture = null } = {}) {
routes,
sessions,
configurationStates,
hosts,
deployments,
serviceInstances,
healthObservations,
});
else if (fixture != null && fixture !== "") {
throw serviceError("device_manager_preview_fixture_invalid", 400);
@@ -439,6 +519,12 @@ export function createLocalPreviewDeviceCore({ fixture = null } = {}) {
displayName: input.displayName,
deploymentRef: input.deploymentRef ?? null,
lifecycleState: input.lifecycleState ?? "provisioning",
channel: existing?.channel ?? {
lifecycleState: "disabled",
generationRef: null,
runtimeState: "disabled",
lastErrorCode: null,
},
createdAt: existing?.createdAt || now(),
updatedAt: now(),
};
@@ -602,6 +688,167 @@ export function createLocalPreviewDeviceCore({ fixture = null } = {}) {
if (command === "devices:claim") {
throw serviceError("device_discovery_not_found", 404);
}
if (command === "assets:ensure") {
if (!projects.has(input.projectRef)) throw serviceError("device_project_not_found", 404);
const existing = projectValues(assets, input.projectRef)
.find((item) => item.assetKey === input.assetKey);
const assetRef = existing?.assetRef || `asset:${randomUUID()}`;
const asset = {
assetRef,
projectRef: input.projectRef,
assetKey: input.assetKey,
displayName: input.displayName,
assetTypeRef: input.assetTypeRef,
lifecycleState: input.lifecycleState ?? "active",
ontology: previewOntology("asset.asset"),
};
assets.set(assetRef, asset);
audit(actor, input.projectRef, createdEvent(existing, "asset"));
return { replayed: false, result: { created: !existing, asset } };
}
if (command === "asset-bindings:ensure") {
const device = devices.get(input.deviceRef);
const asset = assets.get(input.assetRef);
if (!device || device.projectRef !== input.projectRef) {
throw serviceError("device_not_found", 404);
}
if (!asset || asset.projectRef !== input.projectRef) {
throw serviceError("device_asset_not_found", 404);
}
const existing = projectValues(assetBindings, input.projectRef)
.find((item) => item.bindingKey === input.bindingKey);
const assetBindingRef = existing?.assetBindingRef || `asset-binding:${randomUUID()}`;
const assetBinding = {
assetBindingRef,
projectRef: input.projectRef,
bindingKey: input.bindingKey,
deviceRef: input.deviceRef,
deviceName: device.displayName,
assetRef: input.assetRef,
assetName: asset.displayName,
bindingKind: input.bindingKind ?? "tracking",
validFrom: input.validFrom,
validTo: null,
provenanceRef: input.provenanceRef,
ontology: previewOntology("device.asset_binding"),
};
assetBindings.set(assetBindingRef, assetBinding);
audit(actor, input.projectRef, createdEvent(existing, "asset_binding"));
return { replayed: false, result: { created: !existing, assetBinding } };
}
if (command === "asset-bindings:close") {
const existing = assetBindings.get(input.assetBindingRef);
if (!existing || existing.projectRef !== input.projectRef || existing.validTo) {
throw serviceError("device_asset_binding_not_closable", 409);
}
const assetBinding = { ...existing, validTo: input.validTo };
assetBindings.set(existing.assetBindingRef, assetBinding);
audit(actor, input.projectRef, "asset_binding.closed");
return { replayed: false, result: { closed: true, assetBinding } };
}
if (command === "infrastructure-hosts:ensure") {
if (!projects.has(input.projectRef)) throw serviceError("device_project_not_found", 404);
const existing = projectValues(hosts, input.projectRef)
.find((item) => item.hostKey === input.hostKey);
const hostRef = existing?.hostRef || `host:${randomUUID()}`;
const host = {
hostRef,
projectRef: input.projectRef,
hostKey: input.hostKey,
displayName: input.displayName,
providerRef: input.providerRef ?? null,
externalRef: input.externalRef ?? null,
managementCredentialConfigured: Boolean(input.managementCredentialRef),
lifecycleState: input.lifecycleState ?? "provisioning",
ontology: previewOntology("infrastructure.host"),
};
hosts.set(hostRef, host);
audit(actor, input.projectRef, createdEvent(existing, "infrastructure_host"));
return { replayed: false, result: { created: !existing, host } };
}
if (command === "infrastructure-endpoints:ensure") {
const host = hosts.get(input.hostRef);
if (!host || host.projectRef !== input.projectRef) throw serviceError("device_host_not_found", 404);
const existing = projectValues(endpoints, input.projectRef)
.find((item) => item.hostRef === input.hostRef && item.endpointKey === input.endpointKey);
const endpointRef = existing?.endpointRef || `endpoint:${randomUUID()}`;
const endpoint = {
endpointRef,
projectRef: input.projectRef,
hostRef: input.hostRef,
endpointKey: input.endpointKey,
purpose: input.purpose,
endpointUri: input.endpointUri,
lifecycleState: input.lifecycleState ?? "active",
ontology: previewOntology("infrastructure.endpoint"),
};
endpoints.set(endpointRef, endpoint);
audit(actor, input.projectRef, createdEvent(existing, "infrastructure_endpoint"));
return { replayed: false, result: { created: !existing, endpoint } };
}
if (command === "infrastructure-deployments:ensure") {
const host = hosts.get(input.hostRef);
if (!host || host.projectRef !== input.projectRef) throw serviceError("device_host_not_found", 404);
const existing = projectValues(deployments, input.projectRef)
.find((item) => item.deploymentKey === input.deploymentKey);
const deploymentRef = existing?.deploymentRef || `deployment:${randomUUID()}`;
const deployment = {
deploymentRef,
projectRef: input.projectRef,
hostRef: input.hostRef,
deploymentKey: input.deploymentKey,
displayName: input.displayName,
artifactRef: input.artifactRef,
artifactDigest: input.artifactDigest,
lifecycleState: input.lifecycleState ?? "desired",
ontology: previewOntology("infrastructure.deployment"),
};
deployments.set(deploymentRef, deployment);
audit(actor, input.projectRef, createdEvent(existing, "infrastructure_deployment"));
return { replayed: false, result: { created: !existing, deployment } };
}
if (command === "infrastructure-service-instances:ensure") {
const host = hosts.get(input.hostRef);
const deployment = deployments.get(input.deploymentRef);
if (!host || host.projectRef !== input.projectRef) throw serviceError("device_host_not_found", 404);
if (!deployment || deployment.projectRef !== input.projectRef) {
throw serviceError("device_deployment_not_found", 404);
}
const existing = projectValues(serviceInstances, input.projectRef)
.find((item) => item.hostRef === input.hostRef && item.serviceKey === input.serviceKey);
const serviceInstanceRef = existing?.serviceInstanceRef || `service-instance:${randomUUID()}`;
const serviceInstance = {
serviceInstanceRef,
projectRef: input.projectRef,
hostRef: input.hostRef,
deploymentRef: input.deploymentRef,
edgeRef: input.edgeRef ?? null,
serviceKey: input.serviceKey,
displayName: input.displayName,
serviceRole: input.serviceRole,
lifecycleState: input.lifecycleState ?? "provisioning",
ontology: previewOntology("infrastructure.service_instance"),
};
serviceInstances.set(serviceInstanceRef, serviceInstance);
audit(actor, input.projectRef, createdEvent(existing, "infrastructure_service_instance"));
return { replayed: false, result: { created: !existing, serviceInstance } };
}
if (command === "health-observations:record") {
const healthObservationRef = `health-observation:${randomUUID()}`;
const healthObservation = {
healthObservationRef,
projectRef: input.projectRef,
subjectKind: input.subjectKind,
subjectRef: input.subjectRef,
observedState: input.observedState,
evidenceClass: input.evidenceClass,
observedAt: input.observedAt,
expiresAt: input.expiresAt,
};
healthObservations.set(healthObservationRef, healthObservation);
audit(actor, input.projectRef, "health_observation.recorded");
return { replayed: false, result: { recorded: true, healthObservation } };
}
if (command === "devices:update") {
const device = devices.get(input.deviceRef);
if (!device || device.projectRef !== input.projectRef) {
@@ -652,6 +899,92 @@ function createdEvent(existing, resource) {
return `${resource}.${existing ? "updated" : "created"}`;
}
function previewOntology(entityId) {
return { entityId, catalogHash: "229c61c02a790906" };
}
function emptyPreviewHostTelemetry() {
return {
state: "unobserved",
freshness: "missing",
observedAt: null,
receivedAt: null,
expiresAt: null,
current: null,
history: [],
observation: null,
};
}
function previewHostTelemetry(hostRef, serviceInstanceRef, edgeRef) {
const now = Date.now();
const history = Array.from({ length: 60 }, (_, index) => {
const observedAt = new Date(now - (59 - index) * 2_000).toISOString();
const phase = index / 7;
return {
observedAt,
cpuUsagePercent: 18 + Math.sin(phase) * 8 + (index % 5),
memoryUsedPercent: 42 + Math.sin(phase / 2) * 3,
network: [{
interface: "eth0",
bytesReceived: 8_000_000 + index * (32_000 + (index % 4) * 4_000),
bytesSent: 3_000_000 + index * (14_000 + (index % 3) * 2_000),
}],
};
});
const observedAt = history.at(-1).observedAt;
const current = {
schemaVersion: "nodedc.infrastructure.host-telemetry.v1",
profile: "linux-host-telegraf-v1",
hostKey: "robot2b-b2-edge-vps",
observedAt,
source: {
agent: "telegraf",
agentVersion: "1.38.4",
collectorRef: "service:nodedc-host-telemetry-agent",
},
hardware: {
hostname: "koffyvngij",
architecture: "x64",
platform: "linux",
kernelRelease: "6.8.0-79-generic",
cpuModel: "AMD EPYC Processor (KVM)",
logicalProcessors: 1,
},
cpu: { usagePercent: history.at(-1).cpuUsagePercent, load1: 0.31, load5: 0.24, load15: 0.18 },
memory: { totalBytes: 1_007_681_536, availableBytes: 570_425_344, freeBytes: null, usedBytes: 437_256_192, usedPercent: history.at(-1).memoryUsedPercent },
swap: { totalBytes: 0, availableBytes: null, freeBytes: 0, usedBytes: 0, usedPercent: 0 },
system: { uptimeSeconds: 723_419, users: 1, processes: { total: 118, running: 2, sleeping: 115, blocked: 0, zombies: 1 } },
disks: [{ device: "/dev/vda1", mount: "/", filesystem: "ext4", totalBytes: 21_474_836_480, freeBytes: 14_495_514_624, usedBytes: 6_979_321_856, usedPercent: 32.5 }],
network: [{ interface: "eth0", bytesReceived: history.at(-1).network[0].bytesReceived, bytesSent: history.at(-1).network[0].bytesSent, packetsReceived: 91_482, packetsSent: 64_501, errorsReceived: 0, errorsSent: 0, droppedReceived: 0, droppedSent: 0 }],
services: [
{ name: "nodedc-device-edge-channel.service", loadState: "loaded", activeState: "active", subState: "running", memoryBytes: 71_303_168, restarts: 0, pid: 1482 },
{ name: "nodedc-host-telemetry-agent.service", loadState: "loaded", activeState: "active", subState: "running", memoryBytes: 35_651_584, restarts: 0, pid: 1510 },
{ name: "ssh.service", loadState: "loaded", activeState: "active", subState: "running", memoryBytes: 8_388_608, restarts: 0, pid: 712 },
],
};
return {
state: "online",
freshness: "fresh",
observedAt,
receivedAt: new Date(now).toISOString(),
expiresAt: new Date(now + 15_000).toISOString(),
current,
history,
observation: {
observationRef: "observation:preview-host-telemetry",
entityId: "observation.observation",
catalogHash: "229c61c02a790906",
targetRef: hostRef,
serviceInstanceRef,
edgeRef,
profileRef: "linux-host-telegraf-v1",
source: { ...current.source, provenanceRef: `${edgeRef}:${current.source.collectorRef}` },
observedProperties: ["host.cpu.utilization", "host.memory.utilization", "host.disk.utilization", "host.network.counters", "host.systemd.unit-state"],
},
};
}
function requirePlatformOwner(actor) {
if (actor?.hubRole !== "owner") {
throw serviceError("device_platform_catalog_access_denied", 403);
@@ -667,6 +1000,10 @@ function seedArusnaviB2Preview({
routes,
sessions,
configurationStates,
hosts,
deployments,
serviceInstances,
healthObservations,
}) {
const timestamp = new Date().toISOString();
const ownerScopeRef = "owner-scope:78da71d5-f48f-4de0-8e47-729f6d644151";
@@ -675,6 +1012,9 @@ function seedArusnaviB2Preview({
const edgeRef = "edge:73da0c42-a641-4559-b8f7-23509b60bfe9";
const routeRef = "route:fef9b7a0-a462-4d68-9991-af026203368b";
const sessionRef = "session:57ead610-47de-45f7-a42d-fbe4fa0aba38";
const hostRef = "host:adf2a5b6-3c0b-4a39-998c-07dfb7818ad1";
const deploymentRef = "deployment:49b296f8-4cc8-470f-9dc1-2e3a543fd224";
const serviceInstanceRef = "service-instance:01f14736-f5c2-4867-9cbc-2d268996a871";
const scope = {
ownerScopeRef,
scopeKind: "personal",
@@ -716,9 +1056,61 @@ function seedArusnaviB2Preview({
displayName: "Preview VPS edge",
deploymentRef: "deployment:preview",
lifecycleState: "active",
channel: {
lifecycleState: "active",
generationRef: "channel-generation:preview",
runtimeState: "accepted",
lastErrorCode: null,
},
createdAt: timestamp,
updatedAt: timestamp,
});
hosts.set(hostRef, {
hostRef,
projectRef,
hostKey: "robot2b-b2-edge-vps",
displayName: "Robot2B B2 Edge VPS",
providerRef: "provider:beget",
externalRef: "host:koffyvngij",
managementCredentialConfigured: true,
lifecycleState: "active",
telemetry: previewHostTelemetry(hostRef, serviceInstanceRef, edgeRef),
ontology: previewOntology("infrastructure.host"),
});
deployments.set(deploymentRef, {
deploymentRef,
projectRef,
hostRef,
deploymentKey: "device-edge-vps-command-transport",
displayName: "Device Edge VPS runtime",
artifactRef: "device-edge-vps-command-transport-20260812-013",
artifactDigest: "sha256:c7486ec879681ddd706f229b628c8556ca8c9ccc4f152a85debb409c302759ef",
lifecycleState: "active",
ontology: previewOntology("infrastructure.deployment"),
});
serviceInstances.set(serviceInstanceRef, {
serviceInstanceRef,
projectRef,
hostRef,
deploymentRef,
edgeRef,
serviceKey: "device-edge",
displayName: "Robot2B B2 Device Edge",
serviceRole: "device.edge",
lifecycleState: "active",
ontology: previewOntology("infrastructure.service_instance"),
});
const healthObservationRef = "health-observation:b912a45a-2b97-4562-8f9e-824cc24e0710";
healthObservations.set(healthObservationRef, {
healthObservationRef,
projectRef,
subjectKind: "host",
subjectRef: hostRef,
observedState: "reachable",
evidenceClass: "agent.telemetry",
observedAt: timestamp,
expiresAt: new Date(Date.now() + 60_000).toISOString(),
});
routes.set(routeRef, {
routeRef,
projectRef,
@@ -857,6 +1249,7 @@ const ownerCapabilities = Object.freeze([
"project.manage",
"access.manage",
"inventory.read",
"asset.manage",
"device.enroll",
"device.claim",
"device.transfer",
@@ -864,6 +1257,9 @@ const ownerCapabilities = Object.freeze([
"route.manage",
"binding.manage",
"telemetry.observe",
"observation.write",
"infrastructure.read",
"infrastructure.manage",
"configuration.read",
"configuration.manage",
"command.plan",
@@ -907,7 +1303,7 @@ function normalizeBaseUrl(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
: "device_core_unavailable";
}
@@ -60,6 +60,36 @@ test("Device Core client accepts only canonical commands and entity refs", async
);
});
test("Device Core client merges workspace and ontology projections", async () => {
const calls = [];
const client = createDeviceCoreClient({
baseUrl: "http://127.0.0.1:3210",
token,
fetchImpl: async (url) => {
calls.push(String(url));
if (String(url).endsWith("/ontology")) {
return jsonResponse(200, {
ok: true,
projection: {
ontology: { catalogHash: "229c61c02a790906", packages: [] },
assets: [], assetBindings: [], hosts: [], endpoints: [],
deployments: [], serviceInstances: [], policies: {},
},
});
}
return jsonResponse(200, { ok: true, workspace: { project: { projectRef: "project:test" } } });
},
});
const workspace = await client.getWorkspace(
actor,
"project:11111111-1111-4111-8111-111111111111",
);
assert.equal(workspace.ontology.ontology.catalogHash, "229c61c02a790906");
assert.equal(calls.length, 2);
assert.ok(calls.some((value) => value.endsWith("/workspace")));
assert.ok(calls.some((value) => value.endsWith("/ontology")));
});
test("local preview is empty and creates resources only through canonical commands", async () => {
const client = createLocalPreviewDeviceCore();
assert.deepEqual(await client.listProjects(actor), []);
@@ -81,6 +111,47 @@ test("local preview is empty and creates resources only through canonical comman
assert.equal(created.result.created, true);
const projectRef = created.result.project.projectRef;
const host = await client.execute("infrastructure-hosts:ensure", actor, {
projectRef,
hostKey: "preview-vps",
displayName: "Preview VPS",
providerRef: "provider:preview",
externalRef: "provider-resource:preview-vps",
managementCredentialRef: "secret-ref:device-core/preview-vps",
lifecycleState: "active",
});
const deployment = await client.execute("infrastructure-deployments:ensure", actor, {
projectRef,
hostRef: host.result.host.hostRef,
deploymentKey: "preview-edge",
displayName: "Preview Edge deployment",
artifactRef: "artifact:device-edge/1.0.0",
artifactDigest: `sha256:${"c".repeat(64)}`,
lifecycleState: "active",
});
await client.execute("infrastructure-service-instances:ensure", actor, {
projectRef,
hostRef: host.result.host.hostRef,
deploymentRef: deployment.result.deployment.deploymentRef,
edgeRef: null,
serviceKey: "device-edge",
displayName: "Device Edge",
serviceRole: "device.edge",
lifecycleState: "active",
});
await client.execute("health-observations:record", actor, {
projectRef,
subjectKind: "host",
subjectRef: host.result.host.hostRef,
observedState: "reachable",
evidenceClass: "manual",
sourceRef: "test:preview",
schemaRef: "nodedc.health.test.v1",
evidence: {},
observedAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 60_000).toISOString(),
});
await client.execute("collections:ensure", actor, {
projectRef,
collectionKey: "field-devices",
@@ -217,6 +288,10 @@ test("local preview is empty and creates resources only through canonical comman
assert.equal(workspace.grants.length, 2);
assert.ok(workspace.auditEvents.some((event) => event.eventType === "device_binding.created"));
assert.equal(workspace.policies.commandTransport, "disabled");
assert.equal(workspace.ontology.hosts[0].health.state, "reachable");
assert.equal(workspace.ontology.serviceInstances[0].serviceRole, "device.edge");
assert.equal(workspace.ontology.hosts[0].managementCredentialConfigured, true);
assert.equal(JSON.stringify(workspace).includes("secret-ref:device-core/preview-vps"), false);
assert.deepEqual(workspace.devices, []);
});
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { basename, dirname, extname, join, resolve, sep } from "node:path";
const DEFAULT_ACCENT = "#b9ff4a";
const DEFAULT_ACCENT = "#f5f5f5";
export function createDeviceManagerPresentationStore({
layoutPath,
@@ -12,6 +12,8 @@ import {
test("Device Core environment defaults to the product-level canonical identity", () => {
const presentation = defaultPresentation();
assert.equal(presentation.environment.theme, "dark");
assert.equal(presentation.environment.accentHex, "#f5f5f5");
assert.deepEqual(presentation.environment.overview, {
headerLabel: "Device Core",
eyebrow: "NODEDC / DEVICE CORE",
@@ -27,6 +29,115 @@ test("Device Core environment defaults to the product-level canonical identity",
});
});
test("environment accent keeps a valid user choice and falls back to neutral white", () => {
assert.equal(
normalizeEnvironmentPresentation({ accentHex: "#8A2BE2" }).accentHex,
"#8a2be2",
);
assert.equal(
normalizeEnvironmentPresentation({ accentHex: "not-a-color" }).accentHex,
"#f5f5f5",
);
});
test("production Compose provides exact persistent writable presentation storage", async () => {
const compose = await readFile(
new URL("../../../docker-compose.device-manager.yml", import.meta.url),
"utf8",
);
for (const expected of [
"NODEDC_DEVICE_MANAGER_PRESENTATION_PATH: /var/lib/nodedc-device-manager/device-manager-presentation.json",
"NODEDC_DEVICE_MANAGER_MEDIA_ROOT: /var/lib/nodedc-device-manager/media",
"source: /volume1/docker/nodedc-device-plane/data/device-manager",
"target: /var/lib/nodedc-device-manager",
"read_only: false",
"create_host_path: false",
]) assert.ok(compose.includes(expected), expected);
const client = await readFile(
new URL("../src/DeviceManagerApp.tsx", import.meta.url),
"utf8",
);
assert.ok(client.includes('accentHex: "#f5f5f5"'));
assert.ok(!client.includes("#b9ff4a"));
});
test("Device Core overview follows the Mission Core landing-stage geometry", async () => {
const styles = await readFile(
new URL("../src/styles.css", import.meta.url),
"utf8",
);
for (const expected of [
".device-manager-stage {\n height: 100%;\n overflow: hidden;",
"left: clamp(2rem, 5vw, 6rem);",
"width: min(39rem, 50%);",
"transform: translateY(-55%);",
"linear-gradient(90deg, rgb(5 6 8 / 0.82) 0%, rgb(5 6 8 / 0.54) 46%, rgb(5 6 8 / 0.24) 100%)",
"font-size: clamp(3rem, 7vw, 7.6rem);",
]) assert.ok(styles.includes(expected), expected);
assert.ok(!/\.device-manager-home\s*\{[^}]*max-width:\s*1420px/s.test(styles));
const client = await readFile(
new URL("../src/DeviceManagerApp.tsx", import.meta.url),
"utf8",
);
assert.ok(client.includes('className="device-manager-home"'));
assert.ok(client.includes('data-has-media={hasMedia ? "true" : undefined}'));
assert.ok(!client.includes('<GlassSurface className="device-manager-home"'));
});
test("host hardware monitoring retains the established geometry", async () => {
const client = await readFile(
new URL("../src/DeviceControlViews.tsx", import.meta.url),
"utf8",
);
const styles = await readFile(
new URL("../src/styles.css", import.meta.url),
"utf8",
);
const infrastructureSource = client.slice(
client.indexOf("function HostsView"),
client.indexOf("function SessionsView"),
);
for (const expected of [
'className="infrastructure-system-workspace host-monitoring-workspace"',
'className="host-monitoring-series-grid"',
'className="host-monitoring-hardware"',
'className="host-monitoring-hardware-facts"',
'className="infrastructure-runtime-grid"',
'percentageTelemetryWindow(cpuHistory, 5)',
'percentageTelemetryWindow(memoryHistory, 4)',
'className="host-monitoring-series__range"',
'resource={networkRate.received == null ? "нет данных" : "входящий трафик"}',
'if (!counters.length) return null;',
]) assert.ok(infrastructureSource.includes(expected), expected);
for (const expected of [
".infrastructure-system-workspace {",
".infrastructure-overview-block,",
".infrastructure-hosts-block,",
".infrastructure-host-card__summary {",
"align-items: center;",
".infrastructure-host-card__freshness[data-freshness=\"fresh\"] {",
".infrastructure-host-card[data-expanded=\"true\"] .infrastructure-host-card__toggle svg {",
".infrastructure-host-relations {",
"grid-template-columns: repeat(3, minmax(0, 1fr));",
"grid-template-columns: repeat(4, minmax(0, 1fr));",
".host-monitoring-series polyline {",
"stroke: var(--nodedc-text-primary);",
".host-monitoring-hardware-facts {",
"grid-template-columns: repeat(2, minmax(0, 1fr));",
]) assert.ok(styles.includes(expected), expected);
assert.ok(!infrastructureSource.includes("<ResourceCard"));
assert.ok(!infrastructureSource.includes('title="Сервисы хостов"'));
assert.ok(!infrastructureSource.includes('title="Deployments и endpoints"'));
assert.ok(!infrastructureSource.includes("ceiling={100}"));
assert.ok(!infrastructureSource.includes("Канонический ontology catalog"));
assert.ok(!styles.includes("background: var(--infrastructure-panel-soft);"), "Functional panels must not add nested black surfaces");
assert.ok(!styles.includes(".host-telemetry-metric,"));
assert.ok(!styles.includes(".host-telemetry-facts"));
});
test("legacy single teaser migrates into the environment media playlist", () => {
const environment = normalizeEnvironmentPresentation({
defaultTeaser: {
@@ -60,6 +171,23 @@ test("environment media accepts MOV even when the browser omits or varies its MI
}
});
test("environment media persists an MP4 upload in the configured data root", async (t) => {
const root = await mkdtemp(join(tmpdir(), "nodedc-device-presentation-mp4-"));
t.after(() => rm(root, { recursive: true, force: true }));
const store = createDeviceManagerPresentationStore({
layoutPath: join(root, "device-manager-presentation.json"),
uploadRoot: join(root, "media"),
});
const uploaded = await store.saveMedia({
bytes: Buffer.from("mp4-payload"),
contentType: "video/mp4",
originalName: "environment.mp4",
kind: "background",
});
assert.match(uploaded.fileSrc, /^\/device-manager-media\/background-[0-9a-f-]+\.mp4$/);
assert.equal(await readFile(store.resolveMedia(uploaded.fileSrc), "utf8"), "mp4-payload");
});
test("environment presentation persists ordered mixed media and image duration", async (t) => {
const root = await mkdtemp(join(tmpdir(), "nodedc-device-presentation-"));
t.after(() => rm(root, { recursive: true, force: true }));
@@ -68,6 +196,8 @@ test("environment presentation persists ordered mixed media and image duration",
uploadRoot: join(root, "media"),
});
const next = defaultPresentation();
next.environment.theme = "light";
next.environment.accentHex = "#8a2be2";
next.environment.overview.background = {
enabled: true,
imageDurationSeconds: 17,
@@ -93,6 +223,8 @@ test("environment presentation persists ordered mixed media and image duration",
await store.write(next);
const restored = await store.read();
assert.equal(restored.environment.theme, "light");
assert.equal(restored.environment.accentHex, "#8a2be2");
assert.equal(restored.environment.overview.background.imageDurationSeconds, 17);
assert.deepEqual(
restored.environment.overview.background.items.map((item) => item.id),
@@ -29,6 +29,14 @@ const mutationRoutes = new Map([
["/api/device-manager/enrollment-intents:ensure", "enrollment-intents:ensure"],
["/api/device-manager/devices:claim", "devices:claim"],
["/api/device-manager/devices:update", "devices:update"],
["/api/device-manager/assets:ensure", "assets:ensure"],
["/api/device-manager/asset-bindings:ensure", "asset-bindings:ensure"],
["/api/device-manager/asset-bindings:close", "asset-bindings:close"],
["/api/device-manager/infrastructure-hosts:ensure", "infrastructure-hosts:ensure"],
["/api/device-manager/infrastructure-endpoints:ensure", "infrastructure-endpoints:ensure"],
["/api/device-manager/infrastructure-deployments:ensure", "infrastructure-deployments:ensure"],
["/api/device-manager/infrastructure-service-instances:ensure", "infrastructure-service-instances:ensure"],
["/api/device-manager/health-observations:record", "health-observations:record"],
["/api/device-manager/device-bindings:ensure", "device-bindings:ensure"],
["/api/device-manager/device-bindings:revoke", "device-bindings:revoke"],
[
@@ -163,6 +171,19 @@ export function createDeviceManagerServer({
const workspace = await coreClient.getWorkspace(context.actor, projectRef);
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);
if (request.method === "POST" && command) {
const idempotencyKey = singleHeader(request.headers["idempotency-key"]);
@@ -365,7 +386,7 @@ function normalizeStatus(value) {
function safeError(error) {
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
: "device_manager_internal_error";
}
@@ -123,6 +123,34 @@ test("Device Manager BFF exposes an empty, mutation-driven project workspace", a
deploymentRef: "deployment:preview-edge",
lifecycleState: "provisioning",
});
const host = await postJson(`${baseUrl}/api/device-manager/infrastructure-hosts:ensure`, {
projectRef,
hostKey: "preview-vps",
displayName: "Preview VPS",
providerRef: "provider:preview",
externalRef: "provider-resource:preview-vps",
managementCredentialRef: "secret-ref:device-core/preview-vps",
lifecycleState: "active",
});
const deployment = await postJson(`${baseUrl}/api/device-manager/infrastructure-deployments:ensure`, {
projectRef,
hostRef: host.result.host.hostRef,
deploymentKey: "preview-edge",
displayName: "Preview Edge deployment",
artifactRef: "artifact:device-edge/1.0.0",
artifactDigest: `sha256:${"c".repeat(64)}`,
lifecycleState: "active",
});
await postJson(`${baseUrl}/api/device-manager/infrastructure-service-instances:ensure`, {
projectRef,
hostRef: host.result.host.hostRef,
deploymentRef: deployment.result.deployment.deploymentRef,
edgeRef: null,
serviceKey: "device-edge",
displayName: "Device Edge",
serviceRole: "device.edge",
lifecycleState: "active",
});
await postJson(`${baseUrl}/api/device-manager/project-grants:upsert`, {
projectRef,
principalKind: "group",
@@ -141,6 +169,9 @@ test("Device Manager BFF exposes an empty, mutation-driven project workspace", a
assert.equal(workspace.workspace.edges[0].edgeKey, "preview-edge");
assert.equal(workspace.workspace.grants.length, 2);
assert.equal(workspace.workspace.policies.commandTransport, "disabled");
assert.equal(workspace.workspace.ontology.hosts[0].hostKey, "preview-vps");
assert.equal(workspace.workspace.ontology.serviceInstances[0].serviceKey, "device-edge");
assert.equal(JSON.stringify(workspace).includes("secret-ref:device-core/preview-vps"), false);
assert.deepEqual(workspace.workspace.devices, []);
const missingKey = await fetch(`${baseUrl}/api/device-manager/projects:ensure`, {
@@ -176,3 +207,44 @@ async function postJson(url, body, headers = {}) {
assert.equal(payload.ok, true);
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 {
Button,
GlassSurface,
FeatureSettingsWindow,
ConfirmationModal,
ResourceList,
ResourceRow,
Icon,
IconButton,
Select,
@@ -14,6 +17,7 @@ import {
createConfigurationRevision,
setDesiredConfiguration,
updateDevice,
archiveDevice,
} from "./api";
import {
accessLabel,
@@ -27,58 +31,16 @@ import type {
SessionView,
} from "./types";
import { B2TrackerSettings } from "./b2/B2TrackerSettings";
import type { TrackerRef } from "./b2/tracker";
import { useB2Inventory } from "./b2/useB2Inventory";
export type DeviceInventoryDetailState = {
deviceRef: string;
sectionId: string;
editing: boolean;
};
export function DeviceDetailHeaderTools({
device,
detail,
canEdit,
onDetailChange,
}: {
device: DeviceView;
detail: DeviceInventoryDetailState;
canEdit: boolean;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
const catalog = getDeviceProfileCatalog(device.modelProfileRef);
const activeSection = catalog.sections.find((section) => section.id === detail.sectionId)
?? catalog.sections[0];
return (
<div className="device-detail-header-tools">
<Select
className="device-detail-section-select"
label="Раздел устройства"
value={activeSection?.id ?? catalog.sections[0]?.id ?? "passport"}
options={catalog.sections.map((section) => ({
value: section.id,
label: section.label,
}))}
onChange={(sectionId) => onDetailChange({ ...detail, sectionId })}
placement="bottom-end"
minMenuWidth={320}
menuWidth="anchor"
variant="split"
/>
<IconButton
label={detail.editing ? "Завершить редактирование" : "Редактировать устройство"}
disabled={!canEdit}
data-active={detail.editing || undefined}
onClick={() => onDetailChange({
...detail,
editing: !detail.editing,
})}
>
<Icon name="edit" size={17} />
</IconButton>
</div>
);
}
export function DeviceInventoryView({
workspace,
canClaim,
@@ -100,15 +62,22 @@ export function DeviceInventoryView({
onError: (reason: unknown) => void;
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
const [tracker, setTracker] = useState<{ device: TrackerRef; projectRef: string; section: string } | null>(null);
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const [typeFilter, setTypeFilter] = useState("all");
const [archiveTarget, setArchiveTarget] = useState<DeviceView | null>(null);
const [archiving, setArchiving] = useState(false);
const [statusFilter, setStatusFilter] = useState("all");
const [sortOrder, setSortOrder] = useState("activity");
const selectedDevice = workspace.devices.find(
(device) => device.deviceRef === detail?.deviceRef,
) ?? null;
const pendingEnrollments = workspace.enrollments.filter(
(enrollment) => enrollment.lifecycleState !== "claimed",
(enrollment) => ["pending", "observed"].includes(enrollment.lifecycleState),
);
const deviceRows = useMemo(() => workspace.devices
.filter((device) => statusFilter === "archived" ? device.lifecycleState === "suspended" : !["suspended", "retired"].includes(device.lifecycleState))
.filter((device) => typeFilter === "all" || device.modelProfileRef.toLowerCase().includes("b2"))
.map((device) => {
const session = latestSession(workspace, device);
const online = session?.lifecycleState === "online" || device.session?.state === "online";
@@ -128,7 +97,7 @@ export function DeviceInventoryView({
return left.online ? -1 : 1;
}
return String(right.lastSeenAt || "").localeCompare(String(left.lastSeenAt || ""));
}), [sortOrder, statusFilter, workspace]);
}), [sortOrder, statusFilter, typeFilter, workspace]);
useEffect(() => {
if (detail?.deviceRef && !selectedDevice) onDetailChange(null);
@@ -143,32 +112,29 @@ export function DeviceInventoryView({
return () => window.clearInterval(timer);
}, [detail?.deviceRef, onError, onPoll]);
if (selectedDevice && detail) {
return (
<DeviceDetailView
device={selectedDevice}
detail={detail}
workspace={workspace}
canConfigure={canConfigure}
canManageProject={canManageProject}
onDetailChange={onDetailChange}
onSaved={onPoll}
onError={onError}
onBack={() => onDetailChange(null)}
/>
);
}
const remoteRows = (b2.data?.items || []).filter(() => !['pending', 'archived', 'active', 'inactive'].includes(statusFilter))
.sort((a, b) => a.name.localeCompare(b.name, 'ru'));
const count = workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + (b2.data?.items.length || 0);
return (
<div className="device-inventory">
{tracker && tracker.projectRef===workspace.project.projectRef ? <B2TrackerSettings key={`${tracker.projectRef}:${tracker.device.id}`} projectRef={tracker.projectRef} device={tracker.device} initialSection={tracker.section} onClose={()=>setTracker(null)} onError={onError} onChanged={onPoll} canConfigure={canConfigure} canCommand={workspace.project.access.capabilities.includes('command.dispatch')} /> : null}
{selectedDevice && detail ? <DeviceDetailView key={selectedDevice.deviceRef} device={selectedDevice} detail={detail} workspace={workspace}
canConfigure={canConfigure} canManageProject={canManageProject} onDetailChange={onDetailChange} onSaved={onPoll} onError={onError} onBack={() => onDetailChange(null)} /> : null}
<ConfirmationModal open={Boolean(archiveTarget)} title={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить устройство?' : 'Перенести устройство в архив?'} description={archiveTarget?.displayName} confirmLabel={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => {
if (!archiveTarget || archiving) return;
setArchiving(true);
try { await archiveDevice(workspace.project.projectRef, archiveTarget.deviceRef, archiveTarget.lifecycleState !== 'suspended'); setArchiveTarget(null); await onPoll(); } catch (reason) { onError(reason); } finally { setArchiving(false); }
}} />
<div className="device-manager-panel-toolbar device-inventory__toolbar">
<div>
<strong>Реестр устройств</strong>
<p>{workspace.devices.length} зарегистрировано · {pendingEnrollments.length} ожидают подключения</p>
<p>{count} зарегистрировано · {pendingEnrollments.length} ожидают подключения</p>
</div>
</div>
<div className="device-inventory__filters" aria-label="Фильтры устройств">
<Select label="Тип устройства" value={typeFilter} onChange={setTypeFilter} options={[{ value: 'all', label: 'Все типы' }, { value: 'arnavi', label: 'ARNavi B2' }]} />
<Select
label="Состояние"
value={statusFilter}
@@ -177,6 +143,7 @@ export function DeviceInventoryView({
{ value: "active", label: "Активные" },
{ value: "inactive", label: "Неактивные" },
{ value: "pending", label: "Ожидают подключения" },
{ value: "archived", label: "Архив" },
]}
onChange={setStatusFilter}
/>
@@ -193,54 +160,22 @@ export function DeviceInventoryView({
/>
</div>
{statusFilter !== "pending" && !deviceRows.length ? (
<GlassSurface className="device-manager-empty device-inventory__empty" padding="lg" tone="soft">
<Icon name="inbox" size={24} />
<h3>{workspace.devices.length ? "Устройств с таким состоянием нет" : "В проекте пока нет устройств"}</h3>
<p>Добавьте разрешённый трекер через «плюс». Идентификатор попадёт в Device Core по защищённому процессу подключения.</p>
</GlassSurface>
) : statusFilter !== "pending" ? (
<GlassSurface className="device-inventory-table" padding="sm" tone="soft" role="table" aria-label="Устройства проекта">
<div className="device-inventory-table__head" role="row">
<span role="columnheader">Устройство</span>
<span role="columnheader">Профиль</span>
<span role="columnheader">IMEI</span>
<span role="columnheader">ID интеграционного устройства</span>
<span role="columnheader">Канал</span>
<span role="columnheader">Последний пакет</span>
<span aria-hidden="true" />
</div>
{deviceRows.map(({ device, session, online, lastSeenAt }) => {
return (
<Button
key={device.deviceRef}
type="button"
variant="ghost"
className="device-inventory-row"
role="row"
onClick={() => onDetailChange({
deviceRef: device.deviceRef,
sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? "passport",
editing: false,
})}
>
<span className="device-inventory-row__device" role="cell">
<span className="device-inventory-row__icon"><Icon name="apps" size={17} /></span>
<span><strong>{device.displayName}</strong><small>{device.deviceKey || "ключ не назначен"}</small></span>
</span>
<span role="cell">{profileLabel(workspace, device)}</span>
<span role="cell">{deviceIdentifierDisplayValue(device) || "не назначен"}</span>
<span role="cell">{device.integrationDeviceId || "не назначен"}</span>
<span role="cell"><StatusBadge tone={online ? "success" : "neutral"}>{online ? "Онлайн" : session?.lifecycleState || device.lifecycleState}</StatusBadge></span>
<span role="cell">{formatDate(lastSeenAt)}</span>
<span className="device-inventory-row__open" role="cell" aria-hidden="true"><Icon name="chevron-right" size={16} /></span>
</Button>
);
})}
</GlassSurface>
) : null}
{b2.error ? <p role="alert">{b2.error}</p> : null}
{b2.data?.hosts.filter((host) => !host.reachable).map((host) => <ResourceRow key={host.hostRef} title={host.name} status={<StatusBadge tone="warning">Нет связи с VPS</StatusBadge>} />)}
{statusFilter !== 'pending' ? <ResourceList>
{remoteRows.map((device) => <li key={`${device.hostRef}:${device.id}`}><ResourceRow
icon={<Icon name="apps" />} title={device.name || `ARNavi B2 · ${device.number}`} metadata={`ARNavi B2 · ${device.number} · IMEI ${device.identifier.masked}`} description={device.hostName}
actions={<><IconButton label={`Команды: ${device.name || 'ARNavi B2'}`} onClick={()=>setTracker({device,projectRef:workspace.project.projectRef,section:'commands'})}><Icon name="terminal" /></IconButton><IconButton label={`Настройки: ${device.name || 'ARNavi B2'}`} onClick={()=>setTracker({device,projectRef:workspace.project.projectRef,section:'identity'})}><Icon name="settings" /></IconButton></>} /></li>)}
{deviceRows.map(({ device, online, lastSeenAt }) => <li key={device.deviceRef}><ResourceRow
icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`}
description={lastSeenAt ? formatDate(lastSeenAt) : undefined}
status={<StatusBadge tone={online ? 'success' : 'neutral'}>{device.lifecycleState === 'suspended' ? 'В архиве' : online ? 'Онлайн' : 'Не в сети'}</StatusBadge>}
actions={<><IconButton label={`Настройки ${device.displayName}`} onClick={() => onDetailChange({ deviceRef: device.deviceRef, sectionId: getDeviceProfileCatalog(device.modelProfileRef).sections[0]?.id ?? 'passport', editing: false })}><Icon name="settings" /></IconButton>
{canManageProject && !online ? <Button size="compact" disabled={archiving} onClick={() => setArchiveTarget(device)}>{device.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'}</Button> : null}</>} /></li>)}
</ResourceList> : null}
{statusFilter !== 'pending' && !deviceRows.length && !remoteRows.length ? <div className="device-manager-empty device-inventory__empty"><Icon name="inbox" size={24} /><h3>{!b2.data && !b2.error ? 'Загрузка устройств…' : b2.error || b2.data?.hosts.some((host) => !host.reachable) ? 'Реестр VPS недоступен' : statusFilter === 'archived' ? 'Архив пуст' : count ? 'Нет устройств с таким состоянием' : 'В проекте пока нет устройств'}</h3></div> : null}
{(statusFilter === "all" || statusFilter === "pending") ? (
{(statusFilter === "pending" || statusFilter === "all" && pendingEnrollments.length > 0) ? (
<section className="device-inventory__pending" aria-label="Ожидают подключения">
<div className="device-inventory__section-heading">
<div>
@@ -264,9 +199,9 @@ export function DeviceInventoryView({
<p className="device-manager-card-copy">После первого пакета устройство можно принять в реестр. Исходный идентификатор в интерфейсе не раскрывается.</p>
</SettingsCard>
)) : (
<GlassSurface className="device-manager-panel-empty device-inventory__pending-empty" padding="md" tone="soft">
<div className="device-manager-panel-empty device-inventory__pending-empty">
Нет ожидающих подключений.
</GlassSurface>
</div>
)}
</section>
) : null}
@@ -417,35 +352,21 @@ function DeviceDetailView({
};
return (
<FeatureSettingsWindow open title="Настройки устройства" subtitle={workspace.project.name}
identity={{ title: device.displayName, subtitle: `${catalog.vendor} · ${catalog.model}`, avatarLabel: catalog.vendor.slice(0, 2) }}
sections={catalog.sections.map((section) => ({ id: section.id, label: section.label }))}
activeSection={activeSection.id} onSectionChange={(sectionId) => onDetailChange({ ...detail, sectionId })} onClose={onBack}
headerActions={<><IconButton label="Обновить устройство" disabled={saving} onClick={() => void onSaved().catch(onError)}><Icon name="refresh" /></IconButton>
{(canConfigure || canManageProject) ? <IconButton label={detail.editing ? 'Завершить редактирование' : 'Редактировать устройство'} disabled={saving} onClick={() => onDetailChange({ ...detail, editing: !detail.editing })}><Icon name="edit" /></IconButton> : null}</>}>
<div ref={detailRef} className="device-detail">
<div className="device-detail__header">
<IconButton label="Вернуться к списку устройств" onClick={onBack}>
<Icon name="chevron-left" size={18} />
</IconButton>
<div className="device-detail__identity">
<small>{catalog.vendor} · {catalog.model}</small>
<h2>{device.displayName}</h2>
<p>{identifierDisplayValue || "Идентификатор не назначен"} · {device.modelProfileRef}</p>
</div>
<StatusBadge tone={session?.lifecycleState === "online" ? "success" : "neutral"}>
{session?.lifecycleState === "online" ? "Онлайн" : session?.lifecycleState || device.lifecycleState}
</StatusBadge>
</div>
<div className="device-detail__legend" aria-label="Режимы доступа">
<AccessBadge access="read-only" />
<AccessBadge access="managed" />
<AccessBadge access="protected" />
</div>
<GlassSurface className="device-detail__connection" padding="md" tone="soft">
<div className="device-detail__connection">
<div><span>Состояние связи</span><strong>{session?.lifecycleState || device.session?.state || "Нет сессии"}</strong></div>
<div><span>Маршрут</span><strong>{session?.routeName || "Не определён"}</strong></div>
<div><span>Протокол</span><strong>{session?.protocol || profile?.protocol || "Нет данных"}</strong></div>
<div><span>Последняя активность</span><strong>{formatDate(session?.lastSeenAt || device.session?.lastSeenAt)}</strong></div>
<div><span>Пакеты</span><strong>{session?.frameCount ?? 0}</strong></div>
<div><span>Подключено</span><strong>{formatDate(session?.connectedAt)}</strong></div>
</GlassSurface>
</div>
<div className="device-detail__layout">
<section className="device-detail-section">
@@ -475,7 +396,7 @@ function DeviceDetailView({
? draftValues[item.path]
: readPath(context, item.path);
return (
<GlassSurface key={item.key} className="device-detail-field" padding="sm" tone="soft" data-access={access} data-editing={editable || undefined}>
<div key={item.key} className="device-detail-field" data-access={access} data-editing={editable || undefined}>
{editable && item.valueKind === "boolean" ? (
<Switch
checked={Boolean(value)}
@@ -503,7 +424,7 @@ function DeviceDetailView({
{item.description ? <small>{item.description}</small> : null}
</>
)}
</GlassSurface>
</div>
);
})}
</div>
@@ -534,14 +455,15 @@ function DeviceDetailView({
) : null}
<div className="device-detail-section__state">
<span>Desired</span>
<span>Запрошенная конфигурация</span>
<strong>{configurationState?.desiredConfigurationRevisionRef || "Не задано"}</strong>
<span>Applied</span>
<span>Подтверждена устройством</span>
<strong>{configurationState?.appliedConfigurationRevisionRef || "Не подтверждено"}</strong>
</div>
</section>
</div>
</div>
</FeatureSettingsWindow>
);
}
@@ -614,12 +536,12 @@ function AccessNotice({
commandTransport: ProjectWorkspace["policies"]["commandTransport"];
}) {
if (access === "read-only") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="lock" size={15} /><span>Этот блок отражает фактическое состояние устройства и не редактируется.</span></div>;
}
if (access === "protected") {
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="shield" size={15} /><span>Операция требует отдельного подтверждения. Обновление прошивки пилотного B2 запрещено.</span></div>;
}
return <GlassSurface className="device-detail-notice" padding="sm" tone="soft"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></GlassSurface>;
return <div className="device-detail-notice"><Icon name="settings" size={15} /><span>{commandTransport === "typed-service-ping-v1" ? "Изменение создаёт новую desired-ревизию. Статус Applied появится только после подтверждения устройством." : "Настройка поддерживается моделью, но запись включится только после запуска двустороннего командного канала."}</span></div>;
}
function latestSession(workspace: ProjectWorkspace, device: DeviceView): SessionView | null {
+78 -68
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import {
AdminNavigationPanel,
AppHeader,
@@ -9,6 +9,8 @@ import {
Dropdown,
FeatureSettingsWindow,
GlassSurface,
ResourceList,
ResourceRow,
HeaderNavigation,
HeaderProfile,
HeaderWorkspace,
@@ -56,12 +58,14 @@ import type {
ProjectWorkspace,
} from "./types";
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
import { B2AddDevice } from "./b2/B2AddDevice";
import { B2AddHost } from "./b2/B2AddHost";
import { useB2Inventory } from "./b2/useB2Inventory";
import {
DeviceControlView,
type ControlViewId,
} from "./DeviceControlViews";
import {
DeviceDetailHeaderTools,
DeviceInventoryView,
type DeviceInventoryDetailState,
} from "./DeviceInventoryView";
@@ -98,13 +102,10 @@ const sectionNavigation: Record<PrimarySection, NavigationItem[]> = {
{ id: "collections", label: "Коллекции", icon: "folder", capability: "inventory.read" },
],
infrastructure: [
{ id: "infrastructure", label: "Edges и маршруты", icon: "globe", capability: "telemetry.observe" },
{ id: "catalog", label: "Модели и адаптеры", icon: "database", capability: "project.read" },
{ id: "hosts", label: "VPS и хосты", icon: "building", capability: "telemetry.observe" },
],
management: [
{ id: "bindings", label: "Связи с Foundry", icon: "external", capability: "binding.manage" },
{ id: "commands", label: "Команды", icon: "target", capability: "command.plan" },
{ id: "settings", label: "Конфигурации", icon: "settings", capability: "configuration.read" },
],
administration: [
{ id: "audit", label: "Аудит", icon: "clipboard", capability: "audit.read" },
@@ -130,7 +131,7 @@ const emptyMedia = (): DeviceManagerMediaValue => ({
const defaultPresentation = (): DeviceManagerPresentation => ({
environment: {
theme: "dark",
accentHex: "#b9ff4a",
accentHex: "#f5f5f5",
overview: {
headerLabel: "Device Core",
eyebrow: "NODEDC / DEVICE CORE",
@@ -187,10 +188,14 @@ export function DeviceManagerApp() {
const [workspace, setWorkspace] = useState<ProjectWorkspace | null>(null);
const [activeOwnerRef, setActiveOwnerRef] = useState("");
const [activeProjectRef, setActiveProjectRef] = useState("");
const projectRefCurrent = useRef(activeProjectRef);
projectRefCurrent.current = activeProjectRef;
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [projectDialogOpen, setProjectDialogOpen] = useState(false);
const [collectionDialogOpen, setCollectionDialogOpen] = useState(false);
const [addHostOpen, setAddHostOpen] = useState(false);
const [addDeviceOpen, setAddDeviceOpen] = useState(false);
const [enrollmentDialogOpen, setEnrollmentDialogOpen] = useState(false);
const [claimEnrollment, setClaimEnrollment] = useState<EnrollmentView | null>(null);
const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);
@@ -230,6 +235,7 @@ export function DeviceManagerApp() {
useEffect(() => {
applyNodedcTheme(document.documentElement, {
theme: presentation.environment.theme,
appearance: "mission",
accent: hexToRgb(presentation.environment.accentHex),
});
}, [presentation.environment.accentHex, presentation.environment.theme]);
@@ -285,9 +291,11 @@ export function DeviceManagerApp() {
}, [activeOwnerRef, activeProjectRef, visibleProjects]);
const selectProject = (projectRef: string) => {
if (projectRef === activeProjectRef) return;
setInventoryDetail(null);
projectRefCurrent.current = projectRef;
setWorkspace(null);
setActiveProjectRef(projectRef);
shell.closeView();
};
const openSection = (section: PrimarySection) => {
@@ -304,14 +312,17 @@ export function DeviceManagerApp() {
};
const selectOwner = (ownerRef: string) => {
if (ownerRef === activeOwnerRef) return;
setActiveOwnerRef(ownerRef);
setInventoryDetail(null);
setWorkspace(null);
const nextProject = projects.find((project) => project.ownerScope.ownerRef === ownerRef);
if (nextProject) {
projectRefCurrent.current = nextProject.projectRef;
setActiveProjectRef(nextProject.projectRef);
shell.closeView();
}
else {
projectRefCurrent.current = "";
setActiveProjectRef("");
setWorkspace(null);
shell.closeView();
@@ -321,6 +332,7 @@ export function DeviceManagerApp() {
const refreshWorkspace = async () => {
if (!activeProjectRef) return;
const next = await loadWorkspace(activeProjectRef);
if (projectRefCurrent.current !== activeProjectRef) return;
setWorkspace(next);
await refreshProjects();
};
@@ -328,17 +340,14 @@ export function DeviceManagerApp() {
const pollWorkspace = async () => {
if (!activeProjectRef) return;
const next = await loadWorkspace(activeProjectRef);
setWorkspace(next);
if (projectRefCurrent.current === activeProjectRef) setWorkspace(next);
};
if (loading || !session) {
return <div className="device-manager-boot">Подключаем Device Core…</div>;
}
const activeView = shell.activeView;
const selectedInventoryDevice = inventoryDetail
? workspace?.devices.find((device) => device.deviceRef === inventoryDetail.deviceRef) ?? null
: null;
const activeView = visibleNavigationItems.some((item) => item.id === shell.activeView) ? shell.activeView : null;
return (
<>
<ApplicationShell
@@ -404,8 +413,8 @@ export function DeviceManagerApp() {
{activeSection === "devices" && activeProject ? (
<IconButton
label="Подключить устройство"
disabled={!canEnroll || !workspace?.routes.some((route) => route.lifecycleState === "active")}
onClick={() => setEnrollmentDialogOpen(true)}
disabled={!canEnroll}
onClick={() => setAddDeviceOpen(true)}
>
<Icon name="plus" size={16} />
</IconButton>
@@ -481,21 +490,18 @@ export function DeviceManagerApp() {
expanded={shell.contentExpanded}
onExpandedChange={shell.setContentExpanded}
onClose={shell.closeView}
headerTools={activeView === "inventory" && selectedInventoryDevice && inventoryDetail ? (
<DeviceDetailHeaderTools
device={selectedInventoryDevice}
detail={inventoryDetail}
canEdit={canConfigure || canManageProject}
onDetailChange={setInventoryDetail}
/>
) : undefined}
utilityActions={[{
utilityActions={[...(activeView === 'inventory' && canEnroll ? [{
label: 'Добавить устройство', icon: 'plus' as const, onClick: () => setAddDeviceOpen(true),
}] : []), ...(activeView === 'hosts' && capabilities.has('infrastructure.manage') ? [{
label: 'Добавить VPS', icon: 'plus' as const, onClick: () => setAddHostOpen(true),
}] : []), {
label: "Обновить данные",
icon: "refresh",
onClick: () => refreshWorkspace().catch((reason) => setError(errorText(reason))),
}]}
>
<ProjectView
key={activeProjectRef}
view={activeView}
workspace={workspace}
canManageCollections={canManageCollections}
@@ -547,6 +553,8 @@ export function DeviceManagerApp() {
}}
onError={(reason) => setError(errorText(reason))}
/>
{addDeviceOpen && workspace ? <B2AddDevice key={activeProjectRef} workspace={workspace} onClose={() => setAddDeviceOpen(false)} onCreated={async () => { setAddDeviceOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} onLegacy={workspace.routes.some(route => route.lifecycleState === 'active') ? () => { setAddDeviceOpen(false); setEnrollmentDialogOpen(true); } : undefined} /> : null}
{addHostOpen && activeProject ? <B2AddHost key={activeProjectRef} open projectRef={activeProjectRef} onClose={() => setAddHostOpen(false)} onCreated={async () => { setAddHostOpen(false); await refreshWorkspace(); }} onError={(reason) => setError(errorText(reason))} /> : null}
<EnrollmentDialog
open={enrollmentDialogOpen}
workspace={workspace}
@@ -684,6 +692,9 @@ function DeviceStage({
&& primarySections.some((section) => section.value === value)
&& values.indexOf(value) === index
));
const hasMedia = overview.background.enabled && overview.background.items.some(
(item) => Boolean(mediaSource(item)) && Boolean(item.mediaKind),
);
return (
<div className="device-manager-stage">
{error ? (
@@ -694,7 +705,10 @@ function DeviceStage({
</GlassSurface>
) : null}
<GlassSurface className="device-manager-home" padding="lg" tone="soft">
<section
className="device-manager-home"
data-has-media={hasMedia ? "true" : undefined}
>
<EnvironmentBackdrop background={overview.background} />
<div className="device-manager-home__scrim" aria-hidden="true" />
<section className="device-manager-hero">
@@ -715,7 +729,7 @@ function DeviceStage({
</div>
) : null}
</section>
</GlassSurface>
</section>
</div>
);
}
@@ -766,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 }: {
view: ViewId;
workspace: ProjectWorkspace | null;
@@ -793,12 +797,13 @@ function ProjectView({ view, workspace, canManageCollections, canClaim, canConfi
onInventoryDetailChange: (detail: DeviceInventoryDetailState | null) => void;
}) {
if (!workspace) return <div className="device-manager-panel-empty">Загружаем проект…</div>;
if (["catalog", "infrastructure", "sessions", "bindings", "commands", "audit", "access", "settings"].includes(view)) {
if (["catalog", "hosts", "infrastructure", "sessions", "bindings", "commands", "audit", "access", "settings"].includes(view)) {
return <DeviceControlView
view={view as ControlViewId}
workspace={workspace}
session={session}
onRefresh={onRefresh}
onPoll={onPoll}
onError={onError}
/>;
}
@@ -818,7 +823,7 @@ function ProjectView({ view, workspace, canManageCollections, canClaim, canConfi
if (view === "collections") return (
<div className="device-manager-stack">
<div className="device-manager-panel-toolbar">
<p>Коллекции группируют устройства для последующих bindings и задач.</p>
<p>Группы устройств проекта.</p>
<Button icon={<Icon name="plus" />} disabled={!canManageCollections} onClick={onCreateCollection}>Новая коллекция</Button>
</div>
<EntityList
@@ -833,17 +838,27 @@ function ProjectView({ view, workspace, canManageCollections, canClaim, canConfi
/>
</div>
);
return <ProjectOverview key={workspace.project.projectRef} workspace={workspace} />;
}
function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) {
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const incomplete = !b2.data || b2.data.hosts.some((host) => !host.reachable);
const deviceCount = incomplete ? null : workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + b2.data!.items.length;
const deviceDetail = !incomplete ? 'В реестре' : (b2.error || b2.data) ? 'Данные VPS недоступны' : 'Загрузка…';
const metrics = [
{ label: 'Устройства', value: deviceCount, detail: deviceDetail },
{ label: 'Ожидают проверки', value: workspace.discoveries.filter((item) => item.lifecycleState === 'quarantine').length, detail: 'Обнаружены' },
{ label: 'Коллекции', value: workspace.collections.length, detail: 'Группы устройств' },
];
return (
<div className="device-manager-overview-grid">
<Metric label="Устройства" value={workspace.devices.length} detail="inventory" />
<Metric label="Quarantine" value={workspace.discoveries.filter((item) => item.lifecycleState === "quarantine").length} detail="safe projection" />
<Metric label="Коллекции" value={workspace.collections.length} detail="bindings ready" />
<SettingsCard title="Права проекта" description={workspace.project.access.projectRole || "read"}>
<div className="device-manager-capabilities">
{workspace.project.access.capabilities.map((capability) => <StatusBadge key={capability}>{capability}</StatusBadge>)}
</div>
</SettingsCard>
</div>
<ResourceList>
{metrics.map((metric) => (
<li key={metric.label}>
<ResourceRow title={metric.label} metadata={metric.detail} status={<StatusBadge>{metric.value ?? '—'}</StatusBadge>} />
</li>
))}
</ResourceList>
);
}
@@ -926,7 +941,7 @@ function ProjectSettingsDialog({ open, workspace, presentation, onClose, onSaved
avatarUrl: iconPreview ?? undefined,
}}
sections={[
{ id: "identity", label: "Идентичность", icon: "profile", group: "Проект" },
{ id: "identity", label: "Основное", icon: "profile", group: "Проект" },
{ id: "media", label: "Медиа", icon: "image", group: "Оформление" },
]}
activeSection={section}
@@ -1225,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 }) {
if (!items.length) return <div className="device-manager-panel-empty">{empty}</div>;
return <div className="device-manager-entity-list">{items.map((item) => (
<GlassSurface key={item.id} className="device-manager-entity" padding="md" tone="soft">
<span className="device-manager-entity__icon"><Icon name="circle" /></span>
<span className="device-manager-entity__body"><strong>{item.title}</strong><small>{item.subtitle}</small></span>
<StatusBadge tone={item.tone}>{item.status}</StatusBadge>
</GlassSurface>
))}</div>;
return <ResourceList>{items.map((item) => <li key={item.id}><ResourceRow
icon={<Icon name="folder" />} title={item.title} description={item.subtitle}
status={<StatusBadge tone={item.tone}>{item.status}</StatusBadge>} /></li>)}</ResourceList>;
}
function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated, onError }: {
@@ -1271,17 +1282,17 @@ function ProjectDialog({ open, ownerScopes, initialOwnerRef, onClose, onCreated,
await onCreated();
} catch (reason) { onError(reason); } finally { setPending(false); }
};
return <Window open={open} title="Новый Device Project" subtitle={ownerScope?.displayName || "Owner scope недоступен"} onClose={onClose} footer={
return <Window open={open} title="Новый проект" subtitle={ownerScope?.displayName || "Компания недоступна"} onClose={onClose} footer={
<WindowFooterActions><Button variant="ghost" onClick={onClose}>Отмена</Button><Button type="submit" form="device-project-form" variant="primary" disabled={pending || !ownerScope}>{pending ? "Создаём…" : "Создать"}</Button></WindowFooterActions>
}>
<form id="device-project-form" className="device-manager-form" onSubmit={submit}>
<Select
label="Контур проекта"
label="Владелец проекта"
value={ownerRef}
options={ownerScopes.map((scope) => ({
value: scope.ownerRef,
label: scope.displayName,
description: scope.scopeKind === "company" ? "Коммерческий контур" : "Личный контур",
description: scope.scopeKind === "company" ? "Компания" : "Личное пространство",
}))}
onChange={setOwnerRef}
/>
@@ -1345,7 +1356,6 @@ function ClaimDialog({ enrollment, project, onClose, onClaimed, onError }: {
<form id="device-claim-form" className="device-manager-form" onSubmit={submit}>
<TextField label="Название устройства" value={name} onChange={(event) => setName(event.target.value)} required maxLength={160} />
<TextField label="Ключ устройства" value={key} onChange={(event) => setKey(event.target.value.toLowerCase())} required pattern="[a-z][a-z0-9-]{1,62}" />
<p className="device-manager-card-copy">Claim использует только ссылки на enrollment и discovery. Исходный идентификатор не запрашивается повторно.</p>
</form>
</Window>;
}
@@ -1424,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="IMEI" value={imei} onChange={(event) => setImei(event.target.value.replace(/\D/g, "").slice(0, 15))} required pattern="[0-9]{15}" inputMode="numeric" autoComplete="off" />
<TextField label="Истекает" type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} description="Опционально. Время будет сохранено в UTC." />
<p className="device-manager-card-copy">IMEI передаётся один раз по HTTPS в Device Control Core. В базе, audit и ответе останутся только HMAC и маска.</p>
</form>
</Window>;
}
@@ -1449,11 +1458,12 @@ function viewTitle(view: ViewId) {
inventory: "Устройства",
collections: "Коллекции",
catalog: "Модели и адаптеры",
infrastructure: "Edges и маршруты",
sessions: "Gateway sessions",
bindings: "Data bindings",
commands: "Command ledger",
audit: "Immutable audit",
hosts: "VPS и хосты",
infrastructure: "Узлы и маршруты",
sessions: "Подключения устройств",
bindings: "Связи с Foundry",
commands: "Команды",
audit: "Аудит",
access: "Доступ к проекту",
settings: "Настройки и конфигурации",
})[view];
@@ -1462,7 +1472,7 @@ function viewTitle(view: ViewId) {
function sectionForView(view: ViewId): PrimarySection {
if (view === "overview") return "overview";
if (view === "inventory" || view === "collections" || view === "sessions") return "devices";
if (view === "catalog" || view === "infrastructure") return "infrastructure";
if (view === "catalog" || view === "hosts" || view === "infrastructure") return "infrastructure";
if (view === "bindings" || view === "commands" || view === "settings") return "management";
return "administration";
}
+127
View File
@@ -1,10 +1,16 @@
import type {
AdapterPackageView,
AdapterVersionView,
AssetBindingView,
AssetView,
BindingView,
ConfigurationRevisionView,
EdgeView,
ModelProfileView,
InfrastructureDeploymentView,
InfrastructureEndpointView,
InfrastructureHostView,
InfrastructureServiceInstanceView,
ProjectGrantView,
DeviceManagerSession,
DeviceManagerPresentation,
@@ -144,6 +150,120 @@ export async function ensureEnrollmentIntent(input: {
return mutate("/api/device-manager/enrollment-intents:ensure", input);
}
export async function ensureAsset(input: {
projectRef: string;
assetKey: string;
displayName: string;
assetTypeRef: string;
lifecycleState?: "active" | "retired";
}) {
return mutate<{ created: boolean; asset: AssetView }>(
"/api/device-manager/assets:ensure",
input,
);
}
export async function ensureAssetBinding(input: {
projectRef: string;
bindingKey: string;
deviceRef: string;
assetRef: string;
bindingKind: "tracking" | "installed" | "assigned";
validFrom: string;
provenanceRef: string;
}) {
return mutate<{ created: boolean; assetBinding: AssetBindingView }>(
"/api/device-manager/asset-bindings:ensure",
input,
);
}
export async function closeAssetBinding(input: {
projectRef: string;
assetBindingRef: string;
validTo: string;
}) {
return mutate<{ closed: boolean; assetBinding: AssetBindingView }>(
"/api/device-manager/asset-bindings:close",
input,
);
}
export async function ensureInfrastructureHost(input: {
projectRef: string;
hostKey: string;
displayName: string;
providerRef: string | null;
externalRef: string | null;
managementCredentialRef: string | null;
lifecycleState: "provisioning" | "active" | "suspended" | "retired";
}) {
return mutate<{ created: boolean; host: InfrastructureHostView }>(
"/api/device-manager/infrastructure-hosts:ensure",
input,
);
}
export async function ensureInfrastructureEndpoint(input: {
projectRef: string;
hostRef: string;
endpointKey: string;
purpose: "management" | "service" | "monitoring";
endpointUri: string;
lifecycleState: "active" | "disabled" | "retired";
}) {
return mutate<{ created: boolean; endpoint: InfrastructureEndpointView }>(
"/api/device-manager/infrastructure-endpoints:ensure",
input,
);
}
export async function ensureInfrastructureDeployment(input: {
projectRef: string;
hostRef: string;
deploymentKey: string;
displayName: string;
artifactRef: string;
artifactDigest: string;
lifecycleState: "desired" | "applying" | "active" | "failed" | "retired";
}) {
return mutate<{ created: boolean; deployment: InfrastructureDeploymentView }>(
"/api/device-manager/infrastructure-deployments:ensure",
input,
);
}
export async function ensureInfrastructureServiceInstance(input: {
projectRef: string;
hostRef: string;
deploymentRef: string;
edgeRef: string | null;
serviceKey: string;
displayName: string;
serviceRole: string;
lifecycleState: "provisioning" | "active" | "degraded" | "stopped" | "retired";
}) {
return mutate<{ created: boolean; serviceInstance: InfrastructureServiceInstanceView }>(
"/api/device-manager/infrastructure-service-instances:ensure",
input,
);
}
export async function recordHealthObservation(input: {
projectRef: string;
subjectKind: "host" | "service-instance";
subjectRef: string;
observedState: "reachable" | "degraded" | "unreachable";
evidenceClass: "agent_probe" | "channel" | "management_probe" | "manual";
sourceRef: string;
schemaRef: string;
evidence: Record<string, unknown>;
observedAt: string;
expiresAt: string;
}) {
return mutate("/api/device-manager/health-observations:record", input);
}
export async function upsertProjectGrant(input: {
projectRef: string;
principalKind: "user" | "group";
@@ -322,3 +442,10 @@ async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {
}
return body as T;
}
export function archiveDevice(projectRef: string, deviceRef: string, archived: boolean) {
return mutate("/api/device-manager/devices:update", { projectRef, deviceRef, archived });
}
export function archiveHost(projectRef: string, hostRef: string, archived: boolean) {
return mutate("/api/device-manager/infrastructure-hosts:ensure", { projectRef, hostRef, archived });
}
@@ -0,0 +1,92 @@
import { useEffect, useRef, useState } from 'react';
import { Button, Icon, Select, SettingsCard, StatusBadge, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
import type { ProjectWorkspace } from '../types';
import { b2Request } from './api';
import { readB2Usb, supportsB2Usb, type UsbSnapshot } from './usb.mjs';
import './b2.css';
type Host = { hostRef: string; name: string; reachable: boolean; contours: Array<{ id: string; name: string }> };
type Preview = { number: number; identifier: string; firmware: string; configuration: { record_count: number }; parameters: Record<string, number> };
export function B2AddDevice({ workspace, onClose, onCreated, onLegacy }: {
workspace: ProjectWorkspace; onClose: () => void; onCreated: () => Promise<void>;
onError: (error: unknown) => void; onLegacy?: () => void;
}) {
const projectRef = workspace.project.projectRef;
const [hosts, setHosts] = useState<Host[]>([]), [hostRef, setHostRef] = useState(''), [contourId, setContourId] = useState('');
const [name, setName] = useState(''), [method, setMethod] = useState(supportsB2Usb() ? 'usb' : 'manual');
const [imei, setImei] = useState(''), [number, setNumber] = useState('');
const [profile, setProfile] = useState(''), [profiles, setProfiles] = useState<Array<{ id: string; name: string }>>([]);
const [snapshot, setSnapshot] = useState<UsbSnapshot | null>(null), [preview, setPreview] = useState<Preview | null>(null);
const [loading, setLoading] = useState(true), [catalogReady, setCatalogReady] = useState(false), [retry, setRetry] = useState(0);
const [reading, setReading] = useState(false), [pending, setPending] = useState(false), [error, setError] = useState('');
const controller = useRef<AbortController | null>(null), mounted = useRef(true);
useEffect(() => { mounted.current = true; return () => { mounted.current = false; controller.current?.abort(); }; }, []);
useEffect(() => {
let active = true; setLoading(true); setError('');
b2Request<{ hosts: Host[] }>(projectRef, '', 'enrollment-options').then(result => {
if (!active) return; setHosts(result.hosts);
const first = result.hosts.find(host => host.reachable && host.contours.length);
setHostRef(first?.hostRef || ''); setContourId(first?.contours[0]?.id || '');
}).catch(reason => { if (active) setError(reason.message); }).finally(() => { if (active) setLoading(false); });
return () => { active = false; };
}, [projectRef, retry]);
useEffect(() => {
let active = true; setProfiles([]); setProfile(''); setCatalogReady(false); setSnapshot(null); setPreview(null);
if (hostRef && contourId) b2Request<{ profiles: Array<{ id: string; name: string }> }>(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'catalog' } })
.then(result => { if (active) { setProfiles(result.profiles); setCatalogReady(true); } })
.catch(reason => { if (active) setError(reason.message); });
return () => { active = false; };
}, [projectRef, hostRef, contourId, retry]);
const busy = pending || reading;
const host = hosts.find(item => item.hostRef === hostRef);
const canRegister = workspace.project.access.capabilities.includes('device.claim');
const valid = canRegister && catalogReady && Boolean(name.trim()) && (method === 'usb' ? Boolean(snapshot && preview) : /^\d{15}$/.test(imei) && /^\d{1,10}$/.test(number) && Number(number) > 0 && Number(number) <= 4294967295);
function close() { if (!pending) { controller.current?.abort(); onClose(); } }
async function readUsb() {
setError(''); setSnapshot(null); setPreview(null); setReading(true);
const abort = new AbortController(); controller.current = abort;
try {
const observed = await readB2Usb({ signal: abort.signal });
if (abort.signal.aborted) return;
const result = await b2Request<Preview>(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'inspect', usb: observed } });
if (!mounted.current || abort.signal.aborted) return;
setSnapshot(observed); setPreview(result); setName(current => current || `ARNavi B2 · ${result.number}`);
} catch (reason) { if (mounted.current && !abort.signal.aborted) setError(reason instanceof Error ? reason.message : 'Не удалось прочитать USB.'); }
finally { if (mounted.current) setReading(false); }
}
return <Window open title="Добавить устройство" subtitle={workspace.project.name} size="md" onClose={close} footer={
<WindowFooterActions><Button disabled={pending} onClick={close}>Отмена</Button><Button form="b2-add-device" type="submit" disabled={!valid || busy} loading={pending}>Добавить устройство</Button></WindowFooterActions>
}>
<form id="b2-add-device" className="b2-settings" onSubmit={async event => {
event.preventDefault(); if (!valid || busy) return; setPending(true); setError('');
try {
await b2Request(projectRef, hostRef, 'enrollment', { contourId, request: { action: 'register', name: name.trim(),
...(method === 'usb' ? { usb: snapshot } : { imei, number: Number(number) }), ...(profile ? { profile_id: profile } : {}) } });
setSnapshot(null); await onCreated();
} catch (reason) { setError(reason instanceof Error ? reason.message : 'Не удалось добавить устройство.'); }
finally { if (mounted.current) setPending(false); }
}}>
<Select label="Тип устройства" value="arnavi-b2" disabled={busy} onChange={event => { if (event === 'edge') onLegacy?.(); }} options={[{ value: 'arnavi-b2', label: 'ARNavi B2' }, ...(onLegacy ? [{ value: 'edge', label: 'Устройство через Edge' }] : [])]} />
<TextField label="Название" value={name} maxLength={160} required disabled={busy} onChange={event => setName(event.target.value)} />
{loading ? <p role="status">Загрузка подключённых VPS…</p> : hosts.some(item => item.reachable && item.contours.length) ? <>
<Select label="VPS" value={hostRef} disabled={busy} options={hosts.filter(item => item.reachable && item.contours.length).map(item => ({ value: item.hostRef, label: item.name }))} onChange={event => {
setHostRef(event); setContourId(hosts.find(item => item.hostRef === event)?.contours[0]?.id || ''); setError('');
}} />
{(host?.contours.length || 0) > 1 ? <Select label="Контур проекта" value={contourId} disabled={busy} options={host!.contours.map(item => ({ value: item.id, label: item.name }))} onChange={event => setContourId(event)} /> : null}
<Select label="Добавление" value={method} disabled={busy} options={[{ value: 'usb', label: 'Прочитать настройки трекера по USB' }, { value: 'manual', label: 'Ввести IMEI и ID вручную' }]} onChange={event => { setMethod(event); setError(''); }} />
<Select label="Профиль настроек" value={profile} disabled={busy || !catalogReady} options={[{ value: '', label: method === 'usb' ? 'Сохранить настройки трекера' : 'Настроить после добавления' }, ...profiles.map(item => ({ value: item.id, label: item.name }))]} onChange={event => setProfile(event)} />
{method === 'usb' ? <SettingsCard title="USB на этом компьютере">
<div className="b2-settings">
<p>{supportsB2Usb() ? 'Подключите один ARNavi B2 и выберите его USB-порт.' : 'Откройте Device Core в Chrome или Edge для чтения USB. Здесь доступен ручной ввод.'}</p>
{preview ? <><StatusBadge tone="success">Настройки прочитаны</StatusBadge><p>ARNavi B2 · {preview.number} · IMEI {preview.identifier}<br />Прошивка {preview.firmware} · {preview.configuration.record_count} параметров</p></> : null}
<Button disabled={!catalogReady || busy || !supportsB2Usb()} loading={reading} onClick={readUsb}><Icon name="refresh" />{preview ? 'Прочитать повторно' : 'Прочитать настройки по USB'}</Button>
</div>
</SettingsCard> : <><TextField label="IMEI" value={imei} inputMode="numeric" maxLength={15} required disabled={busy} onChange={event => setImei(event.target.value.trim())} /><TextField label="ID трекера" value={number} inputMode="numeric" maxLength={10} required disabled={busy} onChange={event => setNumber(event.target.value.trim())} /></>}
{profile ? <p>Профиль сохранится на VPS. Отправка настроек трекеру — в настройках устройства.</p> : null}
</> : <SettingsCard title="Нет VPS для этого проекта"><p>{hosts.some(item => !item.reachable) ? 'Проверьте доступность VPS и связь контура с этим проектом.' : 'Подключите VPS и свяжите контур с этим проектом в разделе «Инфраструктура».'}</p></SettingsCard>}
{!canRegister ? <p>Для регистрации устройства нужно право «Принятие устройства» в этом проекте.</p> : null}
{error ? <p role="alert">{error}</p> : null}
{!loading && (!catalogReady || error) ? <Button disabled={busy} onClick={() => setRetry(value => value + 1)}>Обновить подключения</Button> : null}
</form>
</Window>;
}
+72
View File
@@ -0,0 +1,72 @@
import { useRef, useState } from 'react';
import { Button, Icon, Select, SettingsCard, TextAreaField, TextField, Window, WindowFooterActions } from '@nodedc/ui-react';
import { b2Request } from './api';
import release from './installer-release.json';
import './b2.css';
const installCommand = `sudo python3 ${release.filename} --device-core`;
const keyCommand = 'sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection';
export function B2AddHost({ open, projectRef, onClose, onCreated, onError }: {
open: boolean; projectRef: string; onClose: () => void; onCreated: () => Promise<void>; onError: (error: unknown) => void;
}) {
const [name, setName] = useState('ARNavi VPS'), [connection, setConnection] = useState('');
const [pending, setPending] = useState(false);
const [downloading, setDownloading] = useState(false);
const fileInput = useRef<HTMLInputElement>(null);
async function downloadInstaller() {
setDownloading(true);
try {
const response = await fetch(`/installers/${release.filename}`, { credentials: 'same-origin', signal: AbortSignal.timeout(45000) });
if (!response.ok) throw new Error('Не удалось скачать установщик. Проверьте вход в Device Core и повторите.');
const bytes = await response.arrayBuffer();
const digest = await crypto.subtle.digest('SHA-256', bytes);
const sha256 = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
if (bytes.byteLength !== release.bytes || sha256 !== release.sha256) throw new Error('Загруженный файл не прошёл проверку. Повторите скачивание.');
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
const link = document.createElement('a'); link.href = url; link.download = release.filename;
document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (error) {
onError(error instanceof Error && ['TimeoutError', 'AbortError'].includes(error.name)
? new Error('Сервер не успел передать установщик. Повторите скачивание.') : error);
} finally { setDownloading(false); }
}
return <Window open={open} title="Добавить VPS" size="lg" onClose={onClose} footer={
<WindowFooterActions><Button onClick={onClose}>Отмена</Button><Button type="submit" form="b2-add-vps" loading={pending} disabled={pending || !name.trim() || !connection.trim()}>Подключить VPS</Button></WindowFooterActions>
}>
<form id="b2-add-vps" className="b2-settings" onSubmit={async (event) => {
event.preventDefault(); if (pending) return;
setPending(true);
try {
await b2Request(projectRef, '', 'register-host', { name: name.trim(), connection });
setConnection(''); await onCreated();
} catch (error) { onError(error); } finally { setPending(false); }
}}>
<Select label="Поддерживаемый VPS" value="arnavi" onChange={() => undefined} options={[{ value: 'arnavi', label: 'ARNavi VPS' }]} />
<div className="b2-onboarding-grid">
<SettingsCard title="1. Установить сервер" description={`ARNavi VPS ${release.version} · Ubuntu Server 24.04 LTS · x86-64`}>
<div className="b2-settings">
<div className="b2-actions"><Button disabled={downloading} loading={downloading} onClick={downloadInstaller}><Icon name="download" />Скачать установщик</Button></div>
<p>Перенесите файл на новый VPS. В его терминале выполните команду и укажите публичный IP или домен.</p>
<TextAreaField label="Установка на VPS" rows={2} readOnly value={installCommand} />
<p>Порты сервера: 19443/TCP для API и 9922/TCP для трекеров. Ключ администратора Device Core создаётся при первой установке.</p>
<TextAreaField label="Получить ключ подключения на VPS" rows={2} readOnly value={keyCommand} />
<p>Скопируйте полученный JSON в блок подключения или загрузите сохранённый файл.</p>
<p className="b2-key-id">SHA-256 установщика: {release.sha256}</p>
</div>
</SettingsCard>
<SettingsCard title="2. Подключить сервер">
<div className="b2-settings">
<TextField label="Название VPS" value={name} maxLength={160} disabled={pending} required onChange={(event) => setName(event.target.value)} />
<Button disabled={pending} onClick={() => fileInput.current?.click()}><Icon name="upload" />Загрузить ключ сервера</Button>
<input ref={fileInput} type="file" hidden accept=".json,application/json" aria-label="Файл ключа сервера" onChange={async (event) => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return;
try { if (file.size > 16384) throw new Error('Файл ключа слишком большой.'); const text = await file.text(); JSON.parse(text); setConnection(text); }
catch { onError(new Error('Не удалось прочитать JSON ключа сервера.')); }
}} />
<TextAreaField label="Ключ администратора VPS · JSON" value={connection} disabled={pending} rows={4} autoComplete="off" spellCheck={false} maxLength={16384} required onChange={(event) => setConnection(event.target.value)} />
</div>
</SettingsCard>
</div>
</form>
</Window>;
}
@@ -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;
}
+727 -62
View File
@@ -5,7 +5,6 @@
.device-control-toolbar {
align-items: center;
padding: 2px 0 14px;
border-bottom: 1px solid var(--nodedc-glass-outline);
}
.device-control-toolbar > p {
@@ -42,8 +41,8 @@
.device-control-resource-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
gap: var(--nodedc-space-3);
grid-template-columns: minmax(0, 1fr);
}
.device-control-row {
@@ -86,10 +85,15 @@
.device-control-command-form {
display: grid;
grid-template-columns: minmax(220px, 1fr) minmax(220px, 1fr) auto;
align-items: end;
align-items: start;
gap: 14px;
}
.device-control-command-form > .nodedc-select-anchor,
.device-control-command-form > .nodedc-button {
margin-top: 1.35rem;
}
.device-control-command-policy p {
margin-top: 5px;
color: var(--nodedc-text-secondary);
@@ -117,9 +121,604 @@
}
.device-control-form {
max-height: min(62vh, 680px);
overflow-y: auto;
padding-right: 3px;
min-width: 0;
}
.infrastructure-system-workspace {
--infrastructure-panel-soft: var(--nodedc-canvas-soft);
--infrastructure-accent-soft: color-mix(in srgb, var(--nodedc-text-primary) 4.5%, transparent);
--infrastructure-hairline: color-mix(in srgb, var(--nodedc-text-primary) 8%, transparent);
display: grid;
min-width: 0;
gap: 1rem;
padding-bottom: 1rem;
}
.infrastructure-overview-block,
.infrastructure-hosts-block,
.infrastructure-assets-block {
min-width: 0;
border-radius: var(--nodedc-radius-card);
padding: 1rem;
}
.infrastructure-eyebrow {
display: block;
color: var(--nodedc-text-muted);
font-size: 0.62rem;
font-weight: 820;
letter-spacing: 0.12em;
line-height: 1.2;
text-transform: uppercase;
}
.infrastructure-workspace-lead,
.infrastructure-section-heading {
display: flex;
min-width: 0;
align-items: flex-start;
justify-content: space-between;
gap: 1.2rem;
}
.infrastructure-workspace-lead {
padding: 0;
}
.infrastructure-workspace-lead h2,
.infrastructure-section-heading h3 {
margin: 0.4rem 0 0;
color: var(--nodedc-text-primary);
letter-spacing: -0.035em;
}
.infrastructure-workspace-lead h2 {
font-size: 1.42rem;
}
.infrastructure-section-heading h3 {
font-size: 1.02rem;
}
.infrastructure-workspace-lead p,
.infrastructure-section-heading p {
max-width: 48rem;
margin: 0.42rem 0 0;
color: var(--nodedc-text-muted);
font-size: 0.68rem;
line-height: 1.48;
}
.infrastructure-workspace-actions,
.infrastructure-section-actions {
display: flex;
flex: 0 0 auto;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 0.55rem;
}
.infrastructure-overview-grid,
.host-monitoring-series-grid {
display: grid;
min-width: 0;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 0.65rem;
}
.infrastructure-overview-block .infrastructure-overview-grid {
margin-top: 1rem;
}
.infrastructure-count-card,
.host-monitoring-series {
min-width: 0;
border-radius: var(--nodedc-radius-card);
}
.infrastructure-count-card {
display: grid;
align-content: center;
gap: 0.3rem;
min-height: 5.4rem;
padding: 0.82rem;
background: var(--infrastructure-accent-soft);
}
.infrastructure-count-card span,
.infrastructure-count-card small,
.host-monitoring-series span {
color: var(--nodedc-text-muted);
font-size: 0.62rem;
}
.infrastructure-count-card strong,
.host-monitoring-series strong {
color: var(--nodedc-text-primary);
font-size: 1.14rem;
font-weight: 720;
letter-spacing: -0.035em;
white-space: nowrap;
}
.infrastructure-count-card small {
overflow: hidden;
font-size: 0.55rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.infrastructure-section {
display: grid;
min-width: 0;
gap: 0.75rem;
}
.infrastructure-section--separated {
padding-top: 0.25rem;
border-top: 1px solid var(--infrastructure-hairline);
}
.infrastructure-runtime-grid,
.infrastructure-asset-grid,
.host-monitoring-network-grid {
display: grid;
min-width: 0;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.7rem;
}
.infrastructure-host-list {
display: grid;
min-width: 0;
gap: 0.5rem;
}
.infrastructure-host-card,
.infrastructure-runtime-card,
.host-monitoring-runtime-card,
.host-monitoring-network-card {
display: grid;
min-width: 0;
gap: 0.9rem;
}
.infrastructure-host-card {
overflow: hidden;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-accent-soft);
}
.infrastructure-host-card__summary,
.infrastructure-runtime-card > header,
.host-monitoring-runtime-card > header {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 0.8rem;
}
.infrastructure-host-card__summary {
min-height: 4.35rem;
padding: 0.62rem 0.72rem;
}
.infrastructure-host-card__identity {
min-width: 0;
}
.infrastructure-host-card__actions {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: 0.6rem;
}
.infrastructure-host-card__freshness {
width: 0.48rem;
height: 0.48rem;
flex: 0 0 0.48rem;
border-radius: 50%;
background: var(--nodedc-text-muted);
}
.infrastructure-host-card__freshness[data-freshness="fresh"] {
background: rgb(var(--nodedc-success-rgb));
}
.infrastructure-host-card__freshness[data-freshness="stale"] {
background: rgb(var(--nodedc-warning-rgb));
}
.infrastructure-host-card__toggle svg {
transition: transform 160ms ease;
}
.infrastructure-host-card[data-expanded="true"] .infrastructure-host-card__toggle svg {
transform: rotate(180deg);
}
.infrastructure-host-card h4,
.infrastructure-runtime-card h3,
.host-monitoring-runtime-card h3 {
margin: 0.38rem 0 0.18rem;
color: var(--nodedc-text-primary);
font-size: 0.9rem;
letter-spacing: -0.025em;
}
.infrastructure-host-card code,
.infrastructure-runtime-card code,
.host-monitoring-runtime-card code {
display: block;
max-width: 23rem;
overflow: hidden;
color: var(--nodedc-text-muted);
font-size: 0.56rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.infrastructure-host-card__details {
display: grid;
min-width: 0;
gap: 0.8rem;
padding: 0 0.72rem 0.72rem;
}
.infrastructure-host-card__facts {
display: grid;
min-width: 0;
grid-template-columns: repeat(4, minmax(0, 1fr));
margin: 0;
padding: 0.72rem;
border-radius: var(--nodedc-radius-control);
}
.infrastructure-host-card__facts > div {
display: grid;
min-width: 0;
gap: 0.22rem;
padding-right: 0.65rem;
}
.infrastructure-host-card__facts dt {
color: var(--nodedc-text-muted);
font-size: 0.58rem;
}
.infrastructure-host-card__facts dd {
overflow: hidden;
margin: 0;
color: var(--nodedc-text-primary);
font-size: 0.67rem;
font-weight: 650;
text-overflow: ellipsis;
white-space: nowrap;
}
.infrastructure-host-relations {
display: grid;
min-width: 0;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.65rem;
}
.infrastructure-host-relations > section {
display: grid;
min-width: 0;
align-content: start;
gap: 0.55rem;
padding: 0.72rem;
border-radius: var(--nodedc-radius-control);
}
.infrastructure-host-relations > section > header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.65rem;
}
.infrastructure-host-relations > section > header strong {
color: var(--nodedc-text-primary);
font-size: 0.68rem;
}
.infrastructure-host-relations > section > p {
margin: 0;
color: var(--nodedc-text-muted);
font-size: 0.58rem;
line-height: 1.45;
}
.infrastructure-host-relations .infrastructure-registry-row {
padding: 0.58rem 0.62rem;
}
.infrastructure-host-relations .infrastructure-registry-row .nodedc-status {
font-size: 0;
}
.infrastructure-host-relations .infrastructure-registry-row .nodedc-status::before {
margin: 0;
}
.infrastructure-host-card dl,
.infrastructure-runtime-card dl,
.host-monitoring-runtime-card dl,
.host-monitoring-network-card dl {
display: grid;
min-width: 0;
grid-template-columns: repeat(4, minmax(0, 1fr));
margin: 0;
gap: 0;
}
.infrastructure-host-card dl > div,
.infrastructure-runtime-card dl > div,
.host-monitoring-runtime-card dl > div,
.host-monitoring-network-card dl > div {
display: grid;
min-width: 0;
gap: 0.22rem;
padding-right: 0.65rem;
}
.infrastructure-host-card dt,
.infrastructure-runtime-card dt,
.host-monitoring-runtime-card dt,
.host-monitoring-network-card dt,
.host-monitoring-hardware-facts dt {
color: var(--nodedc-text-muted);
font-size: 0.58rem;
}
.infrastructure-host-card dd,
.infrastructure-runtime-card dd,
.host-monitoring-runtime-card dd,
.host-monitoring-network-card dd,
.host-monitoring-hardware-facts dd {
min-width: 0;
overflow: hidden;
margin: 0;
color: var(--nodedc-text-primary);
font-size: 0.67rem;
font-weight: 650;
text-overflow: ellipsis;
white-space: nowrap;
}
.infrastructure-host-card footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.8rem;
}
.infrastructure-host-card footer > span {
overflow: hidden;
color: var(--nodedc-text-muted);
font-size: 0.58rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.infrastructure-registry-list {
display: grid;
min-width: 0;
gap: 0.48rem;
}
.infrastructure-registry-row,
.infrastructure-asset-card {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 0.9rem;
padding: 0.72rem 0.8rem;
border-radius: var(--nodedc-radius-control);
}
.infrastructure-registry-row > div,
.infrastructure-asset-card > div {
display: grid;
min-width: 0;
gap: 0.2rem;
}
.infrastructure-registry-row > div:last-child,
.infrastructure-asset-card > div:last-child {
flex: 0 0 auto;
justify-items: end;
}
.infrastructure-registry-row strong,
.infrastructure-asset-card strong {
overflow: hidden;
color: var(--nodedc-text-primary);
font-size: 0.68rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.infrastructure-registry-row small,
.infrastructure-asset-card small {
overflow: hidden;
color: var(--nodedc-text-muted);
font-size: 0.55rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.infrastructure-empty {
padding: 0.8rem;
border-radius: var(--nodedc-radius-control);
color: var(--nodedc-text-muted);
font-size: 0.65rem;
line-height: 1.5;
}
.host-monitoring-series {
overflow: hidden;
padding: 0.82rem 0.82rem 0.32rem;
}
.host-monitoring-series > div {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.75rem;
}
.host-monitoring-series__label {
display: grid;
min-width: 0;
gap: 0.16rem;
}
.host-monitoring-series__label small {
overflow: hidden;
max-width: 11rem;
color: var(--nodedc-text-secondary);
font-size: 0.54rem;
line-height: 1.15;
text-overflow: ellipsis;
white-space: nowrap;
}
.host-monitoring-series svg {
display: block;
width: 100%;
height: 2.45rem;
margin-top: 0.45rem;
}
.host-monitoring-series path {
fill: none;
stroke: var(--infrastructure-hairline);
stroke-width: 0.8;
vector-effect: non-scaling-stroke;
}
.host-monitoring-series polyline {
fill: none;
stroke: var(--nodedc-text-primary);
stroke-linecap: round;
stroke-linejoin: round;
stroke-width: 1.15;
vector-effect: non-scaling-stroke;
}
.host-monitoring-series__range {
display: block;
margin-top: -0.1rem;
color: var(--nodedc-text-secondary);
font-size: 0.5rem;
line-height: 1.2;
text-align: right;
}
.host-monitoring-hardware {
display: grid;
min-width: 0;
gap: 1rem;
}
.host-monitoring-hardware-facts {
display: grid;
min-width: 0;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.7rem;
}
.host-monitoring-hardware-facts dl {
display: grid;
min-width: 0;
grid-template-columns: repeat(2, minmax(0, 1fr));
margin: 0;
gap: 0;
border-radius: var(--nodedc-radius-control);
}
.host-monitoring-hardware-facts dl > div {
display: grid;
min-width: 0;
gap: 0.22rem;
padding: 0.75rem;
}
.host-monitoring-disk-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
gap: 0.55rem;
}
.host-monitoring-disk-list > div {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.8rem;
padding: 0.62rem 0.72rem;
border-radius: var(--nodedc-radius-control);
background: var(--infrastructure-accent-soft);
}
.host-monitoring-disk-list span {
color: var(--nodedc-text-muted);
font-size: 0.61rem;
}
.host-monitoring-disk-list strong {
color: var(--nodedc-text-primary);
font-size: 0.64rem;
}
.host-monitoring-network-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.65rem;
}
.host-monitoring-network-card header strong,
.host-monitoring-network-card header small {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.host-monitoring-network-card header strong {
color: var(--nodedc-text-primary);
font-size: 0.71rem;
}
.host-monitoring-network-card header small {
margin-top: 0.25rem;
color: var(--nodedc-text-muted);
font-size: 0.55rem;
}
.host-monitoring-network-card dl {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.65rem;
}
@media (max-width: 1100px) {
.infrastructure-overview-grid,
.host-monitoring-series-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.host-monitoring-network-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.infrastructure-host-relations {
grid-template-columns: 1fr;
}
}
@media (max-width: 760px) {
@@ -145,6 +744,11 @@
grid-template-columns: 1fr;
}
.device-control-command-form > .nodedc-select-anchor,
.device-control-command-form > .nodedc-button {
margin-top: 0;
}
.device-control-command-policy > .nodedc-status {
grid-column: 2;
justify-self: start;
@@ -158,6 +762,48 @@
grid-column: 2;
justify-content: flex-start;
}
.infrastructure-workspace-lead,
.infrastructure-section-heading {
display: grid;
}
.infrastructure-workspace-actions,
.infrastructure-section-actions {
justify-content: space-between;
}
.infrastructure-overview-grid,
.host-monitoring-series-grid,
.infrastructure-host-list,
.infrastructure-runtime-grid,
.infrastructure-asset-grid,
.host-monitoring-hardware-facts,
.host-monitoring-network-grid {
grid-template-columns: 1fr;
}
.infrastructure-host-card__facts,
.infrastructure-runtime-card dl,
.host-monitoring-runtime-card dl {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.65rem;
}
.infrastructure-host-card__summary,
.infrastructure-registry-row,
.infrastructure-asset-card {
align-items: flex-start;
}
.infrastructure-host-card__summary {
display: grid;
}
.infrastructure-host-card__actions {
width: 100%;
justify-content: flex-end;
}
}
html,
@@ -257,46 +903,56 @@ body {
.device-manager-stage {
height: 100%;
overflow: auto;
padding: clamp(1rem, 2.5vw, 2.5rem);
scrollbar-width: thin;
overflow: hidden;
}
.device-manager-home {
position: relative;
display: flex;
min-height: calc(100% - 1px);
max-width: 1420px;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
overflow: hidden;
flex-direction: column;
justify-content: center;
gap: clamp(3rem, 7vh, 6rem);
border-radius: var(--nodedc-radius-card);
background: var(--nodedc-canvas);
isolation: isolate;
margin: 0 auto;
padding: clamp(2.5rem, 6vw, 6rem) !important;
}
.device-manager-home__media,
.device-manager-home__scrim {
position: absolute;
z-index: -2;
inset: 0;
width: 100%;
height: 100%;
}
.device-manager-home__media {
z-index: 0;
display: block;
object-fit: cover;
}
.device-manager-home__scrim {
z-index: -1;
background: var(--nodedc-overlay-bg);
opacity: 0.82;
z-index: 1;
background:
linear-gradient(90deg, rgb(5 6 8 / 0.82) 0%, rgb(5 6 8 / 0.54) 46%, rgb(5 6 8 / 0.24) 100%),
linear-gradient(0deg, rgb(5 6 8 / 0.58), transparent 38%);
pointer-events: none;
}
.device-manager-home:not([data-has-media="true"]) .device-manager-home__scrim {
background:
radial-gradient(circle at 68% 42%, rgb(255 255 255 / 0.035), transparent 34%),
linear-gradient(90deg, rgb(5 6 8 / 0.2), transparent 62%);
}
.device-manager-hero {
max-width: 900px;
position: absolute;
z-index: 2;
top: 50%;
left: clamp(2rem, 5vw, 6rem);
width: min(39rem, 50%);
transform: translateY(-55%);
}
.device-manager-hero__icon {
@@ -316,27 +972,33 @@ body {
}
.device-manager-hero h1 {
margin: 0.7rem 0 0.9rem;
margin: 0.75rem 0 1rem;
color: var(--nodedc-text-primary);
font-size: clamp(4rem, 8vw, 8.5rem);
font-weight: 520;
letter-spacing: -0.065em;
line-height: 0.9;
font-size: clamp(3rem, 7vw, 7.6rem);
font-weight: 600;
letter-spacing: -0.072em;
line-height: 0.87;
}
.device-manager-hero p {
max-width: 680px;
max-width: 34rem;
margin: 0;
color: var(--nodedc-text-secondary);
font-size: clamp(0.96rem, 1.4vw, 1.14rem);
line-height: 1.55;
font-size: clamp(0.8rem, 1vw, 1rem);
line-height: 1.6;
}
.device-manager-hero__actions {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
margin-top: 1.5rem;
gap: 0.65rem;
margin-top: 1.6rem;
}
@media (max-width: 1480px) {
.device-manager-hero {
width: min(35rem, 54%);
}
}
.environment-settings {
@@ -510,6 +1172,8 @@ body {
min-height: 220px;
place-items: center;
color: var(--nodedc-text-secondary);
font-size: 0.82rem;
line-height: 1.55;
text-align: center;
}
@@ -558,16 +1222,6 @@ body {
white-space: nowrap;
}
.device-manager-overview-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.9rem;
}
.device-manager-overview-grid .nodedc-settings-card {
grid-column: 1 / -1;
}
.device-manager-capabilities {
display: flex;
flex-wrap: wrap;
@@ -590,8 +1244,8 @@ body {
.device-inventory__filters {
display: grid;
max-width: 620px;
grid-template-columns: repeat(2, minmax(0, 1fr));
max-width: 960px;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.75rem;
}
@@ -600,7 +1254,6 @@ body {
gap: 0.75rem;
margin-top: 0.45rem;
padding-top: 1rem;
border-top: 1px solid var(--nodedc-glass-border);
}
.device-inventory__section-heading {
@@ -722,7 +1375,6 @@ body {
align-items: center;
gap: 0.9rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--nodedc-glass-border);
}
.device-detail__identity {
@@ -885,7 +1537,6 @@ body {
display: flex;
justify-content: flex-end;
gap: 0.55rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem;
}
@@ -921,7 +1572,6 @@ body {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 0.35rem 0.7rem;
border-top: 1px solid var(--nodedc-glass-border);
padding-top: 0.85rem;
color: var(--nodedc-text-secondary);
font-size: 0.65rem;
@@ -948,20 +1598,36 @@ body {
gap: 1rem;
}
@media (max-height: 720px) and (min-width: 761px) {
.device-manager-hero h1 {
font-size: clamp(2.7rem, 6vw, 5rem);
}
.device-manager-hero p {
font-size: 0.76rem;
}
.device-manager-hero__actions {
margin-top: 1rem;
}
}
@media (max-width: 760px) {
body { overflow: auto; }
.device-manager-stage {
padding: 1rem;
overflow: hidden;
}
.device-manager-home {
min-height: auto;
padding: 2.5rem 1.25rem !important;
.device-manager-hero {
top: 42%;
right: 1.2rem;
left: 1.2rem;
width: auto;
}
.device-manager-hero h1 {
font-size: clamp(3.4rem, 17vw, 6rem);
font-size: clamp(2.8rem, 14vw, 5rem);
}
.device-manager-panel-toolbar,
@@ -970,14 +1636,6 @@ body {
flex-direction: column;
}
.device-manager-overview-grid {
grid-template-columns: 1fr;
}
.device-manager-overview-grid .nodedc-settings-card {
grid-column: auto;
}
.device-inventory-table__head {
display: none;
}
@@ -1015,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; }
+161
View File
@@ -194,6 +194,12 @@ export interface EdgeView {
displayName: string;
deploymentRef: string | null;
lifecycleState: string;
channel: {
lifecycleState: string;
generationRef: string | null;
runtimeState: "accepted" | "connecting" | "absent" | "unobserved" | "disabled" | "revoked" | string;
lastErrorCode: string | null;
};
createdAt: string | null;
updatedAt: string | null;
}
@@ -305,6 +311,160 @@ export interface ProjectGrantView {
lifecycleState: string;
}
export interface OntologyRefView {
entityId: string;
catalogHash: string;
}
export interface AssetView {
assetRef: string;
assetKey: string;
displayName: string;
assetTypeRef: string;
lifecycleState: string;
ontology: OntologyRefView;
}
export interface AssetBindingView {
assetBindingRef: string;
bindingKey: string;
deviceRef: string;
deviceName: string;
assetRef: string;
assetName: string;
bindingKind: string;
validFrom: string;
validTo: string | null;
provenanceRef: string;
ontology: OntologyRefView;
}
export interface HealthProjectionView {
state: string;
freshness: "fresh" | "stale" | "missing";
lastObservedState?: string;
evidenceClass?: string;
observedAt?: string | null;
expiresAt?: string | null;
observationRef: string | null;
}
export interface InfrastructureHostView {
hostRef: string;
hostKey: string;
displayName: string;
providerRef: string | null;
externalRef: string | null;
managementCredentialConfigured: boolean;
lifecycleState: string;
health: HealthProjectionView;
telemetry: InfrastructureHostTelemetryView;
ontology: OntologyRefView;
}
export interface InfrastructureHostTelemetrySnapshot {
schemaVersion: "nodedc.infrastructure.host-telemetry.v1";
profile: "linux-host-telegraf-v1";
hostKey: string;
observedAt: string;
source: { agent: string; agentVersion: string; collectorRef: string };
hardware: {
hostname: string | null;
architecture: string | null;
platform: string | null;
kernelRelease: string | null;
cpuModel: string | null;
logicalProcessors: number | null;
};
cpu: { usagePercent: number | null; load1: number | null; load5: number | null; load15: number | null };
memory: { totalBytes: number | null; availableBytes: number | null; freeBytes: number | null; usedBytes: number | null; usedPercent: number | null };
swap: { totalBytes: number | null; availableBytes: number | null; freeBytes: number | null; usedBytes: number | null; usedPercent: number | null };
system: {
uptimeSeconds: number | null;
users: number | null;
processes: { total: number | null; running: number | null; sleeping: number | null; blocked: number | null; zombies: number | null };
};
disks: Array<{ device: string | null; mount: string | null; filesystem: string | null; totalBytes: number | null; freeBytes: number | null; usedBytes: number | null; usedPercent: number | null }>;
network: Array<{ interface: string | null; bytesReceived: number | null; bytesSent: number | null; packetsReceived: number | null; packetsSent: number | null; errorsReceived: number | null; errorsSent: number | null; droppedReceived: number | null; droppedSent: number | null }>;
services: Array<{ name: string | null; loadState: string | null; activeState: string | null; subState: string | null; memoryBytes: number | null; restarts: number | null; pid: number | null }>;
}
export interface InfrastructureHostTelemetryView {
state: string;
freshness: "fresh" | "stale" | "missing";
observedAt: string | null;
receivedAt: string | null;
expiresAt: string | null;
current: InfrastructureHostTelemetrySnapshot | null;
history: Array<{
observedAt: string;
cpuUsagePercent: number | null;
memoryUsedPercent: number | null;
network: Array<{ interface: string | null; bytesReceived: number | null; bytesSent: number | null }>;
}>;
observation: null | {
observationRef: string;
entityId: string;
catalogHash: string;
targetRef: string;
serviceInstanceRef: string;
edgeRef: string;
profileRef: string;
source: { agent: string; agentVersion: string; collectorRef: string; provenanceRef: string };
observedProperties: string[];
};
}
export interface InfrastructureEndpointView {
endpointRef: string;
hostRef: string;
endpointKey: string;
purpose: "management" | "service" | "monitoring";
endpointUri: string;
lifecycleState: string;
ontology: OntologyRefView;
}
export interface InfrastructureDeploymentView {
deploymentRef: string;
hostRef: string;
deploymentKey: string;
displayName: string;
artifactRef: string;
artifactDigest: string;
lifecycleState: string;
ontology: OntologyRefView;
}
export interface InfrastructureServiceInstanceView {
serviceInstanceRef: string;
hostRef: string;
deploymentRef: string;
edgeRef: string | null;
serviceKey: string;
displayName: string;
serviceRole: string;
lifecycleState: string;
health: HealthProjectionView;
ontology: OntologyRefView;
}
export interface ProjectOntologyProjection {
ontology: { catalogHash: string; packages: string[] };
assets: AssetView[];
assetBindings: AssetBindingView[];
hosts: InfrastructureHostView[];
endpoints: InfrastructureEndpointView[];
deployments: InfrastructureDeploymentView[];
serviceInstances: InfrastructureServiceInstanceView[];
policies: {
restrictedIdentifiers: string;
managementCredentials: string;
missingHealthEvidence: string;
arbitraryConsole: string;
};
}
export interface ProjectWorkspace {
project: ProjectSummary;
devices: DeviceView[];
@@ -323,6 +483,7 @@ export interface ProjectWorkspace {
commands: CommandView[];
auditEvents: AuditEventView[];
grants: ProjectGrantView[];
ontology: ProjectOntologyProjection;
policies: {
commandTransport: "disabled" | "typed-service-ping-v1";
commandPlanningApi: "disabled" | "enabled";
+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;
@@ -0,0 +1,36 @@
{
"schemaVersion": "nodedc.device-plane.device-control-core-incident-audit.v1",
"mode": "double-rollback-failed-read-only-audit",
"allowedOperation": "canonical-plan-only",
"applyAllowed": false,
"failedAttempts": [
{
"patchId": "device-control-core-release-v3-20260822-040",
"artifactSha256": "08448a56cdf391076f92c5242e368fd0033b420167874645eebfa1f22184ee92",
"backupId": "device-plane-device-control-core-release-v3-20260822-040-20260822-184245"
},
{
"patchId": "device-control-core-release-v3-reconciliation-20260822-042",
"artifactSha256": "54ab243439bce724fa0a0872b76cc32e0052ea5127153214d92872f02ae831cf",
"backupId": "device-plane-device-control-core-release-v3-reconciliation-20260822-042-20260822-195448"
}
],
"readOnlyEvidence": [
"device-control-core-runtime-inventory",
"device-control-core-bounded-container-logs",
"device-postgres-schema-presence",
"device-postgres-wait-activity"
],
"runtimeMutation": "none",
"sourceMutation": "none",
"databaseMutation": "none",
"networkMutation": "none",
"secretRead": "none",
"preservedServices": [
"device-control-core",
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target"
]
}
@@ -0,0 +1,29 @@
{
"schemaVersion": "nodedc.device-plane.device-control-core-migration-replay-audit.v1",
"mode": "rejected-recovery-044-live-invariants-read-only-audit",
"allowedOperation": "canonical-plan-only",
"applyAllowed": false,
"rejectedRecovery": {
"patchId": "device-control-core-migration-replay-recovery-20260822-044",
"artifactSha256": "b893d8c90f98943797d32f486d6477d58a3be69eb1291e28c4a4bbd2e96774b7"
},
"readOnlyEvidence": [
"invalid-command-kind-count",
"triggering-receipt-count",
"constraint-validated",
"constraint-covers-final-command-kinds",
"host-telemetry-table-absent"
],
"runtimeMutation": "none",
"sourceMutation": "none",
"databaseMutation": "none",
"networkMutation": "none",
"secretRead": "none",
"preservedServices": [
"device-control-core",
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target"
]
}
@@ -0,0 +1,36 @@
{
"schemaVersion": "nodedc.device-plane.device-control-core-migration-replay-checkpoint-recovery.v2",
"mode": "terminal-044-replay-checkpoint-forward-repair",
"failedIncidentAudit": "device-control-core-incident-audit-20260822-043",
"failedRecovery": {
"patchId": "device-control-core-migration-replay-recovery-20260822-044",
"artifactSha256": "b893d8c90f98943797d32f486d6477d58a3be69eb1291e28c4a4bbd2e96774b7",
"failure": "preflight-replay-checkpoint-race",
"startedApply": false
},
"sourcePredecessor": {
"path": "services/device-control-core/migrations/014_device_registry_profile_commands.sql",
"sha256": "751accf346b34d2774cc7b9572640d2c25fdb0b1db793ac32183b56f48e26508"
},
"sourceTarget": {
"path": "services/device-control-core/migrations/014_device_registry_profile_commands.sql",
"sha256": "38bd86b42828d44c7101d5433ddc36018e92eedeee37b9de296432ad676edd46"
},
"rootCause": "restarting-core-cycles-exact-committed-migration-checkpoints",
"repair": "migration-014-add-constraint-not-valid",
"databasePreflight": "exact-replay-checkpoint-005-007-009-011-and-final-compatible-rows",
"databaseRowMutation": "none",
"databaseSchemaOutcome": "exact-final-migration-016-validated-command-kind-check",
"runtimeAction": "build+recreate-device-control-core-only",
"runtimePredecessor": "proven-degraded-restarting-exact-preapply-image",
"preservedServices": [
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target"
],
"databaseVolume": "nodedc-device-plane-postgres-data",
"publicIngress": "disabled",
"edgeChannel": "core-initiated-pinned-mtls-registered-edges-only",
"rollback": "source+exact-degraded-predecessor-image-runtime"
}
@@ -0,0 +1,30 @@
{
"schemaVersion": "nodedc.device-plane.device-control-core-migration-replay-recovery.v1",
"mode": "double-rollback-failed-migration-014-forward-repair",
"failedIncidentAudit": "device-control-core-incident-audit-20260822-043",
"sourcePredecessor": {
"path": "services/device-control-core/migrations/014_device_registry_profile_commands.sql",
"sha256": "751accf346b34d2774cc7b9572640d2c25fdb0b1db793ac32183b56f48e26508"
},
"sourceTarget": {
"path": "services/device-control-core/migrations/014_device_registry_profile_commands.sql",
"sha256": "38bd86b42828d44c7101d5433ddc36018e92eedeee37b9de296432ad676edd46"
},
"rootCause": "intermediate-command-kind-check-revalidated-historical-receipts",
"repair": "migration-014-add-constraint-not-valid",
"databasePreflight": "all-live-command-kinds-covered-by-final-migration-016",
"databaseRowMutation": "none",
"databaseSchemaOutcome": "final-migration-016-validated-command-kind-check",
"runtimeAction": "build+recreate-device-control-core-only",
"runtimePredecessor": "proven-degraded-double-rollback-state",
"preservedServices": [
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target"
],
"databaseVolume": "nodedc-device-plane-postgres-data",
"publicIngress": "disabled",
"edgeChannel": "core-initiated-pinned-mtls-registered-edges-only",
"rollback": "source+exact-degraded-predecessor-image-runtime"
}
@@ -0,0 +1,25 @@
{
"schemaVersion": "nodedc.device-plane.device-control-core-release-v3-reconciliation.v1",
"mode": "failed-release-v3-exact-preapply-image-restore",
"failedPatchId": "device-control-core-release-v3-20260822-040",
"failedArtifactSha256": "08448a56cdf391076f92c5242e368fd0033b420167874645eebfa1f22184ee92",
"failedArtifact": "nodedc-device-plane-device-control-core-release-v3-20260822-040.tgz.20260822-184245",
"backupId": "device-plane-device-control-core-release-v3-20260822-040-20260822-184245",
"predecessorPatchId": "device-control-core-release-v2-20260822-038",
"predecessorArtifactSha256": "e2d062b82b022dba662522b5d6e192026ac964d78950d903295ca3cbbc95ab28",
"preapplyImageId": "sha256:31d35733ee46225b487c0f02a7b52d4ba2d13f5b99f6a717b7f5e6f5460b412a",
"sourceAction": "accept-byte-exact-restored-preapply-source",
"runtimeAction": "retag-exact-preapply-image+recreate-device-control-core-only",
"preservedServices": [
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target"
],
"databaseVolume": "nodedc-device-plane-postgres-data",
"publicIngress": "disabled",
"edgeChannel": "core-initiated-pinned-mtls-registered-edges-only",
"commandTransport": "typed-service-ping-v1",
"gelios": "untouched-legacy-only",
"rollback": "marker+exact-preapply-image-runtime"
}
@@ -0,0 +1,40 @@
{
"schemaVersion": "nodedc.device-plane.device-control-core-release.v3",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-control-core-release-v2-20260822-038",
"artifactSha256": "e2d062b82b022dba662522b5d6e192026ac964d78950d903295ca3cbbc95ab28"
},
"service": "device-control-core",
"composeActivation": "preserve-active-v4-topology",
"identity": "reuse-existing-runner-managed-host-local-private-key-public-certificate-export",
"identityRecovery": "forbidden-valid-existing-identity-required",
"tlsPurpose": "clientAuth",
"direction": "core-initiated",
"endpointPolicy": "public-ipv4-standard-https-tcp-443-only",
"coreNetworks": [
"device-plane-private",
"device-plane-egress"
],
"publicIngress": "none-on-synology",
"edgeRegistrations": "preserved",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"telemetryTransport": "edge-channel-host-telemetry-observed-v1",
"telemetryContract": "nodedc.infrastructure.host-telemetry.v1",
"telemetryStorage": "device-control-core-postgres-seven-day-retention",
"ontologyProjection": "observation-observed-property-provenance-freshness-v1",
"telemetryFreshness": "fifteen-seconds-missing-stale-not-unhealthy",
"gelios": "untouched-legacy-only",
"preservedServices": [
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target"
],
"healthGate": "bounded-container-grace+core-edge-contract+exact-private-egress-network-boundary",
"rollback": "restore-preapply-source-and-core-runtime"
}
@@ -0,0 +1,45 @@
{
"schemaVersion": "nodedc.device-plane.device-control-core-release.v4",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "migration-replay-checkpoint-recovery",
"patchId": "device-control-core-migration-replay-checkpoint-recovery-20260822-046",
"artifactSha256": "46000c76977fb583fc7c9cf74ecf624efd8b404f7b8d0322e0270e7b8ac6e450"
},
"service": "device-control-core",
"composeActivation": "preserve-active-v4-topology",
"identity": "reuse-existing-runner-managed-host-local-private-key-public-certificate-export",
"identityRecovery": "forbidden-valid-existing-identity-required",
"tlsPurpose": "clientAuth",
"direction": "core-initiated",
"endpointPolicy": "public-ipv4-standard-https-tcp-443-only",
"coreNetworks": [
"device-plane-private",
"device-plane-egress"
],
"publicIngress": "none-on-synology",
"edgeRegistrations": "preserved",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"telemetryTransport": "edge-channel-host-telemetry-observed-v1",
"telemetryContract": "nodedc.infrastructure.host-telemetry.v1",
"telemetryStorage": "device-control-core-postgres-seven-day-retention",
"ontologyProjection": "observation-observed-property-provenance-freshness-v1",
"telemetryFreshness": "fifteen-seconds-missing-stale-not-unhealthy",
"recoveryPredecessor": "terminal-applied-046-exact-source-runtime-database",
"databasePreflight": "final-migration-016-validated-and-host-telemetry-table-absent",
"databaseRowMutation": "none-before-core-startup-migrations",
"databaseSchemaOutcome": "migration-017-host-telemetry-table-present",
"runtimePredecessor": "healthy-recovery-046-core-generation",
"gelios": "untouched-legacy-only",
"preservedServices": [
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target"
],
"healthGate": "bounded-container-grace+core-edge-contract+exact-private-egress-network-boundary",
"rollback": "restore-preapply-source-and-core-runtime"
}
@@ -0,0 +1,77 @@
{
"schemaVersion": "nodedc.device-edge-vps.host-telemetry.v1",
"mode": "provider-neutral-host-observation-over-accepted-core-channel",
"status": "active-host-telemetry",
"authority": "DCPLATFORM-21/DCPLATFORM-76/DCPLATFORM-77/ADR-0001",
"component": "device-edge-vps",
"phase": "host-telemetry",
"runtimeHost": "koffyvngij",
"predecessorPatch": "device-edge-vps-command-transport-20260812-013",
"predecessorArtifactSha256": "c7486ec879681ddd706f229b628c8556ca8c9ccc4f152a85debb409c302759ef",
"agent": "telegraf",
"agentVersion": "1.38.4",
"agentRuntimeUser": "nodedc-telemetry",
"agentService": "nodedc-host-telemetry-agent.service",
"collector": "127.0.0.1:18223/internal/v1/host-telemetry",
"collectorExposure": "loopback-only",
"transport": "existing-core-initiated-pinned-mtls-channel",
"messageKind": "host.telemetry.observed",
"observationEntity": "observation.observation",
"observationTarget": "infrastructure.host",
"observedProperties": [
"host.cpu.utilization",
"host.memory.utilization",
"host.swap.utilization",
"host.disk.utilization",
"host.network.counters",
"host.process.counts",
"host.systemd.unit-state"
],
"commandTransport": "typed-service-ping-v1",
"publicIngress": "preserved:tcp/443-mtls-core-channel+tcp/9921-bidirectional-tracker-session",
"mqtt": "disabled-no-public-broker-no-wan-plaintext",
"database": "none-on-vps",
"credentials": "none-added",
"gelios": "untouched-legacy-only",
"resourceCeilings": {
"agentMemory": "96M",
"agentSwap": "0",
"agentCpu": "15%",
"agentTasks": 64,
"agentOpenFiles": 512,
"collectorBodyBytes": 524288,
"channelEnvelopeBytes": 1048576
},
"preserved": [
"management-ssh-key",
"accepted-node-runtime",
"accepted-core-channel-trust-and-registration",
"accepted-tracker-ingress",
"accepted-typed-command-transport",
"retired-tailnet-boundary",
"gelios-production-path"
],
"forbidden": [
"public-mqtt",
"plaintext-wan-telemetry",
"vps-initiated-synology-connection",
"public-health",
"vps-database",
"browser-secrets",
"generic-shell",
"ontology-core-telemetry-storage"
],
"acceptance": [
"exact-command-transport-013-predecessor",
"telegraf-1.38.4-exact-archive-and-binary",
"dedicated-non-root-agent",
"loopback-only-http-output",
"core-channel-remains-accepted",
"host-observation-reaches-device-control-core",
"public-port-set-unchanged",
"typed-command-transport-preserved",
"tailscale-remains-absent",
"gelios-untouched"
],
"rollback": "restore-exact-command-transport-013-source-runtime-and-remove-agent-runtime"
}
@@ -0,0 +1,56 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v10",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v8-20260822-039",
"artifactSha256": "30a83d4c6b5c029c96c4af19fa558e0ae75e4b60bc897881457304bd17e0e465"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v4-20260823-047",
"artifactSha256": "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"faviconSet": "nodedc-adaptive-v1",
"commandFormLayout": "aligned-control-row-v1",
"secondaryEmptyTypography": "help-text-sm-v1",
"infrastructureHostProjection": "ontology-backed-host-runtime-v1",
"ontologyFoundation": "ontology-core-device-foundation-20260822-001",
"ontologyCatalogHash": "229c61c02a790906",
"assetBinding": "temporal-device-asset-binding-v1",
"infrastructureRuntime": "host-endpoint-deployment-service-instance-v1",
"healthEvidence": "ttl-observation-missing-not-unhealthy-v1",
"telemetryWorkspace": "mission-core-compute-module-parity-v1",
"telemetryNavigation": "full-workspace-back-navigation-v1",
"telemetryPollInterval": "three-seconds",
"telemetryFreshness": "fifteen-seconds-missing-stale-not-unhealthy",
"telemetryOntologyProjection": "observation-observed-property-provenance-freshness-v1",
"telemetryAgent": "telegraf-host-observer-v1",
"interactiveShell": "disabled-pending-managed-session-boundary",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
@@ -0,0 +1,63 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v11",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v10-20260823-048",
"artifactSha256": "e6b983a314db4f8c27d89062dfedf5ed0523cc30421170799d181a19e2d85d4c"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v4-20260823-047",
"artifactSha256": "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"faviconSet": "nodedc-adaptive-v1",
"commandFormLayout": "aligned-control-row-v1",
"secondaryEmptyTypography": "help-text-sm-v1",
"infrastructureHostProjection": "ontology-backed-host-runtime-v1",
"ontologyFoundation": "ontology-core-device-foundation-20260822-001",
"ontologyCatalogHash": "229c61c02a790906",
"assetBinding": "temporal-device-asset-binding-v1",
"infrastructureRuntime": "host-endpoint-deployment-service-instance-v1",
"healthEvidence": "ttl-observation-missing-not-unhealthy-v1",
"designSystem": "nodedc-canonical-components-and-tokens-v1",
"missionCoreReference": "compute-modules-workspace-71c8b04",
"infrastructureWorkspaceLayout": "mission-core-system-workspace-v1",
"hostInventoryComposition": "mission-core-compute-host-list-v1",
"telemetryWorkspace": "mission-core-compute-module-visual-parity-v2",
"telemetrySurface": "borderless-soft-surface-v1",
"telemetryStatus": "mission-core-dot-status-v1",
"telemetryNavigation": "full-workspace-back-navigation-v1",
"telemetryScroll": "reset-on-workspace-transition-v1",
"telemetryPollInterval": "three-seconds",
"telemetryFreshness": "fifteen-seconds-missing-stale-not-unhealthy",
"telemetryOntologyProjection": "observation-observed-property-provenance-freshness-v1",
"telemetryAgent": "telegraf-host-observer-v1",
"interactiveShell": "disabled-pending-managed-session-boundary",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
@@ -0,0 +1,67 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v12",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v11-20260823-049",
"artifactSha256": "c1e2056b50bfbb0d03d077461d0c27cc56cc52967c3f5620be14871c8a6d5cf0"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v4-20260823-047",
"artifactSha256": "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"faviconSet": "nodedc-adaptive-v1",
"commandFormLayout": "aligned-control-row-v1",
"secondaryEmptyTypography": "help-text-sm-v1",
"infrastructureHostProjection": "ontology-backed-host-runtime-v1",
"ontologyFoundation": "ontology-core-device-foundation-20260822-001",
"ontologyCatalogHash": "229c61c02a790906",
"assetBinding": "temporal-device-asset-binding-v1",
"infrastructureRuntime": "host-endpoint-deployment-service-instance-v1",
"healthEvidence": "ttl-observation-missing-not-unhealthy-v1",
"designSystem": "nodedc-canonical-components-and-tokens-v1",
"missionCoreReference": "compute-modules-workspace-71c8b04",
"infrastructureWorkspaceLayout": "mission-core-system-workspace-v1",
"hostInventoryComposition": "mission-core-compute-host-list-v1",
"telemetryWorkspace": "mission-core-compute-module-adaptive-window-v3",
"telemetrySurface": "borderless-soft-surface-v1",
"telemetryStatus": "mission-core-dot-status-v1",
"telemetryNavigation": "full-workspace-back-navigation-v1",
"telemetryScroll": "reset-on-workspace-transition-v1",
"telemetryPollInterval": "three-seconds",
"telemetryFreshness": "fifteen-seconds-missing-stale-not-unhealthy",
"telemetryOntologyProjection": "observation-observed-property-provenance-freshness-v1",
"telemetryAgent": "telegraf-host-observer-v1",
"telemetryGraphScale": "adaptive-observed-window-explicit-domain-v1",
"telemetryCpuMinimumSpan": "five-percentage-points",
"telemetryMemoryMinimumSpan": "four-percentage-points",
"telemetryNetworkMissingSemantics": "missing-counters-never-zero-v1",
"interactiveShell": "disabled-pending-managed-session-boundary",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
@@ -0,0 +1,74 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v13",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v12-20260823-050",
"artifactSha256": "1a49839140e5f2e49763d78f24ee47d946e244bcfde15a9c38266e8bd14c0d49"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v4-20260823-047",
"artifactSha256": "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"faviconSet": "nodedc-adaptive-v1",
"commandFormLayout": "aligned-control-row-v1",
"secondaryEmptyTypography": "help-text-sm-v1",
"infrastructureHostProjection": "ontology-backed-host-runtime-v1",
"ontologyFoundation": "ontology-core-device-foundation-20260822-001",
"ontologyCatalogHash": "229c61c02a790906",
"assetBinding": "temporal-device-asset-binding-v1",
"infrastructureRuntime": "host-endpoint-deployment-service-instance-v1",
"healthEvidence": "ttl-observation-missing-not-unhealthy-v1",
"designSystem": "nodedc-canonical-components-and-tokens-v1",
"missionCoreReference": "compute-modules-workspace-71c8b04",
"infrastructureWorkspaceLayout": "mission-core-system-workspace-v2",
"hostInventoryComposition": "mission-core-compute-host-accordion-v2",
"hostInventoryOverviewSurface": "separate-summary-soft-surface-v1",
"hostInventoryCollectionSurface": "separate-host-collection-soft-surface-v1",
"hostInventoryRow": "compact-centered-accordion-v1",
"hostInventoryFreshness": "dot-only-v1",
"hostInventoryRelations": "host-scoped-endpoint-deployment-service-v1",
"hostInventoryDefaultExpansion": "collapsed",
"hostInventoryScaleTarget": "five-hundred-collapsed-rows-v1",
"telemetryWorkspace": "mission-core-compute-module-adaptive-window-v3",
"telemetrySurface": "borderless-soft-surface-v1",
"telemetryStatus": "mission-core-dot-status-v1",
"telemetryNavigation": "full-workspace-back-navigation-v1",
"telemetryScroll": "reset-on-workspace-transition-v1",
"telemetryPollInterval": "three-seconds",
"telemetryFreshness": "fifteen-seconds-missing-stale-not-unhealthy",
"telemetryOntologyProjection": "observation-observed-property-provenance-freshness-v1",
"telemetryAgent": "telegraf-host-observer-v1",
"telemetryGraphScale": "adaptive-observed-window-explicit-domain-v1",
"telemetryCpuMinimumSpan": "five-percentage-points",
"telemetryMemoryMinimumSpan": "four-percentage-points",
"telemetryNetworkMissingSemantics": "missing-counters-never-zero-v1",
"interactiveShell": "disabled-pending-managed-session-boundary",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
+2 -2
View File
@@ -8,8 +8,8 @@
"artifactSha256": "d4132993216eb674967dc6fc65d9670cfc2a9efdf46186ca019030f259de2d0e"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v2-20260813-028",
"artifactSha256": "816ef07fd81923328c3ff54d833dcc49f873aef13256259ae4f66061e7453635"
"patchId": "device-control-core-release-v2-20260821-030",
"artifactSha256": "8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
+39
View File
@@ -0,0 +1,39 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v4",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v3-20260822-032",
"artifactSha256": "6e0eb3a0a6f19ceab92d46832b93bffbcea21247dbdc2ea50625a51ff460e4ca"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v2-20260821-030",
"artifactSha256": "8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
+40
View File
@@ -0,0 +1,40 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v5",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v4-20260822-033",
"artifactSha256": "52ba322042f1e4f595bbfea99f8bb35630b15984e0da648dc55348bc9e5b2066"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v2-20260821-030",
"artifactSha256": "8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
+41
View File
@@ -0,0 +1,41 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v6",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v5-20260822-034",
"artifactSha256": "acc1d2ae2cda66861054826928c25d01a2428e688cc8132a9c381831bf29ab5a"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v2-20260821-030",
"artifactSha256": "8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"faviconSet": "nodedc-adaptive-v1",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
+45
View File
@@ -0,0 +1,45 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v7",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v6-20260822-035",
"artifactSha256": "193faabe930e2b3f212f8eb45288e39f850ec714528b28881095be654baf9a80"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v2-20260822-036",
"artifactSha256": "8708cc4b59fa0cd5e9c6e6a7b2654ba01ea60271549167aca2631f94000d3da3"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"faviconSet": "nodedc-adaptive-v1",
"commandFormLayout": "aligned-control-row-v1",
"secondaryEmptyTypography": "help-text-sm-v1",
"infrastructureHostProjection": "edge-registration-live-channel-v1",
"ontologyStatus": "generic-host-domain-candidate-not-canonical",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
+50
View File
@@ -0,0 +1,50 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v8",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v6-20260822-035",
"artifactSha256": "193faabe930e2b3f212f8eb45288e39f850ec714528b28881095be654baf9a80"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v2-20260822-038",
"artifactSha256": "e2d062b82b022dba662522b5d6e192026ac964d78950d903295ca3cbbc95ab28"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"faviconSet": "nodedc-adaptive-v1",
"commandFormLayout": "aligned-control-row-v1",
"secondaryEmptyTypography": "help-text-sm-v1",
"infrastructureHostProjection": "ontology-backed-host-runtime-v1",
"ontologyFoundation": "ontology-core-device-foundation-20260822-001",
"ontologyCatalogHash": "229c61c02a790906",
"assetBinding": "temporal-device-asset-binding-v1",
"infrastructureRuntime": "host-endpoint-deployment-service-instance-v1",
"healthEvidence": "ttl-observation-missing-not-unhealthy-v1",
"interactiveShell": "disabled-pending-managed-session-boundary",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
+56
View File
@@ -0,0 +1,56 @@
{
"schemaVersion": "nodedc.device-plane.device-manager-release.v9",
"releaseId": "__PATCH_ID__",
"action": "upgrade",
"predecessor": {
"kind": "release",
"patchId": "device-manager-release-v8-20260822-039",
"artifactSha256": "30a83d4c6b5c029c96c4af19fa558e0ae75e4b60bc897881457304bd17e0e465"
},
"controlCorePredecessor": {
"patchId": "device-control-core-release-v3-20260822-040",
"artifactSha256": "08448a56cdf391076f92c5242e368fd0033b420167874645eebfa1f22184ee92"
},
"edgeChannelPredecessor": {
"patchId": "device-edge-core-channel-upgrade-v4-20260812-023",
"artifactSha256": "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
},
"service": "device-manager",
"publicIngress": "reverse-proxy-only",
"deviceCoreManagementApi": "file-token-authenticated",
"launcherTrust": "file-token-scoped-to-device-core-handoff",
"edgeChannel": "preserve-active-v4-core-initiated-pinned-mtls",
"edgeChannelIdentity": "reuse-runner-managed-host-local-private-key-public-certificate-export",
"edgeChannelEgress": "preserve-dedicated-core-only-bridge-no-host-ingress-public-ipv4-tcp-443-only",
"healthGate": "bounded-container-grace+core-contract+persistent-data",
"commandTransport": "typed-service-ping-v1",
"commandCatalog": "allowlisted-adapter-typed-commands-only",
"credentialBoundary": "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned",
"presentationPersistence": "runner-managed-host-data-bind",
"presentationDataHostPath": "/volume1/docker/nodedc-device-plane/data/device-manager",
"presentationDataContainerPath": "/var/lib/nodedc-device-manager",
"presentationDataOwnership": "uid-1000-gid-1000-mode-0750",
"presentationDataLifecycle": "preserve-across-manager-recreate-and-source-rollback",
"presentationPath": "/var/lib/nodedc-device-manager/device-manager-presentation.json",
"mediaRoot": "/var/lib/nodedc-device-manager/media",
"defaultAccentHex": "#f5f5f5",
"overviewLayout": "mission-core-landing-stage-v1",
"faviconSet": "nodedc-adaptive-v1",
"commandFormLayout": "aligned-control-row-v1",
"secondaryEmptyTypography": "help-text-sm-v1",
"infrastructureHostProjection": "ontology-backed-host-runtime-v1",
"ontologyFoundation": "ontology-core-device-foundation-20260822-001",
"ontologyCatalogHash": "229c61c02a790906",
"assetBinding": "temporal-device-asset-binding-v1",
"infrastructureRuntime": "host-endpoint-deployment-service-instance-v1",
"healthEvidence": "ttl-observation-missing-not-unhealthy-v1",
"telemetryWorkspace": "mission-core-compute-module-parity-v1",
"telemetryNavigation": "full-workspace-back-navigation-v1",
"telemetryPollInterval": "three-seconds",
"telemetryFreshness": "fifteen-seconds-missing-stale-not-unhealthy",
"telemetryOntologyProjection": "observation-observed-property-provenance-freshness-v1",
"telemetryAgent": "telegraf-host-observer-v1",
"interactiveShell": "disabled-pending-managed-session-boundary",
"gelios": "untouched-legacy-only",
"rollback": "restore-preapply-snapshot-preserve-manager-data"
}
+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
+8
View File
@@ -34,6 +34,8 @@ services:
NODEDC_LAUNCHER_INTERNAL_TOKEN_FILE: /run/nodedc-secrets/device-core-internal-token
NODEDC_DEVICE_CORE_INTERNAL_URL: http://device-control-core:18120
NODEDC_DEVICE_CORE_TOKEN_FILE: /run/nodedc-secrets/management-core-token
NODEDC_DEVICE_MANAGER_PRESENTATION_PATH: /var/lib/nodedc-device-manager/device-manager-presentation.json
NODEDC_DEVICE_MANAGER_MEDIA_ROOT: /var/lib/nodedc-device-manager/media
volumes:
- type: bind
source: /volume1/docker/nodedc-platform/secrets/device-core-internal-token
@@ -47,6 +49,12 @@ services:
read_only: true
bind:
create_host_path: false
- type: bind
source: /volume1/docker/nodedc-device-plane/data/device-manager
target: /var/lib/nodedc-device-manager
read_only: false
bind:
create_host_path: false
expose:
- "18122"
networks:
+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.
Работающее подключение не требует повторного импорта. Это отдельно от ключей
приложений внутри контуров; обновление доступа не устанавливает ПО на сервер.
+242
View File
@@ -0,0 +1,242 @@
# Device Core: deploy from main
Decision, 2026-09-29: a push to `SILVER/NODEDC_DEVICE_CORE:main` must trigger
qualification and automatic deployment after the gates pass. No separate
`DEPLOY` branch or approval for each release. This decision is specific to
Device Core; other repositories keep their existing policy until onboarded.
## Current implementation status
As of 2026-09-30, the first automatic application release using the accepted
network-priority override is r13/source
`33cd08c7ab4b1ee87e8c943fca4a30f38c782aae`, accepted at09:25:33Z in canonical
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.
The installed root runner015 has SHA
`7a213b7d086225ac9677f52e1bde99dd4b57d77da7c548aadb11793336911cf2`,
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
The first runner lives on Synology. No additional listening ports, DSM reverse
proxy route, firewall opening or webhook receiver are required. It polls the
existing Gitea HTTPS endpoint. Disable the runner cache server and metrics
listener initially. Start with one job at a time and an explicit CPU/RAM limit,
chosen after reading the live host baseline.
Use container jobs, no host-execution labels, no privileged jobs, no arbitrary
host volumes and no Docker socket inside jobs. The runner daemon's own Docker
access is privileged infrastructure and belongs to Platform. Repository jobs
must not receive production paths, databases, runtime secrets or deploy keys.
Build qualification and production installation are separate responsibilities.
A Platform-owned controller polls completed Gitea runs and drives the canonical
root-owned `nodedc-deploy` on the same NAS. It does not expose an HTTP server.
The application workflow cannot supply shell commands, target paths or service
names to this controller. Adding another repo requires an explicit registry
entry, branch policy, release contract and acceptance tests.
## Reproduce source qualification
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 fetches the
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;
following their current `main` branches would make old releases unreproducible.
Launcher sources are required by the existing Hub trust/session artifact tests;
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
are rejected, never reset or deleted by the qualification script.
From a fresh exact Device Core checkout in a disposable parent directory:
```sh
python3 infra/ci/qualify.py fetch-dependencies --commit <full-device-core-sha>
python3 infra/ci/qualify.py check --commit <full-device-core-sha> --report ../qualification.json
```
The checks reject dirty or wrong checkouts and mismatched toolchain versions.
They install lockfile dependencies, build the two required Design Guideline
packages, run Device Core unit and CI tests, compile the UI and run the existing
artifact contract suite against the pinned Platform runner source. The report
is created only after all checks pass and records all source SHAs, lockfile
hashes and the UI output hash. It contains `deployed: false` deliberately.
The qualification report is evidence, not an authorization token or substitute
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'`.
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.
## Installed production contract
1. The root installer verifies its installed identity, applied journals, current
manager/core release descriptors and preserved runtime state on Synology.
2. The versioned **normal update** transition handles repeat releases.
Historical recovery descriptors and fixed predecessor guards remain intact.
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
durable queue. Serialize production transitions. Handle duplicate events
idempotently; never install an older revision after a newer one. A missed
poll must not lose a push. Do not depend on Gitea job completion order.
4. Link exact source commits to immutable data-only deploy artifacts. Retain
existing `manifest.env`, `files.txt`, `payload/...` validation and fixed
component/service selection. Exclude secrets, DB state and executable hooks.
5. Obtain a fresh canonical plan, reserve the verified artifact in the durable
queue, then apply with predecessor and payload checks under the deploy lock. Record
commit, run, artifact, plan, receipt and backup. The controller's allowlist
is root-owned and cannot be expanded by a workflow artifact.
6. Source tests cover wrong SHA/repo/branch, failed/pending checks, duplicate
events, pagination changes, overlapping runs, restart reconciliation and
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
follow the canonical runner's rollback policy; an ambiguous or failed rollback
stops subsequent applies for diagnosis. Never call an unconfirmed release
deployed. User/device data and tokens survive application updates.
## Operator view
Normal use: push to `main`, then watch Gitea **Actions** for qualification.
`/volume1/docker/nodedc-device-autodeploy/runtime-status.json` is a sanitized
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
in-progress apply. Recovery/rollback remains a recorded canonical transition.
Track shared infrastructure in Ops **DCPLATFORM-37**, root deploy contracts in
**DCPLATFORM-21**, and B2 server/contour integration in **MISSIONCOR-86**.
This deployment mechanism does not mix Device Core and Mission Core inventories.
References: [Gitea Actions](https://docs.gitea.com/usage/actions/overview/),
[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.
@@ -0,0 +1,132 @@
# Device Core asset and infrastructure ontology contract
Status: **canonical foundation implemented**
Date: 2026-08-22
Production ontology catalog hash: `229c61c02a790906`
## Authority
Device Core consumes the official read-only NODE.DC Ontology Core catalog. It
does not mint local ontology identifiers. The production catalog now publishes
the `asset`, `device`, `infrastructure` and `observation` packages required by
this runtime foundation.
Canonical entities used by Device Core:
| Entity | Runtime meaning |
| --- | --- |
| `asset.asset` | Stable business or physical object whose identity survives tracker replacement |
| `device.tracking_device` | A tracker registered through Device Core enrollment and claim |
| `device.asset_binding` | Temporal, evidenced Device-to-Asset association |
| `infrastructure.host` | Provider-neutral physical or virtual compute host |
| `infrastructure.endpoint` | Credential-free management, monitoring or service endpoint |
| `infrastructure.deployment` | Desired immutable artifact deployment on a host |
| `infrastructure.service_instance` | Runtime service realizing a deployment on a host |
| `observation.health_observation` | Time-bounded health evidence with source and freshness |
| `observation.position_observation` | Canonical position evidence for Foundry/map projections |
`infrastructure.host` is deliberately distinct from
`integration.connection`, `infrastructure.endpoint`,
`infrastructure.deployment` and Device Edge registration.
## Direct B2 onboarding
Direct B2 registration reuses the existing secure Device Core lifecycle:
```text
adapter + model profile + route
|
v
enrollment intent (IMEI -> HMAC digest + masked projection)
|
v
quarantine discovery -> claim -> device.tracking_device
|
v
asset.asset <- temporal device.asset_binding
```
No raw IMEI, provider credential or device secret is stored in the ontology or
returned to the browser. The current Gelios flow remains a legacy integration;
new B2 trackers can be enrolled directly and attached to the same stable Asset
model without making Gelios the identity authority.
Closing a binding records `valid_to` and actor evidence. Tracker replacement
therefore changes the active binding, not the Asset identity or its history.
## VPS and Edge topology
```text
device.project -> infrastructure.host -> infrastructure.endpoint
|
v
infrastructure.deployment
|
v
infrastructure.service_instance
|
+---- optional link ----> device.edge-registration
```
Provider names and provider resource IDs are annotations. They never define
the host identity. A management credential is an opaque `secret-ref:*`; the
secret value is not accepted by the API, stored in these tables or projected
to the Manager.
An Edge link is allowed only when the Edge is already used by a route in the
same Device project. This prevents a generic host screen from silently taking
ownership of a platform-wide Edge registration.
## Health and monitoring
Health is append-only evidence, not a mutable `online` property. Each
observation has:
- subject: Host or Service Instance;
- state: `reachable`, `degraded` or `unreachable`;
- evidence class and schema reference;
- source reference;
- `observed_at` and mandatory `expires_at`;
- bounded, secret-free evidence projection.
The read projection returns `unobserved` when evidence is missing or stale.
Missing evidence is never converted into `unreachable`.
## API surface
Idempotent management commands:
- `assets:ensure`;
- `asset-bindings:ensure` and `asset-bindings:close`;
- `infrastructure-hosts:ensure`;
- `infrastructure-endpoints:ensure`;
- `infrastructure-deployments:ensure`;
- `infrastructure-service-instances:ensure`;
- `health-observations:record`.
The safe read projection is:
```text
GET /internal/v1/query/projects/{project-id}/ontology
```
It returns the catalog hash, assets and temporal bindings, provider-neutral
infrastructure inventory, and freshness-aware health projections. It never
returns credential references themselves.
## Console boundary
An unrestricted WebSSH terminal remains disabled. A future console requires a
separate `infrastructure.management_session` broker with short-lived sessions,
server-side credentials, command authorization, immutable audit, output limits,
redaction and explicit break-glass controls. A direct browser-to-SSH connection
is outside the Device Core security boundary.
## Next projection
Foundry consumes canonical Asset, Device, temporal binding and Observation
relations. Spatial layers are produced only from current
`observation.position_observation` evidence; Hosts without spatial evidence do
not appear on a map merely because they exist in inventory.
+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.
@@ -0,0 +1,6 @@
# Документ перенесён в репозиторий сервера B2
Актуальная версия: [SHARED_B2_ACCESS_LIFECYCLE_20260929.md](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS/src/branch/main/docs/SHARED_B2_ACCESS_LIFECYCLE_20260929.md).
Серверная архитектура и подключение независимых клиентов развиваются там.
Интеграция Device Core остаётся ответственностью этого репозитория.
@@ -0,0 +1,6 @@
# Документ перенесён в репозиторий сервера B2
Актуальная версия: [SHARED_B2_SERVICE_PROPOSAL_20260929.md](https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS/src/branch/main/docs/SHARED_B2_SERVICE_PROPOSAL_20260929.md).
Серверная архитектура и подключение независимых клиентов развиваются там.
Интеграция Device Core остаётся ответственностью этого репозитория.
+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()
+218
View File
@@ -0,0 +1,218 @@
#!/usr/bin/env python3
"""Qualify exact sources in disposable CI checkouts. No production access."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import time
SHA = re.compile(r"[0-9a-f]{40}")
DEPENDENCIES = {
"NODEDC_DESIGN_GUIDELINE": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"NODEDC_LAUNCHER": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
"platform": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
}
def run(args, cwd, capture=False, capture_errors=False):
return subprocess.run(
args, cwd=cwd, check=True, text=True,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.STDOUT if capture_errors else None,
env={**os.environ, "GIT_TERMINAL_PROMPT": "0", "CI": "true",
"NODEDC_LAUNCHER_REPO": str(Path(__file__).resolve().parents[3] / "NODEDC_LAUNCHER")},
).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):
lock = json.loads((root / "infra/ci/sources.lock.json").read_text())
if lock.get("schema") != "nodedc.device-core.ci-sources.v1":
raise ValueError("unsupported_source_lock")
if set(lock.get("dependencies", {})) != set(DEPENDENCIES):
raise ValueError("unexpected_source_dependencies")
for name, url in DEPENDENCIES.items():
item = lock["dependencies"][name]
if item.get("url") != url or not SHA.fullmatch(item.get("commit", "")):
raise ValueError("invalid_dependency_identity:" + name)
if not re.fullmatch(r"v22\.\d+\.\d+", lock.get("node", "")):
raise ValueError("invalid_node_version")
if not re.fullmatch(r"10\.\d+\.\d+", lock.get("npm", "")):
raise ValueError("invalid_npm_version")
return lock
def verify_checkout(path, commit):
if not SHA.fullmatch(commit):
raise ValueError("full_commit_sha_required")
if path.is_symlink() or not path.is_dir():
raise ValueError("regular_checkout_required:" + path.name)
top = Path(run(["git", "rev-parse", "--show-toplevel"], path, True).strip())
if top.resolve() != path.resolve():
raise ValueError("independent_checkout_required:" + path.name)
actual = run(["git", "rev-parse", "HEAD"], path, True).strip()
if actual != commit:
raise ValueError("source_commit_mismatch:" + path.name)
if run(["git", "status", "--porcelain", "--untracked-files=normal"], path, True).strip():
raise ValueError("dirty_source_checkout:" + path.name)
def verify_sources(root, commit, lock):
verify_checkout(root, commit)
for name, item in lock["dependencies"].items():
verify_checkout(root.parent / name, item["commit"])
def fetch_dependencies(root, lock):
# Never reset an operator checkout or reuse an earlier job's workspace.
for name in DEPENDENCIES:
target = root.parent / name
if target.exists() or target.is_symlink():
raise ValueError("dependency_destination_exists:" + name)
for name, item in lock["dependencies"].items():
target = root.parent / name
target.mkdir()
run(["git", "init", "--quiet"], target)
run(["git", "remote", "add", "origin", item["url"]], target)
run(["git", "fetch", "--quiet", "--depth=1", "origin", item["commit"]], target)
run(["git", "checkout", "--quiet", "--detach", "FETCH_HEAD"], target)
verify_checkout(target, item["commit"])
def tree_digest(root):
"""Digest paths + lengths + bytes, independent of mtime, owner and checkout path."""
digest = hashlib.sha256()
if not root.is_dir() or root.is_symlink():
raise ValueError("build_output_missing")
count = 0
for path in sorted(root.rglob("*")):
if path.is_symlink():
raise ValueError("symlink_in_build_output")
if path.is_dir():
continue
if not path.is_file():
raise ValueError("nonregular_build_output")
data = path.read_bytes()
name = path.relative_to(root).as_posix().encode()
digest.update(len(name).to_bytes(8, "big") + name)
digest.update(len(data).to_bytes(8, "big") + data)
count += 1
if count == 0:
raise ValueError("empty_build_output")
return digest.hexdigest()
def qualify(root, commit, lock, report):
if report.exists():
raise ValueError("qualification_report_already_exists")
verify_sources(root, commit, lock)
for tool in ("node", "npm"):
if run([tool, "--version"], root, True).strip() != lock[tool]:
raise ValueError("toolchain_version_mismatch:" + tool)
design = root.parent / "NODEDC_DESIGN_GUIDELINE"
steps = [
("design-install", design, ["npm", "ci", "--ignore-scripts", "--no-audit", "--no-fund"]),
("design-core", design, ["npm", "run", "build", "--workspace", "@nodedc/ui-core"]),
("design-react", design, ["npm", "run", "build", "--workspace", "@nodedc/ui-react"]),
("device-install", root, ["npm", "ci", "--ignore-scripts", "--no-audit", "--no-fund"]),
("unit-tests", root, ["npm", "test"]),
("ci-contract", root, [sys.executable, "-m", "unittest", "discover", "-s", "infra/ci", "-p", "test_*.py"]),
("build", root, ["npm", "run", "build"]),
("artifact-contracts", root, ["npm", "run", "test:deploy"]),
]
completed = []
for name, cwd, command in steps:
print("ci_step=" + name, flush=True)
if name in ("design-install", "device-install"):
install_dependencies(cwd)
if name == "device-install":
print("ci_dependency_check=core-standalone-runtime", flush=True)
qualify_core_runtime(root)
else:
run(command, cwd)
completed.append(name)
verify_sources(root, commit, lock)
result = {
"schema": "nodedc.device-core.qualification.v1",
"status": "qualified",
"deployed": False,
"sourceCommit": commit,
"sources": lock,
"sourceLockSha256": hashlib.sha256((root / "infra/ci/sources.lock.json").read_bytes()).hexdigest(),
"packageLockSha256": hashlib.sha256((root / "package-lock.json").read_bytes()).hexdigest(),
"managerDistSha256": tree_digest(root / "apps/device-manager/dist"),
"steps": completed,
}
report.parent.mkdir(parents=True, exist_ok=True)
with report.open("x") as stream:
json.dump(result, stream, indent=2)
stream.write("\n")
print(json.dumps(result), flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("fetch-dependencies", "verify", "check"))
parser.add_argument("--commit", required=True)
parser.add_argument("--report", type=Path)
args = parser.parse_args()
root = Path(__file__).resolve().parents[2]
verify_checkout(root, args.commit)
lock = read_lock(root)
if args.action == "fetch-dependencies":
fetch_dependencies(root, lock)
elif args.action == "verify":
verify_sources(root, args.commit, lock)
else:
if args.report is None:
parser.error("check requires --report outside the source checkouts")
report = args.report.resolve()
for checkout in (root, *(root.parent / name for name in DEPENDENCIES)):
if report.is_relative_to(checkout):
raise ValueError("report_must_be_outside_sources")
qualify(root, args.commit, lock, report)
if __name__ == "__main__":
main()
+19
View File
@@ -0,0 +1,19 @@
{
"schema": "nodedc.device-core.ci-sources.v1",
"node": "v22.21.0",
"npm": "10.9.4",
"dependencies": {
"NODEDC_DESIGN_GUIDELINE": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"commit": "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2"
},
"NODEDC_LAUNCHER": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
"commit": "f3a48b80c8256fecb4ef1442242f2211379a8521"
},
"platform": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
"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()
+192
View File
@@ -0,0 +1,192 @@
import importlib.util
import io
import json
from contextlib import redirect_stdout
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest import mock
SPEC = importlib.util.spec_from_file_location("qualify", Path(__file__).with_name("qualify.py"))
CI = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(CI)
class QualificationTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / "source"
self.root.mkdir()
self.git("init", "--quiet")
self.git("config", "user.name", "CI Test")
self.git("config", "user.email", "ci@example.invalid")
(self.root / "source.txt").write_text("committed\n")
self.git("add", "source.txt")
self.git("commit", "--quiet", "-m", "fixture")
self.commit = self.git("rev-parse", "HEAD").strip()
def git(self, *args):
return subprocess.check_output(["git", *args], cwd=self.root, text=True)
def test_clean_exact_commit_is_accepted(self):
CI.verify_checkout(self.root, self.commit)
def test_stale_commit_is_rejected(self):
with self.assertRaisesRegex(ValueError, "source_commit_mismatch"):
CI.verify_checkout(self.root, "a" * 40)
def test_branch_name_is_not_a_release_identity(self):
with self.assertRaisesRegex(ValueError, "full_commit_sha_required"):
CI.verify_checkout(self.root, "main")
def test_local_edits_cannot_be_credited_to_a_commit(self):
(self.root / "source.txt").write_text("uncommitted\n")
with self.assertRaisesRegex(ValueError, "dirty_source_checkout"):
CI.verify_checkout(self.root, self.commit)
def test_untracked_source_is_rejected(self):
(self.root / "extra.mjs").write_text("export default 1")
with self.assertRaisesRegex(ValueError, "dirty_source_checkout"):
CI.verify_checkout(self.root, self.commit)
def test_parent_git_repository_is_not_accepted_as_a_dependency(self):
child = self.root / "child"
child.mkdir()
with self.assertRaisesRegex(ValueError, "independent_checkout_required"):
CI.verify_checkout(child, self.commit)
def test_existing_operator_dependencies_are_never_overwritten(self):
dependency = self.root.parent / "NODEDC_DESIGN_GUIDELINE"
dependency.mkdir()
marker = dependency / "local-work"
marker.write_text("preserve")
with self.assertRaisesRegex(ValueError, "dependency_destination_exists"):
CI.fetch_dependencies(self.root, {})
self.assertEqual(marker.read_text(), "preserve")
def test_lock_cannot_fetch_a_different_repository(self):
lock = json.loads(Path(__file__).with_name("sources.lock.json").read_text())
lock["dependencies"]["platform"]["url"] = "https://example.invalid/other.git"
(self.root / "infra/ci").mkdir(parents=True)
(self.root / "infra/ci/sources.lock.json").write_text(json.dumps(lock))
with self.assertRaisesRegex(ValueError, "invalid_dependency_identity:platform"):
CI.read_lock(self.root)
def test_digest_is_path_independent_and_changes_with_content(self):
a, b = self.root / "a", self.root / "b"
for directory in (a, b):
directory.mkdir()
(directory / "index.html").write_text("same")
self.assertEqual(CI.tree_digest(a), CI.tree_digest(b))
(b / "index.html").write_text("different")
self.assertNotEqual(CI.tree_digest(a), CI.tree_digest(b))
def test_build_cannot_include_external_symlinks(self):
output = self.root / "dist"
output.mkdir()
(output / "index.html").symlink_to(self.root / "source.txt")
with self.assertRaisesRegex(ValueError, "symlink_in_build_output"):
CI.tree_digest(output)
def test_failed_step_never_writes_success_report_or_runs_later_steps(self):
report = self.root.parent / "result.json"
lock = {"node": "v22.21.0", "npm": "10.9.4"}
with mock.patch.object(CI, "verify_sources"), mock.patch.object(
CI, "run", side_effect=["v22.21.0\n", "10.9.4\n", subprocess.CalledProcessError(1, "npm")]
) as execute:
with self.assertRaises(subprocess.CalledProcessError):
CI.qualify(self.root, self.commit, lock, report)
self.assertEqual(execute.call_count, 3)
self.assertFalse(report.exists())
def test_existing_report_cannot_be_mistaken_for_new_success(self):
report = self.root.parent / "result.json"
report.write_text('{"sourceCommit":"old"}')
with self.assertRaisesRegex(ValueError, "qualification_report_already_exists"):
CI.qualify(self.root, self.commit, {}, report)
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__":
unittest.main()
@@ -0,0 +1,92 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const sourceRoot = resolve(scriptDir, "../..");
const artifactDir = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|| resolve(scriptDir, "../deploy-artifacts"),
);
const [
patchId = "device-control-core-incident-audit-20260822-043",
...extra
] = process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
throw new Error("usage: build-device-control-core-incident-audit-artifact.mjs [patch-id]");
}
const entry = "deployment/device-control-core-incident-audit-v1.json";
const stage = await mkdtemp(join(tmpdir(), "nodedc-control-core-incident-audit-"));
const payload = join(stage, "payload");
const target = resolve(artifactDir, `nodedc-device-plane-${patchId}.tgz`);
try {
const descriptor = JSON.parse(await readFile(resolve(sourceRoot, entry), "utf8"));
if (
descriptor.schemaVersion
!== "nodedc.device-plane.device-control-core-incident-audit.v1"
|| descriptor.mode !== "double-rollback-failed-read-only-audit"
|| descriptor.allowedOperation !== "canonical-plan-only"
|| descriptor.applyAllowed !== false
|| descriptor.runtimeMutation !== "none"
|| descriptor.sourceMutation !== "none"
|| descriptor.databaseMutation !== "none"
|| descriptor.networkMutation !== "none"
|| descriptor.secretRead !== "none"
) {
throw new Error("device_control_core_incident_audit_descriptor_mismatch");
}
await mkdir(dirname(join(payload, entry)), { recursive: true });
await cp(resolve(sourceRoot, entry), join(payload, entry), { force: true });
await writeFile(
join(stage, "manifest.env"),
`id=${patchId}\ncomponent=device-plane\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${entry}\n`, "utf8");
await mkdir(artifactDir, { recursive: true });
const tar = spawnSync(
"python3",
["-c", canonicalTarScript(), target, stage],
{ encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
);
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
const sha256 = createHash("sha256")
.update(await readFile(target))
.digest("hex");
console.log(JSON.stringify({
ok: true,
patchId,
component: "device-plane",
artifact: target,
sha256,
entries: [entry],
build: [],
services: [],
allowedOperation: descriptor.allowedOperation,
runtimeMutation: descriptor.runtimeMutation,
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix()); info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -0,0 +1,95 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const sourceRoot = resolve(scriptDir, "../..");
const artifactDir = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|| resolve(scriptDir, "../deploy-artifacts"),
);
const [
patchId = "device-control-core-migration-replay-audit-20260822-045",
...extra
] = process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
throw new Error(
"usage: build-device-control-core-migration-replay-audit-artifact.mjs [patch-id]",
);
}
const entry = "deployment/device-control-core-migration-replay-audit-v1.json";
const stage = await mkdtemp(join(tmpdir(), "nodedc-control-core-migration-audit-"));
const payload = join(stage, "payload");
const target = resolve(artifactDir, `nodedc-device-plane-${patchId}.tgz`);
try {
const descriptor = JSON.parse(await readFile(resolve(sourceRoot, entry), "utf8"));
if (
descriptor.schemaVersion
!== "nodedc.device-plane.device-control-core-migration-replay-audit.v1"
|| descriptor.mode
!== "rejected-recovery-044-live-invariants-read-only-audit"
|| descriptor.allowedOperation !== "canonical-plan-only"
|| descriptor.applyAllowed !== false
|| descriptor.runtimeMutation !== "none"
|| descriptor.sourceMutation !== "none"
|| descriptor.databaseMutation !== "none"
|| descriptor.networkMutation !== "none"
|| descriptor.secretRead !== "none"
) {
throw new Error("device_control_core_migration_replay_audit_descriptor_mismatch");
}
await mkdir(dirname(join(payload, entry)), { recursive: true });
await cp(resolve(sourceRoot, entry), join(payload, entry), { force: true });
await writeFile(
join(stage, "manifest.env"),
`id=${patchId}\ncomponent=device-plane\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${entry}\n`, "utf8");
await mkdir(artifactDir, { recursive: true });
const tar = spawnSync(
"python3",
["-c", canonicalTarScript(), target, stage],
{ encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
);
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
const sha256 = createHash("sha256")
.update(await readFile(target))
.digest("hex");
console.log(JSON.stringify({
ok: true,
patchId,
component: "device-plane",
artifact: target,
sha256,
entries: [entry],
build: [],
services: [],
allowedOperation: descriptor.allowedOperation,
runtimeMutation: descriptor.runtimeMutation,
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix()); info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -0,0 +1,106 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const sourceRoot = resolve(scriptDir, "../..");
const artifactDir = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|| resolve(scriptDir, "../deploy-artifacts"),
);
const [
patchId = "device-control-core-migration-replay-checkpoint-recovery-20260822-046",
...extra
] = process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
throw new Error(
"usage: build-device-control-core-migration-replay-checkpoint-recovery-artifact.mjs [patch-id]",
);
}
const entries = [
"services/device-control-core/migrations/014_device_registry_profile_commands.sql",
"deployment/device-control-core-migration-replay-checkpoint-recovery-v2.json",
];
const stage = await mkdtemp(join(tmpdir(), "nodedc-control-core-replay-checkpoint-"));
const payload = join(stage, "payload");
const target = resolve(artifactDir, `nodedc-device-plane-${patchId}.tgz`);
try {
const descriptor = JSON.parse(await readFile(resolve(sourceRoot, entries[1]), "utf8"));
const targetBytes = await readFile(resolve(sourceRoot, entries[0]));
const targetSha256 = createHash("sha256").update(targetBytes).digest("hex");
if (
descriptor.schemaVersion
!== "nodedc.device-plane.device-control-core-migration-replay-checkpoint-recovery.v2"
|| descriptor.mode !== "terminal-044-replay-checkpoint-forward-repair"
|| descriptor.failedRecovery?.patchId
!== "device-control-core-migration-replay-recovery-20260822-044"
|| descriptor.failedRecovery?.artifactSha256
!== "b893d8c90f98943797d32f486d6477d58a3be69eb1291e28c4a4bbd2e96774b7"
|| descriptor.failedRecovery?.startedApply !== false
|| descriptor.sourceTarget.path !== entries[0]
|| descriptor.sourceTarget.sha256 !== targetSha256
|| descriptor.databaseRowMutation !== "none"
|| descriptor.runtimeAction !== "build+recreate-device-control-core-only"
) {
throw new Error(
"device_control_core_migration_replay_checkpoint_recovery_descriptor_mismatch",
);
}
for (const entry of entries) {
await mkdir(dirname(join(payload, entry)), { recursive: true });
await cp(resolve(sourceRoot, entry), join(payload, entry), { force: true });
}
await writeFile(
join(stage, "manifest.env"),
`id=${patchId}\ncomponent=device-plane\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, "utf8");
await mkdir(artifactDir, { recursive: true });
const tar = spawnSync(
"python3",
["-c", canonicalTarScript(), target, stage],
{ encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
);
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
const sha256 = createHash("sha256")
.update(await readFile(target))
.digest("hex");
console.log(JSON.stringify({
ok: true,
patchId,
component: "device-plane",
artifact: target,
sha256,
entries,
build: ["nodedc/device-control-core:local"],
services: ["device-control-core"],
transition: descriptor.mode,
databaseRowMutation: descriptor.databaseRowMutation,
runtimeAction: descriptor.runtimeAction,
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix()); info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -0,0 +1,99 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const sourceRoot = resolve(scriptDir, "../..");
const artifactDir = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|| resolve(scriptDir, "../deploy-artifacts"),
);
const [
patchId = "device-control-core-migration-replay-recovery-20260822-044",
...extra
] = process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
throw new Error(
"usage: build-device-control-core-migration-replay-recovery-artifact.mjs [patch-id]",
);
}
const entries = [
"services/device-control-core/migrations/014_device_registry_profile_commands.sql",
"deployment/device-control-core-migration-replay-recovery-v1.json",
];
const stage = await mkdtemp(join(tmpdir(), "nodedc-control-core-migration-replay-"));
const payload = join(stage, "payload");
const target = resolve(artifactDir, `nodedc-device-plane-${patchId}.tgz`);
try {
const descriptor = JSON.parse(await readFile(resolve(sourceRoot, entries[1]), "utf8"));
const targetBytes = await readFile(resolve(sourceRoot, entries[0]));
const targetSha256 = createHash("sha256").update(targetBytes).digest("hex");
if (
descriptor.schemaVersion
!== "nodedc.device-plane.device-control-core-migration-replay-recovery.v1"
|| descriptor.mode !== "double-rollback-failed-migration-014-forward-repair"
|| descriptor.sourceTarget.path !== entries[0]
|| descriptor.sourceTarget.sha256 !== targetSha256
|| descriptor.databaseRowMutation !== "none"
|| descriptor.runtimeAction !== "build+recreate-device-control-core-only"
) {
throw new Error("device_control_core_migration_replay_recovery_descriptor_mismatch");
}
for (const entry of entries) {
await mkdir(dirname(join(payload, entry)), { recursive: true });
await cp(resolve(sourceRoot, entry), join(payload, entry), { force: true });
}
await writeFile(
join(stage, "manifest.env"),
`id=${patchId}\ncomponent=device-plane\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, "utf8");
await mkdir(artifactDir, { recursive: true });
const tar = spawnSync(
"python3",
["-c", canonicalTarScript(), target, stage],
{ encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
);
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
const sha256 = createHash("sha256")
.update(await readFile(target))
.digest("hex");
console.log(JSON.stringify({
ok: true,
patchId,
component: "device-plane",
artifact: target,
sha256,
entries,
build: ["nodedc/device-control-core:local"],
services: ["device-control-core"],
transition: descriptor.mode,
databaseRowMutation: descriptor.databaseRowMutation,
runtimeAction: descriptor.runtimeAction,
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix()); info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -16,14 +16,16 @@ const [
predecessorSha256,
...extra
] = process.argv.slice(2);
const isV4 = patchId.startsWith("device-control-core-release-v4-");
if (
extra.length
|| !/^device-control-core-release-[A-Za-z0-9._-]{1,67}$/.test(patchId)
|| !/^device-control-core-release(?:-v[234])?-[A-Za-z0-9._-]{1,67}$/.test(patchId)
|| (isV4 && patchId !== "device-control-core-release-v4-20260823-047")
|| ((predecessorPatchId === undefined) !== (predecessorSha256 === undefined))
|| (
predecessorPatchId !== undefined
&& (
!/^device-control-core-release-[A-Za-z0-9._-]{1,67}$/.test(predecessorPatchId)
!/^(?:device-control-core-release(?:-v[234])?-[A-Za-z0-9._-]{1,67}|device-control-core-migration-replay-checkpoint-recovery-20260822-046)$/.test(predecessorPatchId)
|| predecessorPatchId === patchId
|| !/^[0-9a-f]{64}$/.test(predecessorSha256)
)
@@ -35,12 +37,44 @@ if (
);
}
const isV3 = patchId.startsWith("device-control-core-release-v3-");
const isV2 = patchId.startsWith("device-control-core-release-v2-");
const includesTelemetry = isV3 || isV4;
const coreDockerfile = await readFile(
resolve(devicePlaneRoot, "services/device-control-core/Dockerfile"),
"utf8",
);
if (
!includesTelemetry
&& coreDockerfile.includes(
"COPY packages/infrastructure-telemetry-contract ./packages/infrastructure-telemetry-contract",
)
) {
throw new Error("historical_device_control_core_builder_has_advanced");
}
const expectedV2Predecessor = Object.freeze({
patchId: predecessorPatchId ?? "device-control-core-release-20260812-024",
artifactSha256: predecessorSha256 ?? "a289e909283109642e6bba3d9822a31f63423cfe0bbcd52705979681bd2bc793",
});
const descriptorPath = isV2
const expectedV4Predecessor = Object.freeze({
patchId: "device-control-core-migration-replay-checkpoint-recovery-20260822-046",
artifactSha256: "46000c76977fb583fc7c9cf74ecf624efd8b404f7b8d0322e0270e7b8ac6e450",
});
if (
isV4
&& predecessorPatchId !== undefined
&& (
predecessorPatchId !== expectedV4Predecessor.patchId
|| predecessorSha256 !== expectedV4Predecessor.artifactSha256
)
) {
throw new Error("device_control_core_release_v4_predecessor_mismatch");
}
const descriptorPath = isV4
? "deployment/device-control-core-release-v4.json"
: isV3
? "deployment/device-control-core-release-v3.json"
: isV2
? "deployment/device-control-core-release-v2.json"
: "deployment/device-control-core-release-v1.json";
const entries = [
@@ -49,6 +83,7 @@ const entries = [
"package-lock.json",
"packages/device-protocol-contract",
"packages/device-edge-channel-contract",
...(includesTelemetry ? ["packages/infrastructure-telemetry-contract"] : []),
"services/device-control-core",
descriptorPath,
];
@@ -67,7 +102,9 @@ try {
descriptor.releaseId = patchId;
if (predecessorPatchId !== undefined) {
descriptor.predecessor = {
kind: "release",
kind: isV4
? "migration-replay-checkpoint-recovery"
: "release",
patchId: predecessorPatchId,
artifactSha256: predecessorSha256,
};
@@ -88,6 +125,7 @@ try {
"services/device-control-core/src/device-gateway-core-runtime.mjs",
"packages/device-protocol-contract/src/index.mjs",
"packages/device-edge-channel-contract/src/index.mjs",
...(includesTelemetry ? ["packages/infrastructure-telemetry-contract/src/index.mjs"] : []),
]) {
const imported = spawnSync(
process.execPath,
@@ -101,7 +139,7 @@ try {
const descriptor = JSON.parse(await readFile(join(payload, descriptorPath), "utf8"));
if (
descriptor.schemaVersion !== `nodedc.device-plane.device-control-core-release.${isV2 ? "v2" : "v1"}`
descriptor.schemaVersion !== `nodedc.device-plane.device-control-core-release.${isV4 ? "v4" : isV3 ? "v3" : isV2 ? "v2" : "v1"}`
|| descriptor.releaseId !== patchId
|| descriptor.action !== "upgrade"
|| descriptor.service !== "device-control-core"
@@ -113,16 +151,37 @@ try {
|| JSON.stringify(descriptor.coreNetworks) !== JSON.stringify(["device-plane-private", "device-plane-egress"])
|| descriptor.publicIngress !== "none-on-synology"
|| descriptor.edgeRegistrations !== "preserved"
|| descriptor.commandTransport !== (isV2 ? "typed-service-ping-v1" : "disabled")
|| descriptor.gelios !== (isV2 ? "untouched-legacy-only" : "untouched")
|| descriptor.commandTransport !== ((isV2 || isV3 || isV4) ? "typed-service-ping-v1" : "disabled")
|| descriptor.gelios !== ((isV2 || isV3 || isV4) ? "untouched-legacy-only" : "untouched")
|| descriptor.rollback !== "restore-preapply-source-and-core-runtime"
|| (
isV2
(isV2 || isV3 || isV4)
&& (
descriptor.commandCatalog !== "allowlisted-adapter-typed-commands-only"
|| descriptor.credentialBoundary !== "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned"
|| descriptor.predecessor?.patchId !== expectedV2Predecessor.patchId
|| descriptor.predecessor?.artifactSha256 !== expectedV2Predecessor.artifactSha256
|| descriptor.predecessor?.patchId !== (isV4 ? expectedV4Predecessor : expectedV2Predecessor).patchId
|| descriptor.predecessor?.artifactSha256 !== (isV4 ? expectedV4Predecessor : expectedV2Predecessor).artifactSha256
)
)
|| (
includesTelemetry
&& (
descriptor.telemetryTransport !== "edge-channel-host-telemetry-observed-v1"
|| descriptor.telemetryContract !== "nodedc.infrastructure.host-telemetry.v1"
|| descriptor.telemetryStorage !== "device-control-core-postgres-seven-day-retention"
|| descriptor.ontologyProjection !== "observation-observed-property-provenance-freshness-v1"
|| descriptor.telemetryFreshness !== "fifteen-seconds-missing-stale-not-unhealthy"
)
)
|| (
isV4
&& (
descriptor.predecessor?.kind !== "migration-replay-checkpoint-recovery"
|| descriptor.recoveryPredecessor !== "terminal-applied-046-exact-source-runtime-database"
|| descriptor.databasePreflight !== "final-migration-016-validated-and-host-telemetry-table-absent"
|| descriptor.databaseRowMutation !== "none-before-core-startup-migrations"
|| descriptor.databaseSchemaOutcome !== "migration-017-host-telemetry-table-present"
|| descriptor.runtimePredecessor !== "healthy-recovery-046-core-generation"
)
)
) {
@@ -0,0 +1,114 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const sourceRoot = resolve(scriptDir, "../..");
const artifactDir = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|| resolve(scriptDir, "../deploy-artifacts"),
);
const [
patchId = "device-control-core-release-v3-reconciliation-20260822-042",
...extra
] = process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
throw new Error(
"usage: build-device-control-core-release-v3-reconciliation-artifact.mjs [patch-id]",
);
}
const entry = "deployment/device-control-core-release-v3-reconciliation-v1.json";
const stage = await mkdtemp(join(tmpdir(), "nodedc-control-core-v3-reconciliation-"));
const payload = join(stage, "payload");
const target = resolve(artifactDir, `nodedc-device-plane-${patchId}.tgz`);
try {
const descriptor = JSON.parse(await readFile(resolve(sourceRoot, entry), "utf8"));
const expected = {
schemaVersion: "nodedc.device-plane.device-control-core-release-v3-reconciliation.v1",
mode: "failed-release-v3-exact-preapply-image-restore",
failedPatchId: "device-control-core-release-v3-20260822-040",
failedArtifactSha256:
"08448a56cdf391076f92c5242e368fd0033b420167874645eebfa1f22184ee92",
failedArtifact:
"nodedc-device-plane-device-control-core-release-v3-20260822-040.tgz.20260822-184245",
backupId:
"device-plane-device-control-core-release-v3-20260822-040-20260822-184245",
predecessorPatchId: "device-control-core-release-v2-20260822-038",
predecessorArtifactSha256:
"e2d062b82b022dba662522b5d6e192026ac964d78950d903295ca3cbbc95ab28",
preapplyImageId:
"sha256:31d35733ee46225b487c0f02a7b52d4ba2d13f5b99f6a717b7f5e6f5460b412a",
sourceAction: "accept-byte-exact-restored-preapply-source",
runtimeAction: "retag-exact-preapply-image+recreate-device-control-core-only",
preservedServices: [
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target",
],
databaseVolume: "nodedc-device-plane-postgres-data",
publicIngress: "disabled",
edgeChannel: "core-initiated-pinned-mtls-registered-edges-only",
commandTransport: "typed-service-ping-v1",
gelios: "untouched-legacy-only",
rollback: "marker+exact-preapply-image-runtime",
};
if (JSON.stringify(descriptor) !== JSON.stringify(expected)) {
throw new Error("device_control_core_v3_reconciliation_descriptor_mismatch");
}
await mkdir(dirname(join(payload, entry)), { recursive: true });
await cp(resolve(sourceRoot, entry), join(payload, entry), { force: true });
await writeFile(
join(stage, "manifest.env"),
`id=${patchId}\ncomponent=device-plane\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${entry}\n`, "utf8");
await mkdir(artifactDir, { recursive: true });
const tar = spawnSync(
"python3",
["-c", canonicalTarScript(), target, stage],
{ encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
);
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
const sha256 = createHash("sha256")
.update(await readFile(target))
.digest("hex");
console.log(JSON.stringify({
ok: true,
patchId,
component: "device-plane",
artifact: target,
sha256,
entries: [entry],
build: [],
services: ["device-control-core"],
transition: descriptor.mode,
runtimeAction: descriptor.runtimeAction,
preservedServices: descriptor.preservedServices,
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix()); info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -19,6 +19,17 @@ const upgradeV4 = patchId.startsWith("device-edge-core-channel-upgrade-v4-");
const upgradeV2 = !upgradeV4 && patchId.startsWith("device-edge-core-channel-upgrade-v2-");
const upgradeV1 = !upgradeV4 && !upgradeV2 && patchId.startsWith("device-edge-core-channel-upgrade-");
const upgrade = upgradeV1 || upgradeV2 || upgradeV4;
const coreDockerfile = await readFile(
resolve(devicePlaneRoot, "services/device-control-core/Dockerfile"),
"utf8",
);
if (
coreDockerfile.includes(
"COPY packages/infrastructure-telemetry-contract ./packages/infrastructure-telemetry-contract",
)
) {
throw new Error("historical_device_edge_core_channel_builder_has_advanced");
}
const descriptorPath = upgradeV4
? "deployment/device-edge-core-channel-upgrade-v4.json"
: upgradeV2
@@ -38,11 +38,12 @@ if (
"tailscale-retirement",
"tracker-ingress",
"command-transport",
"host-telemetry",
].includes(phase)
|| !/^[A-Za-z0-9._-]{1,96}$/.test(patchId || "")
) {
throw new Error(
"usage: build-device-edge-vps-artifact.mjs <foundation|runtime-reconciliation|backhaul|relay|core-channel|tailscale-retirement|tracker-ingress|command-transport> <patch-id>",
"usage: build-device-edge-vps-artifact.mjs <foundation|runtime-reconciliation|backhaul|relay|core-channel|tailscale-retirement|tracker-ingress|command-transport|host-telemetry> <patch-id>",
);
}
@@ -53,16 +54,22 @@ if (
) {
throw new Error("vps_initiated_transport_frozen:ADR-0001");
}
const acceptedSharedSourcePhases = new Set(["core-channel", "tracker-ingress"]);
const acceptedSharedSourcePhases = new Set([
"core-channel",
"tracker-ingress",
"command-transport",
]);
if (acceptedSharedSourcePhases.has(phase)) {
throw new Error(`accepted_vps_phase_rebuild_frozen:${phase}:ADR-0001`);
}
const nodeArchive = "node-v22.23.2-linux-x64.tar.xz";
const tailscaleArchive = "tailscale_1.102.2_amd64.tgz";
const telegrafArchive = "telegraf-1.38.4_linux_amd64.tar.gz";
const runtimeDigests = new Map([
[nodeArchive, "d60acfe00a2932254bb0ad20e01b0d74397a0875595de719654b214f4b03f307"],
[tailscaleArchive, "ad2cde12f8de95f7b93a1e0401e652291c603d42b9d60a33fb1741eb38ab04d8"],
[telegrafArchive, "81857e9745ebf26e058b6fdc27b9b2c210fd1fe61e57d7fad3d4bb9131f60041"],
]);
const entriesByPhase = {
@@ -130,6 +137,21 @@ const entriesByPhase = {
"vps/edge-process/device-edge-runtime.mjs",
"deployment/device-edge-vps-command-transport-v1.json",
],
"host-telemetry": [
"packages/device-edge-channel-contract/package.json",
"packages/device-edge-channel-contract/src",
"packages/infrastructure-telemetry-contract/package.json",
"packages/infrastructure-telemetry-contract/src",
"services/device-edge-channel/package.json",
"services/device-edge-channel/src",
"vps/edge-process/device-edge-runtime.mjs",
"vps/edge-process/host-telemetry-runtime.mjs",
"vps/config/nodedc-host-telemetry-telegraf.conf",
"vps/systemd/nodedc-device-edge-runtime.service",
"vps/systemd/nodedc-host-telemetry-agent.service",
"deployment/device-edge-vps-host-telemetry-v1.json",
`vendor/${telegrafArchive}`,
],
};
const entries = entriesByPhase[phase];
const ignoredBasenames = new Set([".DS_Store", ".git", "node_modules"]);
@@ -191,10 +213,10 @@ try {
? "tcp/9921"
: ["core-channel", "tailscale-retirement"].includes(phase)
? "tcp/443-mtls-only"
: ["tracker-ingress", "command-transport"].includes(phase)
: ["tracker-ingress", "command-transport", "host-telemetry"].includes(phase)
? "tcp/443-mtls+tcp/9921-telemetry"
: "disabled",
commandTransport: phase === "command-transport"
commandTransport: ["command-transport", "host-telemetry"].includes(phase)
? "typed-service-ping-v1"
: "disabled",
gelios: "untouched",
@@ -212,7 +234,7 @@ async function assertBoundary() {
if (
descriptor.component !== "device-edge-vps"
|| descriptor.runtimeHost !== "koffyvngij"
|| descriptor.commandTransport !== (phase === "command-transport"
|| descriptor.commandTransport !== (["command-transport", "host-telemetry"].includes(phase)
? "typed-service-ping-v1"
: "disabled")
|| !String(descriptor.gelios || "").startsWith("untouched")
@@ -419,6 +441,43 @@ async function assertBoundary() {
}
}
}
if (phase === "host-telemetry") {
if (!/^[0-9a-f]{64}$/.test(descriptor.predecessorArtifactSha256 || "")) {
throw new Error("host_telemetry_predecessor_sha256_invalid");
}
for (const required of [
'"predecessorPatch": "device-edge-vps-command-transport-20260812-013"',
'"agent": "telegraf"',
'"agentVersion": "1.38.4"',
'"transport": "existing-core-initiated-pinned-mtls-channel"',
'"mqtt": "disabled-no-public-broker-no-wan-plaintext"',
"User=nodedc-telemetry",
"IPAddressDeny=any",
"IPAddressAllow=localhost",
"MemoryMax=96M",
"CPUQuota=15%",
'url = "http://127.0.0.1:18223/internal/v1/host-telemetry"',
'data_format = "json"',
"submitHostTelemetry",
"createHostTelemetryCollector",
]) {
if (!combined.includes(required)) {
throw new Error(`host_telemetry_boundary_missing:${required}`);
}
}
for (const forbidden of [
"mqtt://",
"tcp://",
"outputs.mqtt",
"PRIVATE KEY",
"TS_AUTHKEY",
"device.dc.ru",
]) {
if (combined.includes(forbidden)) {
throw new Error(`host_telemetry_boundary_violation:${forbidden}`);
}
}
}
}
function canonicalTarScript() {
@@ -11,15 +11,52 @@ const platformRoot = resolve(scriptDir, "../..");
const devicePlaneRoot = platformRoot;
const managerRoot = resolve(platformRoot, "apps/device-manager");
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"));
const [patchId = "device-manager-release-v3-20260812-026", ...extra] = process.argv.slice(2);
const [patchId = "device-manager-release-v13-20260823-051", ...extra] = process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) throw new Error("usage: build-device-manager-control-plane-artifact.mjs [patch-id]");
const descriptorPath = patchId.startsWith("device-manager-release-v3-")
const descriptorPath = patchId.startsWith("device-manager-release-v13-")
? "deployment/device-manager-release-v13.json"
: patchId.startsWith("device-manager-release-v12-")
? "deployment/device-manager-release-v12.json"
: patchId.startsWith("device-manager-release-v11-")
? "deployment/device-manager-release-v11.json"
: patchId.startsWith("device-manager-release-v10-")
? "deployment/device-manager-release-v10.json"
: patchId.startsWith("device-manager-release-v9-")
? "deployment/device-manager-release-v9.json"
: patchId.startsWith("device-manager-release-v8-")
? "deployment/device-manager-release-v8.json"
: patchId.startsWith("device-manager-release-v7-")
? "deployment/device-manager-release-v7.json"
: patchId.startsWith("device-manager-release-v6-")
? "deployment/device-manager-release-v6.json"
: patchId.startsWith("device-manager-release-v5-")
? "deployment/device-manager-release-v5.json"
: patchId.startsWith("device-manager-release-v4-")
? "deployment/device-manager-release-v4.json"
: patchId.startsWith("device-manager-release-v3-")
? "deployment/device-manager-release-v3.json"
: "deployment/device-manager-release-v1.json";
const isV3 = descriptorPath.endsWith("release-v3.json");
const entries = isV3 ? [
const isV4 = descriptorPath.endsWith("release-v4.json");
const isV5 = descriptorPath.endsWith("release-v5.json");
const isV6 = descriptorPath.endsWith("release-v6.json");
const isV7 = descriptorPath.endsWith("release-v7.json");
const isV8 = descriptorPath.endsWith("release-v8.json");
const isV9 = descriptorPath.endsWith("release-v9.json");
const isV10 = descriptorPath.endsWith("release-v10.json");
const isV11 = descriptorPath.endsWith("release-v11.json");
const isV12 = descriptorPath.endsWith("release-v12.json");
const isV13 = descriptorPath.endsWith("release-v13.json");
const isPersistent = isV4 || isV5 || isV6 || isV7 || isV8 || isV9 || isV10 || isV11 || isV12 || isV13;
const isManagerOnly = isV3 || isPersistent;
const composeSource = resolve(devicePlaneRoot, "docker-compose.device-manager.yml");
const composeSourceSha256 = createHash("sha256").update(await readFile(composeSource)).digest("hex");
if (!isPersistent && composeSourceSha256 !== "4954120aaddc999798b64c304d8cf692b79714feb727d873117bd1f3434e865e") {
throw new Error("historical_device_manager_compose_has_advanced");
}
const entries = isManagerOnly ? [
"docker-compose.device-manager.yml",
"services/device-manager",
descriptorPath,
@@ -70,7 +107,7 @@ try {
}
await copySafe(resolve(devicePlaneRoot, entry), join(payload, entry), devicePlaneRoot);
}
if (!isV3) {
if (!isManagerOnly) {
await validateDockerCopySources(
join(payload, "services/device-control-core/Dockerfile"),
payload,
@@ -80,7 +117,7 @@ try {
join(payload, "services/device-manager/Dockerfile"),
join(payload, "services/device-manager"),
);
for (const modulePath of isV3 ? [] : [
for (const modulePath of isManagerOnly ? [] : [
"services/device-control-core/src/sensitive-reference-management.mjs",
"services/device-control-core/src/device-gateway-core-runtime.mjs",
"packages/device-edge-channel-contract/src/index.mjs",
@@ -111,6 +148,14 @@ try {
"NODEDC_LAUNCHER_INTERNAL_TOKEN_FILE: /run/nodedc-secrets/device-core-internal-token",
"NODEDC_DEVICE_CORE_TOKEN_FILE: /run/nodedc-secrets/management-core-token",
"name: nodedc-platform_edge",
...(isPersistent ? [
"NODEDC_DEVICE_MANAGER_PRESENTATION_PATH: /var/lib/nodedc-device-manager/device-manager-presentation.json",
"NODEDC_DEVICE_MANAGER_MEDIA_ROOT: /var/lib/nodedc-device-manager/media",
"source: /volume1/docker/nodedc-device-plane/data/device-manager",
"target: /var/lib/nodedc-device-manager",
"read_only: false",
"create_host_path: false",
] : []),
]) if (!compose.includes(required)) throw new Error(`device_manager_compose_contract_missing:${required}`);
for (const forbidden of [
"NODEDC_INTERNAL_ACCESS_TOKEN:",
@@ -135,18 +180,303 @@ try {
|| !/^[A-Za-z0-9._-]{1,96}$/.test(predecessor.patchId || "")
|| !/^[a-f0-9]{64}$/.test(predecessor.artifactSha256 || "")
|| (descriptor.action === "activate") !== (predecessor.kind === "reconciliation")
|| descriptor.healthGate !== "bounded-container-grace+core-contract"
|| descriptor.rollback !== "restore-preapply-snapshot"
|| descriptor.healthGate !== (isPersistent
? "bounded-container-grace+core-contract+persistent-data"
: "bounded-container-grace+core-contract")
|| descriptor.rollback !== (isPersistent
? "restore-preapply-snapshot-preserve-manager-data"
: "restore-preapply-snapshot")
);
if (commonContractInvalid) throw new Error("device_manager_activation_successor_contract_mismatch");
if (descriptorPath.endsWith("release-v3.json")) {
if (descriptorPath.endsWith("release-v13.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v13"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v12-20260823-050"
|| descriptor.predecessor?.artifactSha256 !== "1a49839140e5f2e49763d78f24ee47d946e244bcfde15a9c38266e8bd14c0d49"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v4-20260823-047"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.designSystem !== "nodedc-canonical-components-and-tokens-v1"
|| descriptor.missionCoreReference !== "compute-modules-workspace-71c8b04"
|| descriptor.infrastructureWorkspaceLayout !== "mission-core-system-workspace-v2"
|| descriptor.hostInventoryComposition !== "mission-core-compute-host-accordion-v2"
|| descriptor.hostInventoryOverviewSurface !== "separate-summary-soft-surface-v1"
|| descriptor.hostInventoryCollectionSurface !== "separate-host-collection-soft-surface-v1"
|| descriptor.hostInventoryRow !== "compact-centered-accordion-v1"
|| descriptor.hostInventoryFreshness !== "dot-only-v1"
|| descriptor.hostInventoryRelations !== "host-scoped-endpoint-deployment-service-v1"
|| descriptor.hostInventoryDefaultExpansion !== "collapsed"
|| descriptor.hostInventoryScaleTarget !== "five-hundred-collapsed-rows-v1"
|| descriptor.telemetryWorkspace !== "mission-core-compute-module-adaptive-window-v3"
|| descriptor.telemetrySurface !== "borderless-soft-surface-v1"
|| descriptor.telemetryStatus !== "mission-core-dot-status-v1"
|| descriptor.telemetryNavigation !== "full-workspace-back-navigation-v1"
|| descriptor.telemetryScroll !== "reset-on-workspace-transition-v1"
|| descriptor.telemetryPollInterval !== "three-seconds"
|| descriptor.telemetryFreshness !== "fifteen-seconds-missing-stale-not-unhealthy"
|| descriptor.telemetryOntologyProjection !== "observation-observed-property-provenance-freshness-v1"
|| descriptor.telemetryAgent !== "telegraf-host-observer-v1"
|| descriptor.telemetryGraphScale !== "adaptive-observed-window-explicit-domain-v1"
|| descriptor.telemetryCpuMinimumSpan !== "five-percentage-points"
|| descriptor.telemetryMemoryMinimumSpan !== "four-percentage-points"
|| descriptor.telemetryNetworkMissingSemantics !== "missing-counters-never-zero-v1"
|| descriptor.interactiveShell !== "disabled-pending-managed-session-boundary"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v13_host_inventory_accordion_contract_mismatch");
await validateFaviconBundle(payload, "device_manager_v13");
} else if (descriptorPath.endsWith("release-v12.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v12"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v11-20260823-049"
|| descriptor.predecessor?.artifactSha256 !== "c1e2056b50bfbb0d03d077461d0c27cc56cc52967c3f5620be14871c8a6d5cf0"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v4-20260823-047"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.designSystem !== "nodedc-canonical-components-and-tokens-v1"
|| descriptor.missionCoreReference !== "compute-modules-workspace-71c8b04"
|| descriptor.infrastructureWorkspaceLayout !== "mission-core-system-workspace-v1"
|| descriptor.hostInventoryComposition !== "mission-core-compute-host-list-v1"
|| descriptor.telemetryWorkspace !== "mission-core-compute-module-adaptive-window-v3"
|| descriptor.telemetrySurface !== "borderless-soft-surface-v1"
|| descriptor.telemetryStatus !== "mission-core-dot-status-v1"
|| descriptor.telemetryNavigation !== "full-workspace-back-navigation-v1"
|| descriptor.telemetryScroll !== "reset-on-workspace-transition-v1"
|| descriptor.telemetryPollInterval !== "three-seconds"
|| descriptor.telemetryFreshness !== "fifteen-seconds-missing-stale-not-unhealthy"
|| descriptor.telemetryOntologyProjection !== "observation-observed-property-provenance-freshness-v1"
|| descriptor.telemetryAgent !== "telegraf-host-observer-v1"
|| descriptor.telemetryGraphScale !== "adaptive-observed-window-explicit-domain-v1"
|| descriptor.telemetryCpuMinimumSpan !== "five-percentage-points"
|| descriptor.telemetryMemoryMinimumSpan !== "four-percentage-points"
|| descriptor.telemetryNetworkMissingSemantics !== "missing-counters-never-zero-v1"
|| descriptor.interactiveShell !== "disabled-pending-managed-session-boundary"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v12_adaptive_telemetry_graph_contract_mismatch");
await validateFaviconBundle(payload, "device_manager_v12");
} else if (descriptorPath.endsWith("release-v11.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v11"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v10-20260823-048"
|| descriptor.predecessor?.artifactSha256 !== "e6b983a314db4f8c27d89062dfedf5ed0523cc30421170799d181a19e2d85d4c"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v4-20260823-047"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.designSystem !== "nodedc-canonical-components-and-tokens-v1"
|| descriptor.missionCoreReference !== "compute-modules-workspace-71c8b04"
|| descriptor.infrastructureWorkspaceLayout !== "mission-core-system-workspace-v1"
|| descriptor.hostInventoryComposition !== "mission-core-compute-host-list-v1"
|| descriptor.telemetryWorkspace !== "mission-core-compute-module-visual-parity-v2"
|| descriptor.telemetrySurface !== "borderless-soft-surface-v1"
|| descriptor.telemetryStatus !== "mission-core-dot-status-v1"
|| descriptor.telemetryNavigation !== "full-workspace-back-navigation-v1"
|| descriptor.telemetryScroll !== "reset-on-workspace-transition-v1"
|| descriptor.telemetryPollInterval !== "three-seconds"
|| descriptor.telemetryFreshness !== "fifteen-seconds-missing-stale-not-unhealthy"
|| descriptor.telemetryOntologyProjection !== "observation-observed-property-provenance-freshness-v1"
|| descriptor.telemetryAgent !== "telegraf-host-observer-v1"
|| descriptor.interactiveShell !== "disabled-pending-managed-session-boundary"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v11_mission_core_visual_parity_contract_mismatch");
await validateFaviconBundle(payload, "device_manager_v11");
} else if (descriptorPath.endsWith("release-v10.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v10"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v8-20260822-039"
|| descriptor.predecessor?.artifactSha256 !== "30a83d4c6b5c029c96c4af19fa558e0ae75e4b60bc897881457304bd17e0e465"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v4-20260823-047"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.telemetryWorkspace !== "mission-core-compute-module-parity-v1"
|| descriptor.telemetryNavigation !== "full-workspace-back-navigation-v1"
|| descriptor.telemetryPollInterval !== "three-seconds"
|| descriptor.telemetryFreshness !== "fifteen-seconds-missing-stale-not-unhealthy"
|| descriptor.telemetryOntologyProjection !== "observation-observed-property-provenance-freshness-v1"
|| descriptor.telemetryAgent !== "telegraf-host-observer-v1"
|| descriptor.interactiveShell !== "disabled-pending-managed-session-boundary"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v10_host_telemetry_workspace_contract_mismatch");
await validateFaviconBundle(payload, "device_manager_v10");
} else if (descriptorPath.endsWith("release-v9.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v9"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v8-20260822-039"
|| descriptor.predecessor?.artifactSha256 !== "30a83d4c6b5c029c96c4af19fa558e0ae75e4b60bc897881457304bd17e0e465"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v3-20260822-040"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "08448a56cdf391076f92c5242e368fd0033b420167874645eebfa1f22184ee92"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.telemetryWorkspace !== "mission-core-compute-module-parity-v1"
|| descriptor.telemetryNavigation !== "full-workspace-back-navigation-v1"
|| descriptor.telemetryPollInterval !== "three-seconds"
|| descriptor.telemetryFreshness !== "fifteen-seconds-missing-stale-not-unhealthy"
|| descriptor.telemetryOntologyProjection !== "observation-observed-property-provenance-freshness-v1"
|| descriptor.telemetryAgent !== "telegraf-host-observer-v1"
|| descriptor.interactiveShell !== "disabled-pending-managed-session-boundary"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v9_host_telemetry_workspace_contract_mismatch");
await validateFaviconBundle(payload, "device_manager_v9");
} else if (descriptorPath.endsWith("release-v8.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v8"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v6-20260822-035"
|| descriptor.predecessor?.artifactSha256 !== "193faabe930e2b3f212f8eb45288e39f850ec714528b28881095be654baf9a80"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v2-20260822-038"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "e2d062b82b022dba662522b5d6e192026ac964d78950d903295ca3cbbc95ab28"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.commandTransport !== "typed-service-ping-v1"
|| descriptor.commandCatalog !== "allowlisted-adapter-typed-commands-only"
|| descriptor.credentialBoundary !== "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned"
|| descriptor.presentationPersistence !== "runner-managed-host-data-bind"
|| descriptor.presentationDataHostPath !== "/volume1/docker/nodedc-device-plane/data/device-manager"
|| descriptor.presentationDataContainerPath !== "/var/lib/nodedc-device-manager"
|| descriptor.presentationDataOwnership !== "uid-1000-gid-1000-mode-0750"
|| descriptor.presentationDataLifecycle !== "preserve-across-manager-recreate-and-source-rollback"
|| descriptor.presentationPath !== "/var/lib/nodedc-device-manager/device-manager-presentation.json"
|| descriptor.mediaRoot !== "/var/lib/nodedc-device-manager/media"
|| descriptor.defaultAccentHex !== "#f5f5f5"
|| descriptor.overviewLayout !== "mission-core-landing-stage-v1"
|| descriptor.faviconSet !== "nodedc-adaptive-v1"
|| descriptor.commandFormLayout !== "aligned-control-row-v1"
|| descriptor.secondaryEmptyTypography !== "help-text-sm-v1"
|| descriptor.infrastructureHostProjection !== "ontology-backed-host-runtime-v1"
|| descriptor.ontologyFoundation !== "ontology-core-device-foundation-20260822-001"
|| descriptor.ontologyCatalogHash !== "229c61c02a790906"
|| descriptor.assetBinding !== "temporal-device-asset-binding-v1"
|| descriptor.infrastructureRuntime !== "host-endpoint-deployment-service-instance-v1"
|| descriptor.healthEvidence !== "ttl-observation-missing-not-unhealthy-v1"
|| descriptor.interactiveShell !== "disabled-pending-managed-session-boundary"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v8_canonical_ontology_runtime_contract_mismatch");
await validateFaviconBundle(payload, "device_manager_v8");
} else if (descriptorPath.endsWith("release-v7.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v7"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v6-20260822-035"
|| descriptor.predecessor?.artifactSha256 !== "193faabe930e2b3f212f8eb45288e39f850ec714528b28881095be654baf9a80"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v2-20260822-036"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "8708cc4b59fa0cd5e9c6e6a7b2654ba01ea60271549167aca2631f94000d3da3"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.commandTransport !== "typed-service-ping-v1"
|| descriptor.commandCatalog !== "allowlisted-adapter-typed-commands-only"
|| descriptor.credentialBoundary !== "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned"
|| descriptor.presentationPersistence !== "runner-managed-host-data-bind"
|| descriptor.presentationDataHostPath !== "/volume1/docker/nodedc-device-plane/data/device-manager"
|| descriptor.presentationDataContainerPath !== "/var/lib/nodedc-device-manager"
|| descriptor.presentationDataOwnership !== "uid-1000-gid-1000-mode-0750"
|| descriptor.presentationDataLifecycle !== "preserve-across-manager-recreate-and-source-rollback"
|| descriptor.presentationPath !== "/var/lib/nodedc-device-manager/device-manager-presentation.json"
|| descriptor.mediaRoot !== "/var/lib/nodedc-device-manager/media"
|| descriptor.defaultAccentHex !== "#f5f5f5"
|| descriptor.overviewLayout !== "mission-core-landing-stage-v1"
|| descriptor.faviconSet !== "nodedc-adaptive-v1"
|| descriptor.commandFormLayout !== "aligned-control-row-v1"
|| descriptor.secondaryEmptyTypography !== "help-text-sm-v1"
|| descriptor.infrastructureHostProjection !== "edge-registration-live-channel-v1"
|| descriptor.ontologyStatus !== "generic-host-domain-candidate-not-canonical"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v7_infrastructure_host_projection_contract_mismatch");
await validateFaviconBundle(payload, "device_manager_v7");
} else if (descriptorPath.endsWith("release-v6.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v6"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v5-20260822-034"
|| descriptor.predecessor?.artifactSha256 !== "acc1d2ae2cda66861054826928c25d01a2428e688cc8132a9c381831bf29ab5a"
|| descriptor.commandTransport !== "typed-service-ping-v1"
|| descriptor.commandCatalog !== "allowlisted-adapter-typed-commands-only"
|| descriptor.credentialBoundary !== "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v2-20260821-030"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.presentationPersistence !== "runner-managed-host-data-bind"
|| descriptor.presentationDataHostPath !== "/volume1/docker/nodedc-device-plane/data/device-manager"
|| descriptor.presentationDataContainerPath !== "/var/lib/nodedc-device-manager"
|| descriptor.presentationDataOwnership !== "uid-1000-gid-1000-mode-0750"
|| descriptor.presentationDataLifecycle !== "preserve-across-manager-recreate-and-source-rollback"
|| descriptor.presentationPath !== "/var/lib/nodedc-device-manager/device-manager-presentation.json"
|| descriptor.mediaRoot !== "/var/lib/nodedc-device-manager/media"
|| descriptor.defaultAccentHex !== "#f5f5f5"
|| descriptor.overviewLayout !== "mission-core-landing-stage-v1"
|| descriptor.faviconSet !== "nodedc-adaptive-v1"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v6_favicon_contract_mismatch");
await validateFaviconBundle(payload, "device_manager_v6");
} else if (descriptorPath.endsWith("release-v5.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v5"
|| descriptor.predecessor?.kind !== "release"
|| descriptor.predecessor?.patchId !== "device-manager-release-v4-20260822-033"
|| descriptor.predecessor?.artifactSha256 !== "52ba322042f1e4f595bbfea99f8bb35630b15984e0da648dc55348bc9e5b2066"
|| descriptor.commandTransport !== "typed-service-ping-v1"
|| descriptor.commandCatalog !== "allowlisted-adapter-typed-commands-only"
|| descriptor.credentialBoundary !== "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v2-20260821-030"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.presentationPersistence !== "runner-managed-host-data-bind"
|| descriptor.presentationDataHostPath !== "/volume1/docker/nodedc-device-plane/data/device-manager"
|| descriptor.presentationDataContainerPath !== "/var/lib/nodedc-device-manager"
|| descriptor.presentationDataOwnership !== "uid-1000-gid-1000-mode-0750"
|| descriptor.presentationDataLifecycle !== "preserve-across-manager-recreate-and-source-rollback"
|| descriptor.presentationPath !== "/var/lib/nodedc-device-manager/device-manager-presentation.json"
|| descriptor.mediaRoot !== "/var/lib/nodedc-device-manager/media"
|| descriptor.defaultAccentHex !== "#f5f5f5"
|| descriptor.overviewLayout !== "mission-core-landing-stage-v1"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v5_overview_layout_contract_mismatch");
} else if (descriptorPath.endsWith("release-v4.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v4"
|| descriptor.commandTransport !== "typed-service-ping-v1"
|| descriptor.commandCatalog !== "allowlisted-adapter-typed-commands-only"
|| descriptor.credentialBoundary !== "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v2-20260821-030"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.presentationPersistence !== "runner-managed-host-data-bind"
|| descriptor.presentationDataHostPath !== "/volume1/docker/nodedc-device-plane/data/device-manager"
|| descriptor.presentationDataContainerPath !== "/var/lib/nodedc-device-manager"
|| descriptor.presentationDataOwnership !== "uid-1000-gid-1000-mode-0750"
|| descriptor.presentationDataLifecycle !== "preserve-across-manager-recreate-and-source-rollback"
|| descriptor.presentationPath !== "/var/lib/nodedc-device-manager/device-manager-presentation.json"
|| descriptor.mediaRoot !== "/var/lib/nodedc-device-manager/media"
|| descriptor.defaultAccentHex !== "#f5f5f5"
|| descriptor.rollback !== "restore-preapply-snapshot-preserve-manager-data"
|| descriptor.gelios !== "untouched-legacy-only"
) throw new Error("device_manager_v4_persistence_contract_mismatch");
} else if (descriptorPath.endsWith("release-v3.json")) {
if (
descriptor.schemaVersion !== "nodedc.device-plane.device-manager-release.v3"
|| descriptor.commandTransport !== "typed-service-ping-v1"
|| descriptor.commandCatalog !== "allowlisted-adapter-typed-commands-only"
|| descriptor.credentialBoundary !== "transient-core-memory-then-single-pinned-mtls-command-envelope-to-edge-never-persisted-never-logged-never-returned"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v2-20260813-028"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "816ef07fd81923328c3ff54d833dcc49f873aef13256259ae4f66061e7453635"
|| descriptor.controlCorePredecessor?.patchId !== "device-control-core-release-v2-20260821-030"
|| descriptor.controlCorePredecessor?.artifactSha256 !== "8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
|| descriptor.edgeChannelPredecessor?.patchId !== "device-edge-core-channel-upgrade-v4-20260812-023"
|| descriptor.edgeChannelPredecessor?.artifactSha256 !== "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"
|| descriptor.edgeChannel !== "preserve-active-v4-core-initiated-pinned-mtls"
@@ -173,13 +503,48 @@ try {
artifact: target,
sha256,
entries,
services: isV3 ? ["device-manager"] : ["device-control-core", "device-manager"],
services: isManagerOnly ? ["device-manager"] : ["device-control-core", "device-manager"],
preserved: ["device-postgres", "device-gateway", "device-backhaul-target", "Gelios"],
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
async function validateFaviconBundle(payloadRoot, errorPrefix) {
const faviconHashes = {
"favicon.ico": "f8933114a85646335ea5c94944f56d3cd8c48a6032016719f7905ff244ec0aa2",
"favicon/favicon.ico": "f8933114a85646335ea5c94944f56d3cd8c48a6032016719f7905ff244ec0aa2",
"favicon/icon-adaptive.svg": "481984e83997d786bb0a72ad1ee80037db13aef3a0792ab3109df95c2199b38e",
"favicon/apple-touch-icon.png": "afdccc28152a566e264e533ca218362f05d5bcec936c647f9a54f414c0bd4763",
"favicon/icon-192.png": "5b10a24feb4754f15c69761cef42f91a01f885d04095156b1a12e254875fdd4d",
"favicon/icon-512.png": "f98bac3dba59b7eefbe89f8bb8abc25567226a54ab7ed3b6b1a4caffbdd9ee15",
"favicon/manifest.webmanifest.json": "2a8ecdc6e6c64833f812ae02bbc0c7bd9b435e0cfa75cc21d6edf054d41275fc",
};
for (const [relativePath, expectedSha256] of Object.entries(faviconHashes)) {
const content = await readFile(join(payloadRoot, "services/device-manager/dist", relativePath));
const actualSha256 = createHash("sha256").update(content).digest("hex");
if (actualSha256 !== expectedSha256) {
throw new Error(`${errorPrefix}_favicon_hash_mismatch:${relativePath}`);
}
}
const indexHtml = await readFile(
join(payloadRoot, "services/device-manager/dist/index.html"),
"utf8",
);
for (const requiredLink of [
'href="/favicon/icon-adaptive.svg"',
'href="/favicon/favicon.ico"',
'href="/favicon/apple-touch-icon.png"',
'href="/favicon/icon-192.png"',
'href="/favicon/icon-512.png"',
'href="/favicon/manifest.webmanifest.json"',
]) {
if (!indexHtml.includes(requiredLink)) {
throw new Error(`${errorPrefix}_favicon_link_missing:${requiredLink}`);
}
}
}
async function copySafe(source, destination, sourceBoundary) {
const sourceStat = await lstat(source);
if (sourceStat.isSymbolicLink()) throw new Error(`source_symlink_rejected:${relative(sourceBoundary, source)}`);
@@ -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))));
});
+318 -11
View File
@@ -46,6 +46,8 @@ RELAY_USER = "nodedc-relay"
RELAY_GROUP = "nodedc-relay"
CHANNEL_USER = "nodedc-channel"
CHANNEL_GROUP = "nodedc-channel"
TELEMETRY_USER = "nodedc-telemetry"
TELEMETRY_GROUP = "nodedc-telemetry"
TAILSCALE_REQUIRED_TAG = "tag:device-edge-vps"
MANAGEMENT_KEY_FINGERPRINT = (
"SHA256:DYYy1E3DaxIQGC0jnsW6SP7gXdBHUy3A1zn4pvgVUEw"
@@ -67,10 +69,19 @@ TAILSCALE_ARCHIVE_SHA256 = (
NODE_BIN_SHA256 = "3517c2df0b2f8cd7f422b4b8450ef81c6889f08eb03e281d6de9079b15e6a327"
TAILSCALE_BIN_SHA256 = "58b0fa0907677ea6afe0d3022cc3e99b1a03f39a7ed60144843ed38252e00c80"
TAILSCALED_BIN_SHA256 = "5f17b092bac92326325f6c4ffd9991fad3c073975abe412d02ee68721a500394"
TELEGRAF_VERSION = "1.38.4"
TELEGRAF_ARCHIVE = "telegraf-1.38.4_linux_amd64.tar.gz"
TELEGRAF_ARCHIVE_SHA256 = (
"81857e9745ebf26e058b6fdc27b9b2c210fd1fe61e57d7fad3d4bb9131f60041"
)
TELEGRAF_BIN_SHA256 = (
"0643b582546eb9c70d99a9646b3e49e25ccdea4f78ab06fd9096ed71dba1babb"
)
NODE_BIN = LIVE_ROOT / "runtime/node/bin/node"
TAILSCALE_BIN = LIVE_ROOT / "runtime/tailscale/tailscale"
TAILSCALED_BIN = LIVE_ROOT / "runtime/tailscale/tailscaled"
TELEGRAF_BIN = LIVE_ROOT / "runtime/telegraf/usr/bin/telegraf"
TAILSCALE_SOCKET = Path("/run/nodedc-b2-vps/tailscaled.sock")
TAILSCALE_STATE = Path("/var/lib/nodedc-b2-vps/tailscale/tailscaled.state")
TRUST_ROOT = Path("/var/lib/nodedc-b2-vps/trust")
@@ -102,6 +113,10 @@ CHANNEL_CORE_CERTIFICATE = CHANNEL_TRUST_ROOT / "core-certificate.pem"
CHANNEL_RUNTIME_CONFIG = CHANNEL_TRUST_ROOT / "runtime.json"
CHANNEL_HEALTH_PORT = 18222
CHANNEL_PUBLIC_PORT = 443
HOST_TELEMETRY_PORT = 18223
HOST_TELEMETRY_UNIT = Path(
"/etc/systemd/system/nodedc-host-telemetry-agent.service"
)
CORE_CHANNEL_ACCEPTED_PATCH = "device-edge-vps-core-channel-20260812-010"
CORE_CHANNEL_ACCEPTED_SHA256 = (
"c8ef3c4bb45850cad32e881eba081bc4c891c2886e5500d02cb94616d82353f3"
@@ -116,6 +131,12 @@ TRACKER_INGRESS_ACCEPTED_PATCH = "device-edge-vps-tracker-ingress-20260812-012"
TRACKER_INGRESS_ACCEPTED_SHA256 = (
"290acef118839c6b0c31aac864c47da1832a289537366af9322d4624a1dd81ec"
)
COMMAND_TRANSPORT_ACCEPTED_PATCH = (
"device-edge-vps-command-transport-20260812-013"
)
COMMAND_TRANSPORT_ACCEPTED_SHA256 = (
"c7486ec879681ddd706f229b628c8556ca8c9ccc4f152a85debb409c302759ef"
)
FOUNDATION_ENTRIES = (
"vps/config/00-nodedc-b2-vps.conf",
@@ -181,6 +202,21 @@ COMMAND_TRANSPORT_ENTRIES = (
"vps/edge-process/device-edge-runtime.mjs",
"deployment/device-edge-vps-command-transport-v1.json",
)
HOST_TELEMETRY_ENTRIES = (
"packages/device-edge-channel-contract/package.json",
"packages/device-edge-channel-contract/src",
"packages/infrastructure-telemetry-contract/package.json",
"packages/infrastructure-telemetry-contract/src",
"services/device-edge-channel/package.json",
"services/device-edge-channel/src",
"vps/edge-process/device-edge-runtime.mjs",
"vps/edge-process/host-telemetry-runtime.mjs",
"vps/config/nodedc-host-telemetry-telegraf.conf",
"vps/systemd/nodedc-device-edge-runtime.service",
"vps/systemd/nodedc-host-telemetry-agent.service",
"deployment/device-edge-vps-host-telemetry-v1.json",
f"vendor/{TELEGRAF_ARCHIVE}",
)
PHASE_ENTRIES = {
"foundation": FOUNDATION_ENTRIES,
@@ -191,6 +227,7 @@ PHASE_ENTRIES = {
"tailscale-retirement": TAILSCALE_RETIREMENT_ENTRIES,
"tracker-ingress": TRACKER_INGRESS_ENTRIES,
"command-transport": COMMAND_TRANSPORT_ENTRIES,
"host-telemetry": HOST_TELEMETRY_ENTRIES,
}
SUPERSEDED_TRANSPORT_PHASES = frozenset({"backhaul", "relay"})
@@ -312,6 +349,35 @@ PHASE_FILE_SHA256 = {
"deployment/device-edge-vps-command-transport-v1.json":
"971166143fe954b9c5043cce9a464d17efbc87933da1405b2517a4693a7bed09",
},
"host-telemetry": {
"deployment/device-edge-vps-host-telemetry-v1.json":
"c4dc60e68549c3c3844779091d5b767a2cb4152cd923433b488cb56e37717391",
"packages/device-edge-channel-contract/package.json":
"57d5349b5dcef2cacd4f3e4fad010359a65d59f5f903eff07d89f67c497f97c0",
"packages/device-edge-channel-contract/src/index.mjs":
"58a53836495dc891de191c6022cf7661a2198deb9fff7055a5cc23a36ddf49d2",
"packages/infrastructure-telemetry-contract/package.json":
"5ef70204acc9a2bee68be959347487dc2e8fb7fbe8bd88731033e7ab204acf34",
"packages/infrastructure-telemetry-contract/src/index.mjs":
"6d4b60b79e131380fcec403cf8842a3612614b5540c7052020e84d4fc8a9360f",
"services/device-edge-channel/package.json":
"bdf502be43b62bdd6db05b022a532d93ba954277ac5143d6058d2f27f6a2e9d2",
"services/device-edge-channel/src/runtime.mjs":
"4c0e874b2f1161910d3abde9a07f4a7744ffeece325303cc9985521a0eafb47b",
"services/device-edge-channel/src/server.mjs":
"a82057218bb368ab926404f90a19cc17c0359b57dc890f38a1324ab8c497c17b",
"vps/config/nodedc-host-telemetry-telegraf.conf":
"596e386d1e37b8178ccc660760567f5a8914ae7bef43b3603b31846c73154972",
"vps/edge-process/device-edge-runtime.mjs":
"0fc32e8c71a028777b0945ea6a0dbab22b0244caab1d7f616702c8a4a143c597",
"vps/edge-process/host-telemetry-runtime.mjs":
"ce1c6f368199d6c91e8a7496e0e8388e3c390018f2695107bc2877eced5e566d",
"vps/systemd/nodedc-device-edge-runtime.service":
"88cd8d34df254f8daa1d82f6bcd175fb061376b65491ee6ac90b296fce675dfb",
"vps/systemd/nodedc-host-telemetry-agent.service":
"0d3aa1644af528ebd4cca7a95fb1bb89fe14544a64fb9729fd469296c4343506",
f"vendor/{TELEGRAF_ARCHIVE}": TELEGRAF_ARCHIVE_SHA256,
},
}
# Exact immutable baselines from terminally accepted predecessor artifacts.
@@ -472,7 +538,11 @@ def validate_payload(payload: Path, phase: str):
descriptor.get("component") != COMPONENT
or descriptor.get("runtimeHost") != RUNTIME_HOST
or descriptor.get("commandTransport")
!= ("typed-service-ping-v1" if phase == "command-transport" else "disabled")
!= (
"typed-service-ping-v1"
if phase in {"command-transport", "host-telemetry"}
else "disabled"
)
or not str(descriptor.get("gelios", "")).startswith("untouched")
or not descriptor.get("rollback")
):
@@ -480,6 +550,41 @@ def validate_payload(payload: Path, phase: str):
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):
artifact = artifact.resolve(strict=True)
if artifact.parent != INBOX_ROOT.resolve(strict=True):
@@ -500,7 +605,7 @@ def load_artifact(artifact: Path, extraction_root: Path):
die("artifact top-level contract is incomplete")
if any(name.split("/", 1)[0] not in required for name in seen):
die("artifact contains an unexpected top-level member")
archive.extractall(extraction_root, filter="data")
extract_validated_files(archive, extraction_root)
manifest = parse_manifest(
(extraction_root / "manifest.env").read_text(encoding="utf-8")
@@ -737,6 +842,25 @@ def current_phase_preflight(phase: str):
if (LIVE_ROOT / COMMAND_TRANSPORT_ENTRIES[-1]).exists():
die("VPS command transport target path already exists")
return {"predecessor": "accepted-tracker-ingress-012"}
if phase == "host-telemetry":
command_record = applied_phase_record("command-transport")
if (
command_record.get("patch") != COMMAND_TRANSPORT_ACCEPTED_PATCH
or command_record.get("sha256")
!= COMMAND_TRANSPORT_ACCEPTED_SHA256
):
die("VPS host telemetry command transport predecessor mismatch")
source_file_state("command-transport")
validate_command_transport_runtime()
if (
HOST_TELEMETRY_UNIT.exists()
or TELEGRAF_BIN.exists()
or user_exists(TELEMETRY_USER)
or (LIVE_ROOT / HOST_TELEMETRY_ENTRIES[-2]).exists()
):
die("VPS host telemetry target boundary already exists")
assert_port_closed(HOST_TELEMETRY_PORT)
return {"predecessor": "accepted-command-transport-013"}
validate_foundation_runtime(
require_running_tailnet=phase in {"backhaul", "relay"},
expected_key_user=BACKHAUL_USER if phase == "relay" else SERVICE_USER,
@@ -848,6 +972,12 @@ def backup_targets_for_phase(phase: str):
return common + [CHANNEL_UNIT, NFTABLES_CONFIG]
if phase == "command-transport":
return common + [CHANNEL_UNIT, NFTABLES_CONFIG]
if phase == "host-telemetry":
return common + [
CHANNEL_UNIT,
HOST_TELEMETRY_UNIT,
TELEGRAF_BIN.parent,
]
return common + [RELAY_UNIT, NFTABLES_CONFIG]
@@ -887,7 +1017,13 @@ def create_backup(patch_id: str, phase: str):
"serviceUserExisted": user_exists(),
"serviceUsersExisted": {
name: user_exists(name)
for name in (SERVICE_USER, BACKHAUL_USER, RELAY_USER, CHANNEL_USER)
for name in (
SERVICE_USER,
BACKHAUL_USER,
RELAY_USER,
CHANNEL_USER,
TELEMETRY_USER,
)
},
"services": {
name: {
@@ -902,6 +1038,7 @@ def create_backup(patch_id: str, phase: str):
"nodedc-b2-backhaul.service",
"nodedc-b2-relay.service",
"nodedc-device-edge-channel.service",
"nodedc-host-telemetry-agent.service",
)
},
}
@@ -1002,10 +1139,17 @@ def ensure_service_user(name=SERVICE_USER, home_dir="/var/lib/nodedc-b2-vps"):
def extract_vendor_binary(archive: Path, member_name: str, target: Path, mode=0o755):
with tarfile.open(archive, "r:*") as package:
try:
member = package.getmember(member_name)
except KeyError:
accepted_names = {member_name, f"./{member_name}"}
matches = [
candidate
for candidate in package.getmembers()
if candidate.name in accepted_names
]
if not matches:
die(f"vendor binary member missing: {member_name}")
if len(matches) != 1:
die(f"vendor binary member ambiguous: {member_name}")
member = matches[0]
if not member.isfile() or member.issym() or member.islnk():
die(f"vendor binary member unsafe: {member_name}")
source = package.extractfile(member)
@@ -1336,6 +1480,32 @@ def apply_command_transport(_payload: Path):
validate_command_transport_runtime()
def apply_host_telemetry(_payload: Path):
ensure_service_user(
TELEMETRY_USER,
"/var/lib/nodedc-b2-vps/telemetry",
)
extract_vendor_binary(
LIVE_ROOT / f"vendor/{TELEGRAF_ARCHIVE}",
f"telegraf-{TELEGRAF_VERSION}/usr/bin/telegraf",
TELEGRAF_BIN,
)
install_file(
LIVE_ROOT / "vps/systemd/nodedc-device-edge-runtime.service",
CHANNEL_UNIT,
0o644,
)
install_file(
LIVE_ROOT / "vps/systemd/nodedc-host-telemetry-agent.service",
HOST_TELEMETRY_UNIT,
0o644,
)
systemctl("daemon-reload")
systemctl("restart", "nodedc-device-edge-channel.service")
systemctl("enable", "--now", "nodedc-host-telemetry-agent.service")
validate_host_telemetry_runtime()
def sshd_effective():
return run(["/usr/sbin/sshd", "-T"]).stdout.lower()
@@ -1777,6 +1947,126 @@ def validate_command_transport_runtime():
return health
def validate_host_telemetry_runtime():
source_file_state("foundation")
source_file_state("tailscale-retirement")
source_file_state("host-telemetry")
command_record = applied_phase_record("command-transport")
if (
command_record.get("patch") != COMMAND_TRANSPORT_ACCEPTED_PATCH
or command_record.get("sha256") != COMMAND_TRANSPORT_ACCEPTED_SHA256
):
die("host telemetry command transport identity mismatch")
binary = assert_regular_nonsymlink(
TELEGRAF_BIN,
"VPS Telegraf runtime",
)
if (
binary.st_uid != 0
or binary.st_gid != 0
or (binary.st_mode & 0o777) != 0o755
or sha256_file(TELEGRAF_BIN) != TELEGRAF_BIN_SHA256
):
die("VPS Telegraf runtime identity mismatch")
version = run([str(TELEGRAF_BIN), "version"]).stdout.strip()
if not version.startswith(f"Telegraf {TELEGRAF_VERSION}"):
die("VPS Telegraf version mismatch")
telemetry_account = pwd.getpwnam(TELEMETRY_USER)
channel_account = pwd.getpwnam(CHANNEL_USER)
if (
telemetry_account.pw_shell != "/usr/sbin/nologin"
or telemetry_account.pw_uid == channel_account.pw_uid
):
die("VPS telemetry runtime identity is not isolated")
if not service_active("nodedc-device-edge-channel.service"):
die("VPS Device Edge runtime is not active")
if not service_active("nodedc-host-telemetry-agent.service"):
die("VPS host telemetry agent is not active")
if (
systemctl(
"is-enabled",
"nodedc-host-telemetry-agent.service",
check=False,
).returncode != 0
):
die("VPS host telemetry agent is not enabled")
health = None
last_error = "no host telemetry acceptance"
for _attempt in range(60):
candidate = core_channel_health(require_accepted=True)
host_telemetry = candidate.get("hostTelemetry") or {}
if (
host_telemetry.get("listening") is True
and host_telemetry.get("host") == "127.0.0.1"
and host_telemetry.get("port") == HOST_TELEMETRY_PORT
and host_telemetry.get("profile") == "linux-host-telegraf-v1"
and int(host_telemetry.get("accepted") or 0) >= 1
and host_telemetry.get("lastErrorCode") is None
):
health = candidate
break
last_error = json.dumps(host_telemetry, sort_keys=True)
time.sleep(2)
if health is None:
die(f"VPS host telemetry acceptance timeout: {last_error}")
expected = {
"ok": True,
"service": "nodedc-device-edge-runtime",
"channel": "accepted",
"trackerIngress": "telemetry-ingest",
"commandTransport": "typed-service-ping-v1",
}
for key, value in expected.items():
if health.get(key) != value:
die(f"VPS host telemetry preserved contract mismatch: {key}")
if not port_is_open("127.0.0.1", HOST_TELEMETRY_PORT, timeout=5):
die("VPS host telemetry collector is unavailable")
if port_is_open(PUBLIC_IPV4, HOST_TELEMETRY_PORT, timeout=2):
die("VPS host telemetry collector became public")
for port in (1883, 8883):
if port_is_open("127.0.0.1", port) or port_is_open(PUBLIC_IPV4, port):
die(f"VPS forbidden MQTT listener became available: {port}")
for port in (22, CHANNEL_PUBLIC_PORT, 9921):
if not port_is_open(PUBLIC_IPV4, port, timeout=5):
die(f"VPS host telemetry preserved listener unavailable: {port}")
unit = run([
"/usr/bin/systemctl",
"show",
"nodedc-host-telemetry-agent.service",
"--property=User,Group,NoNewPrivileges,CapabilityBoundingSet,MemoryMax,MemorySwapMax,TasksMax,LimitNOFILE",
]).stdout
for required in (
"User=nodedc-telemetry",
"Group=nodedc-telemetry",
"NoNewPrivileges=yes",
"CapabilityBoundingSet=",
"MemoryMax=100663296",
"MemorySwapMax=0",
"TasksMax=64",
"LimitNOFILE=512",
):
if required not in unit:
die(f"VPS host telemetry resource boundary mismatch: {required}")
nft = run([
"/usr/sbin/nft",
"list",
"table",
"inet",
"nodedc_b2_vps",
]).stdout
for required in (
"policy drop",
"tcp dport 22",
"tcp dport 443",
"tcp dport 9921",
):
if required not in nft:
die(f"VPS host telemetry firewall contract mismatch: {required}")
if f"tcp dport {HOST_TELEMETRY_PORT}" in nft:
die("VPS host telemetry firewall exposed the collector")
return health
def validate_relay_runtime():
validate_backhaul_runtime()
source_file_state("relay")
@@ -1835,6 +2125,7 @@ def restore_service_enablement(metadata):
def rollback(backup: Path, phase: str):
for service in (
"nodedc-host-telemetry-agent.service",
"nodedc-b2-relay.service",
"nodedc-b2-backhaul.service",
"nodedc-device-edge-channel.service",
@@ -1866,6 +2157,9 @@ def rollback(backup: Path, phase: str):
if phase == "core-channel":
if not users_before.get(CHANNEL_USER, False) and user_exists(CHANNEL_USER):
run(["/usr/sbin/userdel", CHANNEL_USER], check=False)
if phase == "host-telemetry":
if not users_before.get(TELEMETRY_USER, False) and user_exists(TELEMETRY_USER):
run(["/usr/sbin/userdel", TELEMETRY_USER], check=False)
if phase == "foundation" and not metadata.get("serviceUserExisted"):
runtime_state_root = Path("/var/lib/nodedc-b2-vps")
if LIVE_ROOT.exists() and not LIVE_ROOT.is_symlink():
@@ -1955,7 +2249,7 @@ def plan_artifact(artifact_argument: str):
print("runtime_composition=single-non-root-process:core-channel+universal-gateway")
print("tailscale=preserved:absent")
print("services=recreate:nodedc-device-edge-channel")
else:
elif phase == "command-transport":
print("public_core_channel=preserved:155.212.211.15:443/tcp:tls13-mtls-h2")
print(f"health=127.0.0.1:{CHANNEL_HEALTH_PORT}:combined-edge-runtime")
print("public_b2_ingress=155.212.211.15:9921/tcp:bidirectional-session")
@@ -1964,16 +2258,27 @@ def plan_artifact(artifact_argument: str):
print("runtime_composition=single-non-root-process:core-channel+universal-gateway")
print("tailscale=preserved:absent")
print("services=recreate:nodedc-device-edge-channel")
else:
print("public_core_channel=preserved:155.212.211.15:443/tcp:tls13-mtls-h2")
print(f"health=127.0.0.1:{CHANNEL_HEALTH_PORT}:combined-edge-runtime")
print(f"host_telemetry_collector=127.0.0.1:{HOST_TELEMETRY_PORT}:loopback-only")
print(f"host_telemetry_agent=telegraf:{TELEGRAF_VERSION}:sha256:{TELEGRAF_ARCHIVE_SHA256}")
print("host_telemetry_interval=2s")
print("host_telemetry_transport=existing-pinned-mtls-core-channel")
print("host_telemetry_ontology=observation.observation=>infrastructure.host")
print("mqtt=disabled")
print("public_port_set=preserved:22,443,9921")
print("services=recreate:nodedc-device-edge-channel+create:nodedc-host-telemetry-agent")
print(
"command_transport=typed-service-ping-v1:allowlisted-adapter-only"
if phase == "command-transport"
if phase in {"command-transport", "host-telemetry"}
else "command_transport=disabled"
)
if phase == "command-transport":
if phase in {"command-transport", "host-telemetry"}:
print("command_catalog=allowlisted-adapter-typed-commands-only")
print(
"gelios=untouched-legacy-only"
if phase == "command-transport"
if phase in {"command-transport", "host-telemetry"}
else "gelios=untouched"
)
print("dns=unchanged")
@@ -2013,8 +2318,10 @@ def apply_artifact(artifact_argument: str):
apply_tailscale_retirement(loaded["payload"])
elif loaded["phase"] == "tracker-ingress":
apply_tracker_ingress(loaded["payload"])
else:
elif loaded["phase"] == "command-transport":
apply_command_transport(loaded["payload"])
else:
apply_host_telemetry(loaded["payload"])
archived = archive_artifact(loaded["artifact"], APPLIED_ROOT)
record = {
+36 -1
View File
@@ -228,6 +228,41 @@ def safe_tar_member(member: tarfile.TarInfo):
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):
artifact = artifact.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")
if any(name.split("/", 1)[0] not in required for name in seen):
die("artifact contains an unexpected top-level member")
archive.extractall(extraction_root, filter="data")
extract_validated_files(archive, extraction_root)
manifest = parse_manifest(
(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,159 @@
#!/usr/bin/env python3
import hashlib
import importlib.machinery
import importlib.util
import inspect
import json
import os
import subprocess
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest import mock
SCRIPT_DIR = Path(__file__).resolve().parent
RUNNER_PATH = Path(
os.environ.get(
"NODEDC_DEPLOY_RUNNER",
SCRIPT_DIR.parents[2] / "platform/infra/deploy-runner/nodedc-deploy",
)
)
BUILDER = SCRIPT_DIR / "build-device-control-core-incident-audit-artifact.mjs"
def load_runner():
loader = importlib.machinery.SourceFileLoader(
"nodedc_control_core_incident_audit_runner_under_test",
str(RUNNER_PATH),
)
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNER = load_runner()
class DeviceControlCoreIncidentAuditArtifactTest(unittest.TestCase):
def build(self, artifact_dir, patch_id):
environment = os.environ.copy()
environment["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(artifact_dir)
result = subprocess.run(
["node", str(BUILDER), patch_id],
check=True,
capture_output=True,
text=True,
env=environment,
)
return json.loads(result.stdout)
def test_artifact_is_deterministic_plan_only_audit(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-control-core-incident-audit-artifact-",
) as directory:
artifact_dir = Path(directory)
patch_id = "device-control-core-incident-audit-unit-043"
first = self.build(artifact_dir, patch_id)
first_bytes = Path(first["artifact"]).read_bytes()
second = self.build(artifact_dir, patch_id)
second_bytes = Path(second["artifact"]).read_bytes()
self.assertEqual(first_bytes, second_bytes)
self.assertEqual(
first["sha256"],
hashlib.sha256(first_bytes).hexdigest(),
)
self.assertEqual(first["build"], [])
self.assertEqual(first["services"], [])
self.assertEqual(first["allowedOperation"], "canonical-plan-only")
self.assertEqual(first["runtimeMutation"], "none")
with tarfile.open(first["artifact"], "r:gz") as archive:
descriptor = json.loads(
archive.extractfile(
"payload/"
+ RUNNER.DEVICE_PLANE_CONTROL_CORE_INCIDENT_AUDIT_REL
).read().decode("utf-8")
)
self.assertEqual(
descriptor,
RUNNER.expected_device_plane_control_core_incident_audit_descriptor(),
)
entries = RUNNER.DEVICE_PLANE_CONTROL_CORE_INCIDENT_AUDIT_ENTRIES
self.assertEqual(RUNNER.component_services("device-plane", entries), ())
self.assertEqual(RUNNER.component_builds("device-plane", entries), ())
def test_descriptor_pins_both_rollback_failures(self):
descriptor = (
RUNNER.expected_device_plane_control_core_incident_audit_descriptor()
)
self.assertFalse(descriptor["applyAllowed"])
self.assertEqual(descriptor["runtimeMutation"], "none")
self.assertEqual(
[item["artifactSha256"] for item in descriptor["failedAttempts"]],
[
"08448a56cdf391076f92c5242e368fd0033b420167874645eebfa1f22184ee92",
"54ab243439bce724fa0a0872b76cc32e0052ea5127153214d92872f02ae831cf",
],
)
def test_runtime_audit_reads_logs_and_database_without_mutation(self):
log_result = mock.Mock(
returncode=0,
stdout="Error: device_database_migration_blocked\n",
stderr="at PostgresDeviceRepository.migrate (postgres-repository.mjs:110)\n",
)
database_result = mock.Mock(
returncode=0,
stdout=(
"activity\t42,active,Lock,relation,schema-ddl,181\n"
"schema\thost-telemetry-table-present\n"
),
stderr="",
)
with mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
side_effect=[("c" * 64,), ("p" * 64,)],
), mock.patch.object(
RUNNER.subprocess,
"run",
side_effect=[log_result, database_result],
) as run:
evidence = RUNNER.collect_device_plane_control_core_incident_audit()
self.assertEqual(evidence["coreContainerId"], "c" * 64)
self.assertIn(
"Error: device_database_migration_blocked",
evidence["logErrors"],
)
self.assertEqual(
evidence["database"],
[
"activity\t42,active,Lock,relation,schema-ddl,181",
"schema\thost-telemetry-table-present",
],
)
self.assertEqual(run.call_count, 2)
log_command = run.call_args_list[0].args[0]
self.assertEqual(log_command[1:4], ["logs", "--tail", "240"])
database_command = run.call_args_list[1].args[0]
self.assertEqual(database_command[1], "exec")
query = database_command[database_command.index("-c") + 1]
self.assertTrue(query.lstrip().startswith("select 'schema'"))
self.assertNotIn(";", query)
def test_apply_path_rejects_plan_only_audit_before_state_mutation(self):
source = inspect.getsource(RUNNER.apply_artifact)
self.assertIn("canonical-plan-only", source)
self.assertIn("apply is forbidden", source)
self.assertLess(
source.index("canonical-plan-only"),
source.index("state_has_sha"),
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,333 @@
#!/usr/bin/env python3
import contextlib
import hashlib
import importlib.machinery
import importlib.util
import inspect
import io
import json
import os
import re
import subprocess
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest import mock
SCRIPT_DIR = Path(__file__).resolve().parent
RUNNER_PATH = Path(
os.environ.get(
"NODEDC_DEPLOY_RUNNER",
SCRIPT_DIR.parents[2] / "platform/infra/deploy-runner/nodedc-deploy",
)
)
BUILDER = (
SCRIPT_DIR
/ "build-device-control-core-migration-replay-audit-artifact.mjs"
)
def load_runner():
loader = importlib.machinery.SourceFileLoader(
"nodedc_control_core_migration_replay_audit_runner_under_test",
str(RUNNER_PATH),
)
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNER = load_runner()
class DeviceControlCoreMigrationReplayAuditArtifactTest(unittest.TestCase):
def build(self, artifact_dir, patch_id):
environment = os.environ.copy()
environment["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(artifact_dir)
result = subprocess.run(
["node", str(BUILDER), patch_id],
check=True,
capture_output=True,
text=True,
env=environment,
)
return json.loads(result.stdout)
def test_artifact_is_deterministic_plan_only_audit(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-control-core-migration-replay-audit-",
) as directory:
artifact_dir = Path(directory)
patch_id = "device-control-core-migration-replay-audit-unit-045"
first = self.build(artifact_dir, patch_id)
first_bytes = Path(first["artifact"]).read_bytes()
second = self.build(artifact_dir, patch_id)
second_bytes = Path(second["artifact"]).read_bytes()
self.assertEqual(first_bytes, second_bytes)
self.assertEqual(
first["sha256"],
hashlib.sha256(first_bytes).hexdigest(),
)
self.assertEqual(first["build"], [])
self.assertEqual(first["services"], [])
self.assertEqual(first["allowedOperation"], "canonical-plan-only")
self.assertEqual(first["runtimeMutation"], "none")
with tarfile.open(first["artifact"], "r:gz") as archive:
descriptor = json.loads(
archive.extractfile(
"payload/"
+ RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_AUDIT_REL
).read().decode("utf-8")
)
self.assertEqual(
descriptor,
RUNNER.expected_device_plane_control_core_migration_replay_audit_descriptor(),
)
entries = RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_AUDIT_ENTRIES
self.assertEqual(RUNNER.component_services("device-plane", entries), ())
self.assertEqual(RUNNER.component_builds("device-plane", entries), ())
def test_database_audit_returns_all_mismatches_without_mutation(self):
database_result = mock.Mock(
returncode=0,
stdout=(
"2\t0\tfalse\tfalse\tfalse\t"
+ json.dumps(
sorted(
RUNNER.DEVICE_PLANE_CONTROL_CORE_REPLAY_011_COMMAND_KINDS
),
separators=(",", ":"),
)
+ "\n"
),
stderr="",
)
with mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("p" * 64,),
), mock.patch.object(
RUNNER.subprocess,
"run",
return_value=database_result,
) as run:
evidence = (
RUNNER.collect_device_plane_control_core_migration_replay_database_evidence(
enforce_recovery_invariants=False,
)
)
self.assertEqual(evidence["invalidCommandKindCount"], 2)
self.assertEqual(evidence["triggeringReceiptCount"], 0)
self.assertFalse(evidence["constraintValidated"])
self.assertFalse(evidence["constraintCoversFinalKinds"])
self.assertFalse(evidence["hostTelemetryTableAbsent"])
self.assertTrue(evidence["constraintMatchesReplay011Kinds"])
self.assertEqual(evidence["constraintPhase"], "replay-011")
self.assertTrue(evidence["constraintMatchesKnownReplayCheckpoint"])
self.assertFalse(evidence["recovery044Ready"])
self.assertFalse(evidence["checkpointRecoveryReady"])
self.assertFalse(evidence["finalStateReady"])
command = run.call_args.args[0]
query = command[command.index("-c") + 1]
self.assertTrue(query.lstrip().lower().startswith("with constraint_state"))
self.assertNotIn(";", query)
self.assertIsNone(
re.search(
r"(?im)^\s*(?:delete|update|insert|truncate|alter|drop|create)\b",
query,
)
)
def test_recovery_rejection_prints_bounded_database_evidence(self):
database_result = mock.Mock(
returncode=0,
stdout=(
"0\t0\ttrue\ttrue\ttrue\t"
+ json.dumps(
sorted(RUNNER.DEVICE_PLANE_CONTROL_CORE_FINAL_COMMAND_KINDS),
separators=(",", ":"),
)
+ "\n"
),
stderr="",
)
output = io.StringIO()
with mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("p" * 64,),
), mock.patch.object(
RUNNER.subprocess,
"run",
return_value=database_result,
), contextlib.redirect_stdout(output), self.assertRaises(
RUNNER.DeployError
):
RUNNER.collect_device_plane_control_core_migration_replay_database_evidence()
rendered = output.getvalue()
for marker in (
"invalid_command_kind_count=0",
"triggering_receipt_count=0",
"constraint_validated=true",
"constraint_covers_final_kinds=true",
"host_telemetry_table_absent=true",
"constraint_matches_replay_011_kinds=false",
"constraint_phase=final-016",
"constraint_matches_final_016_kinds=true",
"recovery_final_state_ready=false",
):
self.assertIn(marker, rendered)
def test_audit_preflight_resolves_recovery_from_canonical_inbox(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-control-core-migration-replay-preflight-",
) as directory:
root = Path(directory)
inbox = root / "inbox"
runner_tmp = root / "runner-tmp"
source = root / "device-plane"
inbox.mkdir()
runner_tmp.mkdir()
live_migration = (
source / RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_014_REL
)
live_migration.parent.mkdir(parents=True)
live_migration.write_bytes(b"migration-014-predecessor")
recovery_artifact = (
inbox
/ RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_ARTIFACT
)
recovery_artifact.write_bytes(b"reviewed-recovery-044")
core = {
"containerId": "c" * 64,
"imageId": RUNNER.DEVICE_PLANE_CONTROL_CORE_V3_PREAPPLY_IMAGE_ID,
"status": "running",
"health": "unhealthy",
"restartCount": 3,
}
database = {
"invalidCommandKindCount": 0,
"triggeringReceiptCount": 0,
"constraintValidated": True,
"constraintCoversFinalKinds": True,
"hostTelemetryTableAbsent": True,
"constraintMatchesReplay011Kinds": True,
"constraintPhase": "replay-011",
"constraintMatchesKnownReplayCheckpoint": True,
"constraintMatchesFinalKinds": False,
"recovery044Ready": False,
"checkpointRecoveryReady": False,
"finalStateReady": False,
}
failure_evidence = {
"firstBackup": root / "first-backup",
"secondBackup": root / "second-backup",
}
recovery_manifest = {
"id": RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_PATCH_ID,
"component": "device-plane",
"type": "app-overlay",
}
with (
mock.patch.object(RUNNER, "INBOX", inbox),
mock.patch.object(RUNNER, "TMP_DIR", runner_tmp),
mock.patch.object(
RUNNER,
"DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_ARTIFACT_SHA256",
hashlib.sha256(recovery_artifact.read_bytes()).hexdigest(),
),
mock.patch.object(
RUNNER,
"DEVICE_PLANE_CONTROL_CORE_MIGRATION_014_PREDECESSOR_SHA256",
hashlib.sha256(live_migration.read_bytes()).hexdigest(),
),
mock.patch.object(
RUNNER,
"validate_device_plane_control_core_migration_replay_audit_payload",
return_value=(
RUNNER.expected_device_plane_control_core_migration_replay_audit_descriptor()
),
),
mock.patch.object(
RUNNER,
"validate_device_plane_control_core_double_failure_evidence",
return_value=failure_evidence,
),
mock.patch.object(
RUNNER,
"load_artifact",
return_value=(
recovery_manifest,
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_ENTRIES,
root / "recovery-payload",
),
),
mock.patch.object(
RUNNER,
"validate_device_plane_control_core_migration_replay_recovery_payload",
),
mock.patch.object(
RUNNER,
"load_state",
return_value=[],
) as load_state,
mock.patch.object(RUNNER, "component_root", return_value=source),
mock.patch.object(
RUNNER,
"validate_device_plane_control_core_migration_replay_preserved_runtime",
return_value={"current": {"services": []}, "core": core},
),
mock.patch.object(
RUNNER,
"collect_device_plane_control_core_migration_replay_database_evidence",
return_value=database,
) as collect_database,
):
evidence = (
RUNNER.validate_device_plane_control_core_migration_replay_audit_evidence(
root / "audit-payload"
)
)
self.assertEqual(evidence["recoveryArtifact"], recovery_artifact)
self.assertEqual(evidence["database"], database)
self.assertEqual(
[call.args for call in load_state.call_args_list],
[(RUNNER.STATE_FILE,), (RUNNER.FAILED_STATE_FILE,)],
)
collect_database.assert_called_once_with(
enforce_recovery_invariants=False,
)
def test_plan_and_apply_paths_preserve_plan_only_boundary(self):
plan_source = inspect.getsource(RUNNER.plan_artifact)
apply_source = inspect.getsource(RUNNER.apply_artifact)
self.assertIn(
"device_plane_control_core_migration_replay_audit_preflight",
plan_source,
)
self.assertIn(
"emit_device_plane_control_core_migration_replay_database_evidence",
plan_source,
)
self.assertIn(
"is_device_plane_control_core_migration_replay_audit_slice",
apply_source,
)
self.assertLess(
apply_source.index(
"is_device_plane_control_core_migration_replay_audit_slice"
),
apply_source.index("state_has_sha"),
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,442 @@
#!/usr/bin/env python3
import hashlib
import importlib.machinery
import importlib.util
import inspect
import json
import os
import re
import subprocess
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest import mock
SCRIPT_DIR = Path(__file__).resolve().parent
RUNNER_PATH = Path(
os.environ.get(
"NODEDC_DEPLOY_RUNNER",
SCRIPT_DIR.parents[2] / "platform/infra/deploy-runner/nodedc-deploy",
)
)
BUILDER = (
SCRIPT_DIR
/ "build-device-control-core-migration-replay-checkpoint-recovery-artifact.mjs"
)
LEGACY_BUILDER = (
SCRIPT_DIR
/ "build-device-control-core-migration-replay-recovery-artifact.mjs"
)
MIGRATION_ROOT = SCRIPT_DIR.parents[1] / "services/device-control-core/migrations"
def load_runner():
loader = importlib.machinery.SourceFileLoader(
"nodedc_control_core_migration_replay_checkpoint_runner_under_test",
str(RUNNER_PATH),
)
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNER = load_runner()
def database_stdout(
kinds,
*,
invalid=0,
triggering=8,
validated="false",
covers_final="false",
telemetry_absent="true",
):
return "\t".join(
(
str(invalid),
str(triggering),
validated,
covers_final,
telemetry_absent,
json.dumps(sorted(kinds), separators=(",", ":")),
)
) + "\n"
class DeviceControlCoreMigrationReplayCheckpointRecoveryArtifactTest(
unittest.TestCase
):
def build(self, artifact_dir):
environment = os.environ.copy()
environment["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(artifact_dir)
result = subprocess.run(
[
"node",
str(BUILDER),
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_CHECKPOINT_RECOVERY_PATCH_ID,
],
check=True,
capture_output=True,
text=True,
env=environment,
)
return json.loads(result.stdout)
def test_artifact_is_deterministic_exact_new_identity(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-control-core-checkpoint-recovery-",
) as directory:
artifact_dir = Path(directory)
first = self.build(artifact_dir)
first_bytes = Path(first["artifact"]).read_bytes()
second = self.build(artifact_dir)
second_bytes = Path(second["artifact"]).read_bytes()
self.assertEqual(first_bytes, second_bytes)
self.assertEqual(
first["sha256"],
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_CHECKPOINT_RECOVERY_ARTIFACT_SHA256,
)
self.assertEqual(first["services"], ["device-control-core"])
self.assertEqual(first["databaseRowMutation"], "none")
self.assertEqual(
first["entries"],
list(
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_CHECKPOINT_RECOVERY_ENTRIES
),
)
with tarfile.open(first["artifact"], "r:gz") as archive:
descriptor = json.loads(
archive.extractfile(
"payload/"
+ RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_CHECKPOINT_RECOVERY_REL
).read().decode("utf-8")
)
migration = archive.extractfile(
"payload/" + RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_014_REL
).read()
self.assertEqual(
descriptor,
RUNNER.expected_device_plane_control_core_migration_replay_checkpoint_recovery_descriptor(),
)
self.assertEqual(
hashlib.sha256(migration).hexdigest(),
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_014_TARGET_SHA256,
)
self.assertIn(b")) not valid;", migration.lower())
self.assertIsNone(
re.search(
rb"(?im)^\s*(?:delete|update|insert|truncate)\b",
migration,
)
)
def test_runner_selects_only_core_and_exact_build(self):
entries = (
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_CHECKPOINT_RECOVERY_ENTRIES
)
self.assertEqual(
RUNNER.component_services("device-plane", entries),
("device-control-core",),
)
builds = RUNNER.component_builds("device-plane", entries)
self.assertEqual(
builds,
((
RUNNER.DEVICE_PLANE_ROOT,
(
"build",
"--no-cache",
"--network=host",
"-f",
"services/device-control-core/Dockerfile",
"-t",
RUNNER.DEVICE_PLANE_CONTROL_CORE_IMAGE,
".",
),
),),
)
def test_checkpoint_sets_match_every_committed_replay_migration(self):
for phase, expected in RUNNER.DEVICE_PLANE_CONTROL_CORE_REPLAY_CHECKPOINTS:
migration_number = phase.split("-", 1)[1]
migration = next(MIGRATION_ROOT.glob(f"{migration_number}_*.sql"))
command_kinds = tuple(re.findall(r"'([^']+)'", migration.read_text()))
with self.subTest(phase=phase):
self.assertEqual(command_kinds, expected)
self.assertIn("not valid", migration.read_text().lower())
def test_every_exact_replay_checkpoint_is_accepted(self):
for phase, kinds in RUNNER.DEVICE_PLANE_CONTROL_CORE_REPLAY_CHECKPOINTS:
database_result = mock.Mock(
returncode=0,
stdout=database_stdout(kinds),
stderr="",
)
with self.subTest(phase=phase), mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("p" * 64,),
), mock.patch.object(
RUNNER.subprocess,
"run",
return_value=database_result,
):
evidence = (
RUNNER.collect_device_plane_control_core_migration_replay_database_evidence(
expected_state="replay-checkpoint-predecessor",
)
)
self.assertEqual(evidence["constraintPhase"], phase)
self.assertTrue(
evidence["constraintMatchesKnownReplayCheckpoint"]
)
self.assertTrue(evidence["checkpointRecoveryReady"])
self.assertFalse(evidence["finalStateReady"])
def test_unknown_missing_and_validated_checkpoint_states_are_rejected(self):
cases = (
(
"unknown",
database_stdout(("owner_scope.ensure", "unknown.ensure")),
),
(
"missing",
database_stdout((), validated="missing"),
),
(
"validated-checkpoint",
database_stdout(
RUNNER.DEVICE_PLANE_CONTROL_CORE_REPLAY_005_COMMAND_KINDS,
validated="true",
),
),
)
for name, stdout in cases:
database_result = mock.Mock(
returncode=0,
stdout=stdout,
stderr="",
)
with self.subTest(name=name), mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("p" * 64,),
), mock.patch.object(
RUNNER.subprocess,
"run",
return_value=database_result,
), self.assertRaises(RUNNER.DeployError):
RUNNER.collect_device_plane_control_core_migration_replay_database_evidence(
expected_state="replay-checkpoint-predecessor",
)
def test_final_acceptance_requires_exact_migration_016_set(self):
database_result = mock.Mock(
returncode=0,
stdout=database_stdout(
RUNNER.DEVICE_PLANE_CONTROL_CORE_FINAL_COMMAND_KINDS,
validated="true",
covers_final="true",
),
stderr="",
)
with mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("p" * 64,),
), mock.patch.object(
RUNNER.subprocess,
"run",
return_value=database_result,
):
evidence = (
RUNNER.collect_device_plane_control_core_migration_replay_database_evidence(
expected_state="final",
)
)
self.assertEqual(evidence["constraintPhase"], "final-016")
self.assertTrue(evidence["constraintMatchesFinalKinds"])
self.assertTrue(evidence["finalStateReady"])
self.assertFalse(evidence["checkpointRecoveryReady"])
def test_terminal_044_failure_evidence_is_exact_and_preapply(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-control-core-recovery-044-failure-",
) as directory:
root = Path(directory)
artifact_dir = root / "artifact"
failed_dir = root / "failed"
runner_tmp = root / "tmp"
state_file = root / "applied.jsonl"
failed_state_file = root / "failed.jsonl"
artifact_dir.mkdir()
failed_dir.mkdir()
runner_tmp.mkdir()
environment = os.environ.copy()
environment["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(artifact_dir)
subprocess.run(
[
"node",
str(LEGACY_BUILDER),
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_PATCH_ID,
],
check=True,
capture_output=True,
text=True,
env=environment,
)
source = (
artifact_dir
/ RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_ARTIFACT
)
failed_artifact = (
failed_dir
/ RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_FAILED_ARTIFACT
)
source.replace(failed_artifact)
state_file.write_text("", encoding="utf-8")
record = {
"artifact": failed_artifact.name,
"backup_id": None,
"component": "device-plane",
"failed_at": (
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_FAILED_AT
),
"id": RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_PATCH_ID,
"message": (
"Device Control Core migration recovery database invariant mismatch"
),
"rollback_status": "not-required",
"sha256": (
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_ARTIFACT_SHA256
),
"started_apply": False,
"status": "failed",
}
failed_state_file.write_text(
json.dumps(record) + "\n",
encoding="utf-8",
)
with mock.patch.object(RUNNER, "FAILED_DIR", failed_dir), mock.patch.object(
RUNNER,
"STATE_FILE",
state_file,
), mock.patch.object(
RUNNER,
"FAILED_STATE_FILE",
failed_state_file,
), mock.patch.object(RUNNER, "TMP_DIR", runner_tmp):
evidence = (
RUNNER.validate_device_plane_control_core_migration_replay_recovery_failure()
)
self.assertEqual(evidence["record"], record)
def test_checkpoint_recovery_preflight_reaches_database_collector(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-control-core-checkpoint-preflight-",
) as directory:
root = Path(directory)
migration = (
root / RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_014_REL
)
migration.parent.mkdir(parents=True)
migration.write_bytes(b"migration-014-predecessor")
core = {
"containerId": "c" * 64,
"imageId": RUNNER.DEVICE_PLANE_CONTROL_CORE_V3_PREAPPLY_IMAGE_ID,
"status": "restarting",
"health": "unhealthy",
"restartCount": 280,
}
runtime = {"core": core, "current": {"services": [core]}}
database = {
"constraintPhase": "replay-007",
"checkpointRecoveryReady": True,
}
descriptor = (
RUNNER.expected_device_plane_control_core_migration_replay_checkpoint_recovery_descriptor()
)
with mock.patch.object(
RUNNER,
"validate_device_plane_control_core_migration_replay_checkpoint_recovery_payload",
return_value=descriptor,
), mock.patch.object(
RUNNER,
"validate_device_plane_control_core_double_failure_evidence",
return_value={
"firstBackup": root / "first",
"secondBackup": root / "second",
},
), mock.patch.object(
RUNNER,
"validate_device_plane_control_core_migration_replay_recovery_failure",
return_value={"record": {"started_apply": False}},
), mock.patch.object(
RUNNER,
"component_root",
return_value=root,
), mock.patch.object(
RUNNER,
"DEVICE_PLANE_CONTROL_CORE_MIGRATION_014_PREDECESSOR_SHA256",
hashlib.sha256(migration.read_bytes()).hexdigest(),
), mock.patch.object(
RUNNER,
"validate_device_plane_control_core_migration_replay_preserved_runtime",
return_value=runtime,
), mock.patch.object(
RUNNER,
"inspect_optional_local_image",
return_value=RUNNER.DEVICE_PLANE_CONTROL_CORE_V3_PREAPPLY_IMAGE_ID,
), mock.patch.object(
RUNNER,
"collect_device_plane_control_core_migration_replay_database_evidence",
return_value=database,
) as collector:
evidence = (
RUNNER.validate_device_plane_control_core_migration_replay_checkpoint_recovery_evidence(
root
)
)
self.assertEqual(evidence["database"], database)
collector.assert_called_once_with(
expected_state="replay-checkpoint-predecessor",
)
def test_v2_rollback_and_acceptance_are_registered(self):
rollback_source = inspect.getsource(RUNNER.rollback_device_plane_apply)
health_source = inspect.getsource(RUNNER.run_healthchecks)
preflight_source = inspect.getsource(
RUNNER.validate_device_plane_control_core_migration_replay_checkpoint_recovery_evidence
)
acceptance_source = inspect.getsource(
RUNNER.accept_device_plane_control_core_migration_replay_checkpoint_recovery
)
self.assertIn(
"is_device_plane_control_core_migration_replay_checkpoint_recovery_slice",
rollback_source,
)
self.assertIn(
"accept_device_plane_control_core_migration_replay_checkpoint_recovery",
health_source,
)
self.assertIn(
'expected_state="replay-checkpoint-predecessor"',
preflight_source,
)
self.assertIn(
"validate_device_plane_control_core_migration_replay_recovery_failure",
preflight_source,
)
self.assertIn('expected_state="final"', acceptance_source)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,289 @@
#!/usr/bin/env python3
import hashlib
import importlib.machinery
import importlib.util
import inspect
import json
import os
import re
import subprocess
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest import mock
SCRIPT_DIR = Path(__file__).resolve().parent
RUNNER_PATH = Path(
os.environ.get(
"NODEDC_DEPLOY_RUNNER",
SCRIPT_DIR.parents[2] / "platform/infra/deploy-runner/nodedc-deploy",
)
)
BUILDER = (
SCRIPT_DIR
/ "build-device-control-core-migration-replay-recovery-artifact.mjs"
)
MIGRATION_011 = (
SCRIPT_DIR.parents[1]
/ "services/device-control-core/migrations/011_device_control_resource_commands.sql"
)
def load_runner():
loader = importlib.machinery.SourceFileLoader(
"nodedc_control_core_migration_replay_runner_under_test",
str(RUNNER_PATH),
)
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNER = load_runner()
class DeviceControlCoreMigrationReplayRecoveryArtifactTest(unittest.TestCase):
def build(self, artifact_dir):
environment = os.environ.copy()
environment["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(artifact_dir)
result = subprocess.run(
[
"node",
str(BUILDER),
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_PATCH_ID,
],
check=True,
capture_output=True,
text=True,
env=environment,
)
return json.loads(result.stdout)
def test_artifact_is_deterministic_exact_minimal_repair(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-control-core-migration-replay-recovery-",
) as directory:
artifact_dir = Path(directory)
first = self.build(artifact_dir)
first_bytes = Path(first["artifact"]).read_bytes()
second = self.build(artifact_dir)
second_bytes = Path(second["artifact"]).read_bytes()
self.assertEqual(first_bytes, second_bytes)
self.assertEqual(
first["sha256"],
hashlib.sha256(first_bytes).hexdigest(),
)
self.assertEqual(first["services"], ["device-control-core"])
self.assertEqual(first["databaseRowMutation"], "none")
self.assertEqual(
first["entries"],
list(
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_ENTRIES
),
)
with tarfile.open(first["artifact"], "r:gz") as archive:
descriptor = json.loads(
archive.extractfile(
"payload/"
+ RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_REL
).read().decode("utf-8")
)
migration = archive.extractfile(
"payload/" + RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_014_REL
).read()
self.assertEqual(
descriptor,
RUNNER.expected_device_plane_control_core_migration_replay_recovery_descriptor(),
)
self.assertEqual(
hashlib.sha256(migration).hexdigest(),
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_014_TARGET_SHA256,
)
self.assertIn(b")) not valid;", migration.lower())
self.assertIsNone(
re.search(
rb"(?im)^\s*(?:delete|update|insert|truncate)\b",
migration,
)
)
def test_runner_selects_only_core_and_exact_build(self):
entries = (
RUNNER.DEVICE_PLANE_CONTROL_CORE_MIGRATION_REPLAY_RECOVERY_ENTRIES
)
self.assertEqual(
RUNNER.component_services("device-plane", entries),
("device-control-core",),
)
builds = RUNNER.component_builds("device-plane", entries)
self.assertEqual(len(builds), 1)
self.assertEqual(builds[0][0], RUNNER.DEVICE_PLANE_ROOT)
self.assertEqual(
builds[0][1],
(
"build",
"--no-cache",
"--network=host",
"-f",
"services/device-control-core/Dockerfile",
"-t",
RUNNER.DEVICE_PLANE_CONTROL_CORE_IMAGE,
".",
),
)
def test_database_preflight_is_read_only_and_covers_live_receipts(self):
database_result = mock.Mock(
returncode=0,
stdout=(
"0\t8\tfalse\tfalse\ttrue\t"
+ json.dumps(
sorted(
RUNNER.DEVICE_PLANE_CONTROL_CORE_REPLAY_011_COMMAND_KINDS
),
separators=(",", ":"),
)
+ "\n"
),
stderr="",
)
with mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("p" * 64,),
), mock.patch.object(
RUNNER.subprocess,
"run",
return_value=database_result,
) as run:
evidence = (
RUNNER.collect_device_plane_control_core_migration_replay_database_evidence(
expected_state="replay-011-predecessor",
)
)
self.assertEqual(evidence["invalidCommandKindCount"], 0)
self.assertEqual(evidence["triggeringReceiptCount"], 8)
self.assertFalse(evidence["constraintValidated"])
self.assertFalse(evidence["constraintCoversFinalKinds"])
self.assertTrue(evidence["constraintMatchesReplay011Kinds"])
self.assertEqual(evidence["constraintPhase"], "replay-011")
self.assertTrue(evidence["recovery044Ready"])
self.assertTrue(evidence["checkpointRecoveryReady"])
self.assertFalse(evidence["finalStateReady"])
command = run.call_args.args[0]
query = command[command.index("-c") + 1]
self.assertTrue(query.lstrip().lower().startswith("with constraint_state"))
self.assertNotIn(";", query)
self.assertIsNone(
re.search(
r"(?im)^\s*(?:delete|update|insert|truncate|alter|drop|create)\b",
query,
)
)
self.assertIn("regexp_matches", query)
self.assertIn("array_to_json", query)
def test_runner_predecessor_kind_set_matches_migration_011(self):
migration = MIGRATION_011.read_text(encoding="utf-8")
command_kinds = tuple(re.findall(r"'([^']+)'", migration))
self.assertEqual(
command_kinds,
RUNNER.DEVICE_PLANE_CONTROL_CORE_REPLAY_011_COMMAND_KINDS,
)
def test_database_acceptance_requires_final_validated_constraint(self):
database_result = mock.Mock(
returncode=0,
stdout=(
"0\t8\ttrue\ttrue\ttrue\t"
+ json.dumps(
sorted(RUNNER.DEVICE_PLANE_CONTROL_CORE_FINAL_COMMAND_KINDS),
separators=(",", ":"),
)
+ "\n"
),
stderr="",
)
with mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("p" * 64,),
), mock.patch.object(
RUNNER.subprocess,
"run",
return_value=database_result,
):
evidence = (
RUNNER.collect_device_plane_control_core_migration_replay_database_evidence(
expected_state="final",
)
)
self.assertTrue(evidence["constraintValidated"])
self.assertTrue(evidence["constraintCoversFinalKinds"])
self.assertFalse(evidence["constraintMatchesReplay011Kinds"])
self.assertEqual(evidence["constraintPhase"], "final-016")
self.assertTrue(evidence["constraintMatchesFinalKinds"])
self.assertFalse(evidence["recovery044Ready"])
self.assertFalse(evidence["checkpointRecoveryReady"])
self.assertTrue(evidence["finalStateReady"])
def test_database_preflight_rejects_ambiguous_constraint_shape(self):
database_result = mock.Mock(
returncode=0,
stdout=(
"0\t8\tfalse\tfalse\ttrue\t"
+ json.dumps(["owner_scope.ensure", "unknown.ensure"])
+ "\n"
),
stderr="",
)
with mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("p" * 64,),
), mock.patch.object(
RUNNER.subprocess,
"run",
return_value=database_result,
), self.assertRaises(RUNNER.DeployError):
RUNNER.collect_device_plane_control_core_migration_replay_database_evidence(
expected_state="replay-011-predecessor",
)
def test_rollback_accepts_exact_degraded_predecessor_boundary(self):
rollback_source = inspect.getsource(RUNNER.rollback_device_plane_apply)
acceptance_source = inspect.getsource(
RUNNER.accept_device_plane_control_core_rollback_runtime
)
preflight_source = inspect.getsource(
RUNNER.validate_device_plane_control_core_migration_replay_recovery_evidence
)
recovery_acceptance_source = inspect.getsource(
RUNNER.accept_device_plane_control_core_migration_replay_recovery
)
self.assertIn(
"is_device_plane_control_core_migration_replay_recovery_slice",
rollback_source,
)
self.assertIn("retag_device_plane_control_core_image", rollback_source)
self.assertIn("not predecessor_was_healthy", acceptance_source)
self.assertIn("changed preserved service", acceptance_source)
self.assertIn(
'expected_state="replay-011-predecessor"',
preflight_source,
)
self.assertIn(
'expected_state="final"',
recovery_acceptance_source,
)
if __name__ == "__main__":
unittest.main()

Some files were not shown because too many files have changed in this diff Show More