Manage shared ARNavi VPS contours and application keys from infrastructure

This commit is contained in:
DCCONSTRUCTIONS
2026-09-30 15:34:39 +03:00
parent 6ca6738bab
commit 1828a05332
22 changed files with 1099 additions and 2 deletions
@@ -63,6 +63,12 @@ export function createDeviceCoreClient({ baseUrl, token, fetchImpl = fetch } = {
return { return {
configured: true, configured: true,
async b2Infrastructure(actor, input, requestId) {
return request("/internal/v1/b2/infrastructure", actor, {
method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": requestId },
body: JSON.stringify(input),
}).then((body) => body.result);
},
async listProjects(actor) { async listProjects(actor) {
return request("/internal/v1/query/projects", actor) return request("/internal/v1/query/projects", actor)
.then((body) => body.projects); .then((body) => body.projects);
@@ -1297,7 +1303,7 @@ function normalizeBaseUrl(value) {
} }
function safeCoreError(value) { function safeCoreError(value) {
return typeof value === "string" && /^device_[a-z0-9._:-]{2,120}$/.test(value) return typeof value === "string" && /^(?:device|b2)_[a-z0-9._:-]{2,120}$/.test(value)
? value ? value
: "device_core_unavailable"; : "device_core_unavailable";
} }
@@ -171,6 +171,19 @@ export function createDeviceManagerServer({
const workspace = await coreClient.getWorkspace(context.actor, projectRef); const workspace = await coreClient.getWorkspace(context.actor, projectRef);
return sendJson(response, 200, { ok: true, workspace }); return sendJson(response, 200, { ok: true, workspace });
} }
if (request.method === "POST" && url.pathname === "/api/device-manager/b2/infrastructure") {
if (!coreClient.b2Infrastructure) throw serviceError("b2_infrastructure_unavailable", 503);
// This route handles keys. Require JSON and an explicit same-origin
// browser request in addition to the authenticated server-side session.
if (request.headers.origin !== `${auth.authRequired ? 'https:' : url.protocol}//${request.headers.host}` || !String(request.headers["content-type"] || "").startsWith("application/json")) {
throw serviceError("device_manager_origin_required", 403);
}
const requestId = singleHeader(request.headers["idempotency-key"]);
if (!/^[a-f0-9]{32}$/.test(requestId)) throw serviceError("b2_request_id_invalid", 400);
const input = await readJsonBody(request, 64 * 1024);
const result = await coreClient.b2Infrastructure(context.actor, input, requestId);
return sendJson(response, 200, { ok: true, result });
}
const command = mutationRoutes.get(url.pathname); const command = mutationRoutes.get(url.pathname);
if (request.method === "POST" && command) { if (request.method === "POST" && command) {
const idempotencyKey = singleHeader(request.headers["idempotency-key"]); const idempotencyKey = singleHeader(request.headers["idempotency-key"]);
@@ -373,7 +386,7 @@ function normalizeStatus(value) {
function safeError(error) { function safeError(error) {
const value = String(error?.message || ""); const value = String(error?.message || "");
return /^(?:device|nodedc)_[a-z0-9._:-]{2,160}$/.test(value) return /^(?:device|nodedc|b2)_[a-z0-9._:-]{2,160}$/.test(value)
? value ? value
: "device_manager_internal_error"; : "device_manager_internal_error";
} }
@@ -207,3 +207,29 @@ async function postJson(url, body, headers = {}) {
assert.equal(payload.ok, true); assert.equal(payload.ok, true);
return payload; return payload;
} }
test('B2 key management rejects cross-origin requests and never caches returned credentials', async (t) => {
const auth = createDeviceManagerAuth({ env: { NODEDC_DEVICE_MANAGER_AUTH_REQUIRED: 'false' } });
const calls = [];
const coreClient = { ...createLocalPreviewDeviceCore(), async b2Infrastructure(actor, body, id) {
calls.push({ actor, body, id }); return { connection: { client_secret: 'synthetic-once-only' } };
} };
const server = createDeviceManagerServer({ auth, coreClient });
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
t.after(() => new Promise((resolve) => server.close(resolve)));
const origin = `http://127.0.0.1:${server.address().port}`;
const headers = { 'content-type': 'application/json', 'idempotency-key': 'a'.repeat(32) };
const body = JSON.stringify({ action: 'key-issue', projectRef: 'project:synthetic', hostRef: 'host:synthetic' });
for (const supplied of [undefined, 'https://attacker.invalid']) {
const denied = await fetch(origin + '/api/device-manager/b2/infrastructure', { method: 'POST', headers: { ...headers, ...(supplied ? { origin: supplied } : {}) }, body });
assert.equal(denied.status, 403);
}
assert.equal(calls.length, 0);
const response = await fetch(origin + '/api/device-manager/b2/infrastructure', { method: 'POST',
headers: { ...headers, origin, 'X-NODEDC-User-Ref': 'user:spoofed' }, body });
assert.equal(response.status, 200);
assert.match(response.headers.get('cache-control'), /no-store/);
assert.equal((await response.json()).result.connection.client_secret, 'synthetic-once-only');
assert.equal(calls.length, 1);
assert.equal(calls[0].actor.userRef, 'user:local-device-admin');
});
@@ -13,6 +13,8 @@ import {
WindowFooterActions, WindowFooterActions,
} from "@nodedc/ui-react"; } from "@nodedc/ui-react";
import { B2HostSettings } from "./b2/B2HostSettings";
import { import {
createConfigurationRevision, createConfigurationRevision,
closeAssetBinding, closeAssetBinding,
@@ -496,7 +498,9 @@ function HostsView({
onPoll: () => Promise<void>; onPoll: () => Promise<void>;
onError: (reason: unknown) => void; onError: (reason: unknown) => void;
}) { }) {
const [settingsHost, setSettingsHost] = useState<InfrastructureHostView | null>(null);
const [selectedHostRef, setSelectedHostRef] = useState<string | null>(null); const [selectedHostRef, setSelectedHostRef] = useState<string | null>(null);
useEffect(() => setSettingsHost(null), [workspace.project.projectRef]);
const [expandedHostRefs, setExpandedHostRefs] = useState<Set<string>>(() => new Set()); const [expandedHostRefs, setExpandedHostRefs] = useState<Set<string>>(() => new Set());
const inventoryRef = useRef<HTMLDivElement>(null); const inventoryRef = useRef<HTMLDivElement>(null);
const topology = workspace.ontology; const topology = workspace.ontology;
@@ -528,6 +532,7 @@ function HostsView({
} }
return ( return (
<div className="infrastructure-system-workspace" ref={inventoryRef}> <div className="infrastructure-system-workspace" ref={inventoryRef}>
{settingsHost ? <B2HostSettings key={workspace.project.projectRef + settingsHost.hostRef} host={settingsHost} workspace={workspace} onClose={() => setSettingsHost(null)} onChanged={onPoll} onError={onError} /> : null}
<section className="infrastructure-overview-block"> <section className="infrastructure-overview-block">
<div className="infrastructure-workspace-lead"> <div className="infrastructure-workspace-lead">
<div> <div>
@@ -579,6 +584,7 @@ function HostsView({
<code>{host.externalRef || host.hostKey}</code> <code>{host.externalRef || host.hostKey}</code>
</div> </div>
<div className="infrastructure-host-card__actions"> <div className="infrastructure-host-card__actions">
{canManageInfrastructure ? <IconButton label={`Настройки ${host.displayName}`} onClick={() => setSettingsHost(host)}><Icon name="settings" /></IconButton> : null}
<Button size="compact" variant="primary" onClick={() => setSelectedHostRef(host.hostRef)}>Мониторинг</Button> <Button size="compact" variant="primary" onClick={() => setSelectedHostRef(host.hostRef)}>Мониторинг</Button>
<span <span
className="infrastructure-host-card__freshness" className="infrastructure-host-card__freshness"
@@ -0,0 +1,125 @@
import { useEffect, useState } from 'react';
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge,
TextField, TextAreaField, WindowFooterActions, ConfirmationModal } from '@nodedc/ui-react';
import { loadProjects } from '../api';
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
import { b2Request, type B2Status } from './api';
import './b2.css';
type Section = 'connection' | 'contours' | 'applications';
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
onChanged: () => Promise<void>; onError: (error: unknown) => void;
}) {
const project = workspace.project;
const [section, setSection] = useState<Section>('connection');
const [status, setStatus] = useState<B2Status | null>(null);
const [pending, setPending] = useState('');
const [connection, setConnection] = useState('');
const [key, setKey] = useState(''); const [name, setName] = useState('');
const [contour, setContour] = useState('');
const [targetProject, setTargetProject] = useState(project.projectRef);
const [projects, setProjects] = useState<ProjectSummary[]>([]);
const [issued, setIssued] = useState('');
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
const request = <T,>(action: string, data: Record<string, unknown> = {}) => b2Request<T>(project.projectRef, host.hostRef, action, data);
const refresh = () => request<B2Status>('status').then(setStatus);
useEffect(() => {
let active = true;
setPending('load');
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
if (!active) return;
setStatus(value);
setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef));
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
return () => { active = false; };
}, [host.hostRef, project.projectRef]);
async function run(action: string, data: Record<string, unknown> = {}) {
setPending(action);
try {
const result = await request<{ connection?: unknown }>(action, data);
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2));
if (action === 'connect') setConnection('');
await refresh(); await onChanged();
} catch (error) { onError(error); } finally { setPending(''); }
}
const contours = status?.contours || [];
const canManage = status?.authority === 'host';
const busy = Boolean(pending);
return <>
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' },
{ id: 'contours', label: 'Контуры и проекты', icon: 'layers', disabled: !status?.connected },
{ id: 'applications', label: 'Приложения и ключи', icon: 'key', disabled: !status?.connected }]}
activeSection={section} onSectionChange={(value) => { setSection(value); setKey(''); setName(''); }} onClose={onClose}
footer={<WindowFooterActions><Button onClick={onClose}>Закрыть</Button>
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
}}><Icon name="refresh" /></IconButton></WindowFooterActions>}>
<div className="b2-settings">
{section === 'connection' ? <>
<SettingsCard title="ARNavi VPS" description="Одно подключение сервера для проектов компании. Устройства разделяются контурами.">
<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Проверяем подключение' : status ? 'Не подключён' : 'Состояние не получено'}</StatusBadge>
{status?.endpoint ? <p>{status.endpoint}</p> : null}
</SettingsCard>
<SettingsCard title={status?.connected ? 'Заменить ключ подключения' : 'Подключить сервер'} description="Вставьте ключ, выданный на VPS. После подключения он хранится только на сервере Device Core.">
<div className="b2-settings">
<TextAreaField label="Ключ подключения" value={connection} autoComplete="off" spellCheck={false}
onChange={(event) => setConnection(event.target.value)} rows={5} />
<Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>Подключить</Button>
</div>
</SettingsCard>
</> : null}
{section === 'contours' ? <>
<SettingsCard title="Контуры на VPS" description="Связь с проектом определяет, где появятся устройства. Один контур можно подключить к нескольким приложениям.">
<div className="b2-settings">
{contours.map((item) => {
const link = status?.links?.find((value) => value.contourId === item.id);
return <div className="b2-resource" key={item.id}><div><strong>{item.name}</strong><small>{item.key}</small></div>
<StatusBadge tone={link ? 'success' : 'neutral'}>{link ? projects.find((p) => p.projectRef === link.projectRef)?.name || 'Связан с проектом' : 'Не связан'}</StatusBadge></div>;
})}
{!contours.length ? <p>На VPS пока нет контуров.</p> : null}
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
<Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((item) => ({ value: item.projectRef, label: item.name }))} />
<Button loading={pending === 'link'} disabled={busy || !contour || !targetProject} onClick={() => void run('link', { contourId: contour, targetProjectRef: targetProject })}>Связать с проектом</Button>
</div>
</SettingsCard>
{canManage ? <SettingsCard title="Новый контур" description="Контур создаётся на VPS и получает собственный реестр устройств.">
<div className="b2-settings"><TextField label="Название" value={name} onChange={(e) => setName(e.target.value)} />
<TextField label="Код контура" value={key} placeholder="robot2b" onChange={(e) => setKey(e.target.value)} />
<Button loading={pending === 'contour-create'} disabled={busy || !/^[a-z][a-z0-9-]{0,63}$/.test(key) || !name.trim()}
onClick={() => void run('contour-create', { key, name })}>Создать контур</Button></div>
</SettingsCard> : null}
</> : null}
{section === 'applications' ? <>
{issued ? <SettingsCard title="Новый ключ приложения" description="Скопируйте ключ и передайте в подключаемое приложение. Позже его можно перевыпустить без потери устройств.">
<div className="b2-settings"><TextAreaField label="Ключ" value={issued} readOnly rows={6} />
<Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать ключ</Button>
<Button onClick={() => setIssued('')}>Скрыть</Button></div>
</SettingsCard> : null}
{(status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core').map((app) => <SettingsCard key={app.id} title={app.name}
description={Object.keys(app.grants).map((id) => contours.find((item) => item.id === id)?.name || id).join(', ')}>
<div className="b2-settings">
{app.credentials.map((credential) => <div className="b2-resource" key={credential.client_id}>
<div><small>{credential.client_id}</small><StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge></div>
{credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${app.name}»? Подключённый клиент потеряет доступ.` })}>Отозвать</Button> : null}
</div>)}
<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: true }, text: `Выдать новый ключ для «${app.name}»? Предыдущие ключи этого приложения перестанут работать. Устройства и история сохранятся.` })}>{app.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>
</div>
</SettingsCard>)}
{canManage ? <SettingsCard title="Подключить новое приложение" description="Для каждого приложения создайте отдельный ключ. Несколько приложений могут работать с одним контуром независимо.">
<div className="b2-settings"><TextField label="Название приложения" value={name} onChange={(e) => setName(e.target.value)} />
<TextField label="Код приложения" value={key} placeholder="robot2b-client" onChange={(e) => setKey(e.target.value)} />
<Select label="Контур" value={contour} onChange={setContour} options={contours.map((item) => ({ value: item.id, label: item.name }))} />
<Button loading={pending === 'application-create'} disabled={busy || !contour || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)}
onClick={() => void run('application-create', { key, name, contourId: contour })}>Создать приложение</Button></div>
</SettingsCard> : <SettingsCard title="Доступ к контуру" description="Управление ключами доступно через управляющее подключение VPS." />}
</> : null}
</div>
</FeatureSettingsWindow>
<ConfirmationModal open={Boolean(confirm)} title="Изменить доступ приложения" description={confirm?.text}
confirmLabel="Продолжить" cancelLabel="Отмена" onClose={() => setConfirm(null)}
onConfirm={async () => { if (confirm) await run(confirm.action, confirm.fields); setConfirm(null); }} />
</>;
}
+32
View File
@@ -0,0 +1,32 @@
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';
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_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.',
b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.',
b2_host_not_connected: 'Сначала подключите VPS.',
b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.',
b2_key_rejected: 'VPS не принял ключ подключения.',
b2_conflict: 'На VPS уже есть запись с такими данными. Обновите список и проверьте результат.',
b2_contour_already_linked: 'Этот контур уже связан с другим проектом.',
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 async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}): Promise<T> {
const response = await fetch('/api/device-manager/b2/infrastructure', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID().replaceAll('-', '') },
body: JSON.stringify({ projectRef, hostRef, action, ...fields }),
});
const body = await response.json().catch(() => null);
if (!response.ok || body?.ok !== true) throw new Error(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.');
return body.result as T;
}
+6
View File
@@ -0,0 +1,6 @@
.b2-settings { display: grid; gap: var(--nodedc-space-md, 16px); }
.b2-settings p { margin: 0; font-size: var(--nodedc-font-size-sm); color: var(--nodedc-text-secondary); }
.b2-resource { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-sm, 8px); flex-wrap: wrap; }
.b2-resource > div { display: grid; gap: 4px; min-width: 0; }
.b2-resource strong { font-size: var(--nodedc-font-size-sm); }
.b2-resource small { font-size: var(--nodedc-font-size-xs); overflow-wrap: anywhere; color: var(--nodedc-text-secondary); }
+10
View File
@@ -0,0 +1,10 @@
{
"schemaVersion": "nodedc.device-b2-foundation.v1",
"releaseId": "device-b2-foundation-v1-20260930-001",
"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;
+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
+103
View File
@@ -0,0 +1,103 @@
# Shared ARNavi VPS and Device Core infrastructure
Status: implementation in progress, 2026-09-30. No production activation yet.
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 Contours and projects, create a contour on the VPS and explicitly link it
to an accessible project of the same company. Linking another project adds
a view of the same host there. It does not duplicate the remote VPS or key.
5. In Applications and keys, create an application for a selected contour.
Issue its key and transfer it to that application's backend. Each application
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.
The public UI and running VPS remain on their accepted previous releases until
that exact transition and VPS authority installation pass acceptance. The old
unidentified Robot2B pilot must not be treated as the physical rover tracker.
## Validation bounds
Current local checks cover company/project authorization, independent VPS
subscriptions, key replacement, private-file permissions and TLS pin-before-send.
These are bounded tests, not fleet simulation. The owner deferred Worker006,
load and simulation. Production acceptance still needs the real VPS, both
DCTOUCH projects, real key import, cross-project denial and independent app
registration. No claim about 50/100-device load is made here.
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.
@@ -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-001'
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,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()
+10
View File
@@ -1648,6 +1648,15 @@
"node": ">=18" "node": ">=18"
} }
}, },
"node_modules/oauth4webapi": {
"version": "3.8.8",
"resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz",
"integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/pg": { "node_modules/pg": {
"version": "8.22.0", "version": "8.22.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz", "resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
@@ -2136,6 +2145,7 @@
"name": "@nodedc/device-control-core", "name": "@nodedc/device-control-core",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"oauth4webapi": "3.8.8",
"pg": "8.22.0" "pg": "8.22.0"
}, },
"engines": { "engines": {
+83
View File
@@ -0,0 +1,83 @@
// Bounded SQL qualification, not a fleet simulator or a production DB connection.
// npm install --prefix /private/tmp/ndc-b2-sql-check --ignore-scripts --save-exact @electric-sql/pglite@0.5.8
// node scripts/qualify-b2-foundation.mjs /private/tmp/ndc-b2-sql-check/node_modules/@electric-sql/pglite/dist/index.js /private/tmp/b2-schema-proof.json
import assert from 'node:assert/strict';
import { readFile, readdir, writeFile, mkdtemp, rm } from 'node:fs/promises';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { resolve } from 'node:path';
import { tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
import { B2Infrastructure } from '../services/device-control-core/src/b2/infrastructure.mjs';
import { B2Secrets } from '../services/device-control-core/src/b2/secrets.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
const { PGlite } = await import(pathToFileURL(resolve(process.argv[2])));
const db = new PGlite();
try {
const directory = resolve(root, 'services/device-control-core/migrations');
const migrations = (await readdir(directory)).filter((name) => name.endsWith('.sql')).sort();
for (const name of migrations) await db.exec(await readFile(resolve(directory, name), 'utf8'));
assert.equal(migrations.length, 17);
await db.exec(await readFile(resolve(root, 'deployment/device-b2-foundation-v1.sql'), 'utf8'));
const ownerA = '11111111-1111-4111-8111-111111111111'; const ownerB = '22222222-2222-4222-8222-222222222222';
const projectA = '33333333-3333-4333-8333-333333333333'; const projectB = '44444444-4444-4444-8444-444444444444';
const source = '55555555-5555-4555-8555-555555555555'; const host = '66666666-6666-4666-8666-666666666666';
for (const [owner, project] of [[ownerA, projectA], [ownerB, projectB]]) {
await db.query('insert into device_owner_scopes(id,scope_kind,owner_ref,display_name,created_by_ref) values($1,$2,$3,$4,$5)', [owner,'company','company:'+owner,'SQL fixture','user:fixture']);
await db.query('insert into device_projects(id,owner_scope_id,project_key,name,created_by_ref) values($1,$2,$3,$4,$5)', [project,owner,'fixture-project','SQL fixture','user:fixture']);
}
await db.query(`insert into device_b2_hosts(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
values($1,$2,$3,$4,$5,$6,$7,$8)`, [source,ownerA,'fixture-vps','https://vps.invalid','a'.repeat(64),'b'.repeat(32),'host','b2-secret:fixture']);
await db.query(`insert into device_infrastructure_hosts(id,owner_scope_id,project_id,host_key,display_name,created_by_ref)
values($1,$2,$3,$4,$5,$6)`, [host,ownerA,projectA,'fixture-host','SQL fixture','user:fixture']);
await db.query('insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id) values($1,$2,$3,$4)', [host,projectA,ownerA,source]);
await assert.rejects(db.query('insert into device_b2_contour_links values($1,$2,$3,$4,$5,now())', [source,'c'.repeat(32),projectB,ownerA,'user:fixture']), (error) => error.code === '23503');
await db.query('insert into device_b2_contour_links values($1,$2,$3,$4,$5,now())', [source,'c'.repeat(32),projectA,ownerA,'user:fixture']);
await assert.rejects(db.query('insert into device_b2_contour_links values($1,$2,$3,$4,$5,now())', [source,'c'.repeat(32),projectA,ownerA,'user:fixture']), (error) => error.code === '23505');
// Execute the actual domain repository against PostgreSQL, not mocked SQL.
const projectA2 = '77777777-7777-4777-8777-777777777777';
await db.query('insert into device_projects(id,owner_scope_id,project_key,name,created_by_ref) values($1,$2,$3,$4,$5)', [projectA2,ownerA,'second-project','Second SQL fixture','user:fixture']);
for (const project of [projectA,projectA2,projectB]) await db.query(
'insert into device_project_grants(id,project_id,principal_kind,principal_ref,project_role,created_by_ref) values($1,$2,$3,$4,$5,$6)',
[randomUUID(),project,'user','user:fixture','owner','user:fixture']);
const secretRoot = await mkdtemp(resolve(tmpdir(),'b2-sql-secrets-'));
try {
const packageValue = { schema:'nodedc.b2-connection/v2',endpoint:'https://vps.invalid',host_id:'fixture-vps',
fingerprint:'a'.repeat(64),integration_id:'b'.repeat(32),authority:'host',issuer:'https://vps.invalid/',
audience:'https://vps.invalid/v2',scope:'b2',client_id:'b2_fixture',client_secret:'synthetic-sql-test-secret' };
const remote = { async call(path) {
if (path==='/v2/identity') return {host_id:packageValue.host_id};
if (path==='/v2/management') return {host_id:packageValue.host_id,contours:[],applications:[]};
if (path==='/v2/contours') return {items:[{id:'d'.repeat(32)}]};
if (path.endsWith('/devices')) return {items:[]};
throw new Error('unexpected test remote operation');
} };
const service = new B2Infrastructure({ pool:{connect:async()=>({query:(...args)=>db.query(...args),release(){}})},
secrets:new B2Secrets(secretRoot),clientFactory:()=>remote });
const actor = {userRef:'user:fixture',hubRole:'owner',groupRefs:[],ownerScopes:[{scopeKind:'company',ownerRef:'company:'+ownerA}]};
const common = {projectRef:'project:'+projectA,hostRef:'host:'+host};
const connect = await service.execute(actor,{...common,action:'connect',connection:packageValue},'a'.repeat(32));
assert.equal(connect.connected,true);
await service.execute(actor,{...common,action:'link',contourId:'d'.repeat(32),targetProjectRef:'project:'+projectA2},'b'.repeat(32));
const linkedViews = (await db.query('select * from device_b2_host_views where source_id=$1',[source])).rows;
assert.equal(linkedViews.length,2);
assert.equal(linkedViews.filter((view)=>view.project_id===projectA2).length,1);
await assert.rejects(service.execute(actor,{...common,action:'link',contourId:'d'.repeat(32),targetProjectRef:'project:'+projectB},'c'.repeat(32)), /b2_company_mismatch/);
const stored = (await db.query('select secret_ref from device_b2_hosts where id=$1',[source])).rows[0];
assert.match(stored.secret_ref,/^b2-secret:/);
const audit = JSON.stringify((await db.query('select payload from device_audit_events')).rows);
assert.equal(audit.includes(packageValue.client_secret),false);
} finally { await rm(secretRoot,{recursive:true,force:true}); }
const schema = (await db.query(`select c.relname as name,obj_description(c.oid) as marker,
(select count(*)::int from pg_attribute a where a.attrelid=c.oid and a.attnum>0 and not a.attisdropped) as columns,
(select count(*)::int from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as constraints,
(select bool_and(k.convalidated) from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as validated,
(select json_agg(json_build_array(a.attname,format_type(a.atttypid,a.atttypmod),a.attnotnull) order by a.attnum)
from pg_attribute a where a.attrelid=c.oid and a.attnum>0 and not a.attisdropped) as fields,
(select json_agg(pg_get_constraintdef(k.oid) order by pg_get_constraintdef(k.oid)) from pg_constraint k where k.conrelid=c.oid and k.contype <> 'n') as definitions
from pg_class c join pg_namespace n on n.oid=c.relnamespace where n.nspname='public'
and c.relname in ('device_b2_hosts','device_b2_host_views','device_b2_contour_links') order by c.relname`)).rows;
if (process.argv[3]) await writeFile(process.argv[3],JSON.stringify(schema,null,2)+'\n');
console.log(JSON.stringify({ ok:true,engine:'PGlite 0.5.8 PostgreSQL WASM',migrations:migrations.length,
checks:['existing schema compatibility','new tables','same-company link','cross-company FK denial','one-contour-one-project uniqueness','actual connect/link repository','private key storage','shared host view in second project','audit excludes secrets'],
productionAcceptance:false,rows:schema.map(({name,columns,constraints})=>({name,columns,constraints})) }));
} finally { await db.close(); }
@@ -8,6 +8,7 @@
"test": "node --test test/*.test.mjs" "test": "node --test test/*.test.mjs"
}, },
"dependencies": { "dependencies": {
"oauth4webapi": "3.8.8",
"pg": "8.22.0" "pg": "8.22.0"
}, },
"engines": { "engines": {
+12
View File
@@ -81,6 +81,7 @@ export function createControlCoreApp({
gatewayIngest = null, gatewayIngest = null,
edgeChannelStatusProvider = null, edgeChannelStatusProvider = null,
typedCommandRuntime = null, typedCommandRuntime = null,
b2Infrastructure = null,
} = {}) { } = {}) {
if (!repository || typeof repository.health !== "function") { if (!repository || typeof repository.health !== "function") {
throw new TypeError("device_repository_required"); throw new TypeError("device_repository_required");
@@ -204,6 +205,17 @@ export function createControlCoreApp({
}); });
} }
if (request.method === "POST" && requestUrl.pathname === "/internal/v1/b2/infrastructure") {
if (!managementApiEnabled || !b2Infrastructure) return writeJson(response, 503, { ok: false, error: "b2_infrastructure_unavailable" });
if (!matchesBearer(request.headers.authorization, managementToken)) return writeJson(response, 401, { ok: false, error: "device_management_auth_required" });
const requestId = String(request.headers["idempotency-key"] || "");
if (!/^[a-f0-9]{32}$/.test(requestId)) throw new TypeError("b2_request_id_invalid");
const actor = managementActorFromHeaders(request.headers);
const input = await readJsonBody(request, 64 * 1024);
const result = await b2Infrastructure.execute(actor, input, requestId);
return writeJson(response, 200, { ok: true, result });
}
const managementCommandKind = managementRoutes.get(requestUrl.pathname); const managementCommandKind = managementRoutes.get(requestUrl.pathname);
if (request.method === "POST" && managementCommandKind) { if (request.method === "POST" && managementCommandKind) {
if (!managementApiEnabled) { if (!managementApiEnabled) {
@@ -0,0 +1,159 @@
import { createHash, timingSafeEqual } from 'node:crypto';
import { lookup } from 'node:dns/promises';
import { request, Agent } from 'node:https';
import { connect } from 'node:tls';
import { isIP } from 'node:net';
import * as oauth from 'oauth4webapi';
export function b2Error(code, statusCode = 400) {
return Object.assign(new Error(code), { statusCode });
}
export function connectionPackage(value) {
if (!value || value.schema !== 'nodedc.b2-connection/v2') throw b2Error('b2_connection_invalid');
const url = new URL(value.endpoint);
if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
throw b2Error('b2_endpoint_invalid');
}
if (!/^[a-f0-9]{64}$/.test(value.fingerprint) || !/^[A-Za-z0-9_-]{1,128}$/.test(value.client_id)
|| typeof value.client_secret !== 'string' || value.client_secret.length < 16 || value.client_secret.length > 1024
|| !/^[a-f0-9]{32}$/.test(value.integration_id) || typeof value.host_id !== 'string'
|| value.host_id.length > 160 || !['host', 'contours'].includes(value.authority)
|| value.issuer !== url.origin + '/' || value.audience !== url.origin + '/v2' || value.scope !== 'b2') {
throw b2Error('b2_connection_invalid');
}
return Object.freeze({ schema: value.schema, endpoint: url.origin, fingerprint: value.fingerprint,
issuer: value.issuer, audience: value.audience, scope: 'b2', host_id: value.host_id,
integration_id: value.integration_id, client_id: value.client_id, client_secret: value.client_secret,
authority: value.authority });
}
export function isPublicIPv4(value) {
if (isIP(value) !== 4) return false;
const [a, b, c] = value.split('.').map(Number);
return !(a === 0 || a === 10 || a === 127 || a >= 224
|| (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254)
|| (a === 172 && b >= 16 && b <= 31) || (a === 192 && (b === 168 || b === 0 || b === 2))
|| (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100)))
|| (a === 203 && b === 0 && c === 113));
}
export function pinnedFetch(pkg, { lookupImpl = lookup, connectImpl = connect, requestImpl = request, timeoutMs = 8000 } = {}) {
return async (input, init = {}) => {
const url = new URL(input instanceof Request ? input.url : input);
if (url.origin !== pkg.endpoint || !(/^\/v2(?:\/|$)/.test(url.pathname) || url.pathname === '/oauth2/token')) {
throw b2Error('b2_endpoint_invalid');
}
const started = Date.now();
let dnsTimer;
let cancelDNS;
let addresses;
try {
addresses = await Promise.race([
lookupImpl(url.hostname, { all: true, family: 4 }),
new Promise((_, reject) => {
cancelDNS = () => reject(b2Error('b2_request_timeout', 504));
dnsTimer = setTimeout(cancelDNS, timeoutMs);
init.signal?.addEventListener('abort', cancelDNS, { once: true });
if (init.signal?.aborted) cancelDNS();
}),
]);
} catch (error) {
if (error?.message?.startsWith('b2_')) throw error;
throw b2Error('b2_host_unavailable', 502);
} finally {
clearTimeout(dnsTimer); init.signal?.removeEventListener('abort', cancelDNS);
}
if (!addresses.length || addresses.some(({ address }) => !isPublicIPv4(address))) throw b2Error('b2_public_endpoint_required');
// Complete and verify TLS before handing the socket to HTTP. No credentials
// are written to a peer whose certificate does not match the imported pin.
const socket = connectImpl({ host: addresses[0].address, port: Number(url.port || 443),
servername: isIP(url.hostname) ? undefined : url.hostname, rejectUnauthorized: false });
const abort = () => socket.destroy(b2Error('b2_request_timeout', 504));
const timer = setTimeout(abort, Math.max(1, timeoutMs - (Date.now() - started)));
init.signal?.addEventListener('abort', abort, { once: true });
try {
if (init.signal?.aborted) throw b2Error('b2_request_timeout', 504);
await new Promise((resolve, reject) => {
socket.once('error', reject);
socket.once('secureConnect', () => {
try {
const cert = socket.getPeerCertificate();
if (!cert.raw || !timingSafeEqual(createHash('sha256').update(cert.raw).digest(), Buffer.from(pkg.fingerprint, 'hex'))) {
throw b2Error('b2_certificate_mismatch', 502);
}
resolve();
} catch (error) { reject(error); }
});
});
return await new Promise((resolve, reject) => {
const headers = Object.fromEntries(new Headers(init.headers));
const body = init.body == null ? null : String(init.body);
if (body) headers['content-length'] = String(Buffer.byteLength(body));
const agent = new Agent({ keepAlive: false, maxSockets: 1 });
agent.createConnection = () => socket;
const req = requestImpl(url, { method: init.method || 'GET', headers, agent }, (res) => {
const chunks = []; let length = 0;
res.on('data', (chunk) => {
length += chunk.length;
if (length > 1024 * 1024) { req.destroy(b2Error('b2_response_too_large', 502)); return; }
chunks.push(chunk);
});
res.on('error', reject);
res.on('end', () => resolve(new Response(Buffer.concat(chunks), {
status: res.statusCode, headers: res.headers,
})));
});
req.on('error', reject);
req.end(body);
});
} catch (error) {
if (error?.message?.startsWith('b2_')) throw error;
throw b2Error('b2_host_unavailable', 502);
} finally {
clearTimeout(timer); init.signal?.removeEventListener('abort', abort); socket.destroy();
}
};
}
export function createB2Client(input, { fetchImpl } = {}) {
const pkg = connectionPackage(input);
const transport = fetchImpl || pinnedFetch(pkg);
const server = { issuer: pkg.issuer, token_endpoint: pkg.endpoint + '/oauth2/token' };
const client = { client_id: pkg.client_id };
let token = null; let expires = 0; let pending = null;
async function accessToken() {
if (token && Date.now() < expires) return token;
if (!pending) pending = (async () => {
const response = await oauth.clientCredentialsGrantRequest(server, client,
oauth.ClientSecretBasic(pkg.client_secret), { scope: 'b2', audience: pkg.audience },
{ [oauth.customFetch]: transport });
const value = await oauth.processClientCredentialsResponse(server, client, response);
token = value.access_token;
expires = Date.now() + Math.max(0, Math.min(value.expires_in || 0, 300) - 15) * 1000;
return token;
})().finally(() => { pending = null; });
return pending;
}
return {
package: pkg,
async call(path, body) {
if (!/^\/v2\//.test(path)) throw b2Error('b2_resource_invalid');
let bearer;
try { bearer = await accessToken(); } catch { throw b2Error('b2_key_rejected', 502); }
const res = await transport(pkg.endpoint + path, {
method: body === undefined ? 'GET' : 'POST',
headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
const value = await res.json().catch(() => null);
if (!res.ok) {
if (res.status === 401 || res.status === 403) { token = null; throw b2Error('b2_access_denied', 403); }
if (res.status === 409) throw b2Error('b2_conflict', 409);
throw b2Error('b2_host_request_failed', 502);
}
if (!value || typeof value !== 'object') throw b2Error('b2_response_invalid', 502);
return value;
},
};
}
@@ -0,0 +1,162 @@
import { randomUUID } from 'node:crypto';
import { applyOntologyManagementCommand } from '../ontology-repository.mjs';
import { normalizeOntologyManagementCommand } from '../ontology-management.mjs';
import { findProjectWithCapability } from '../lifecycle-repository.mjs';
import { assertActorCanManageOwnerScope } from '../project-management.mjs';
import { b2Error, connectionPackage, createB2Client } from './connection.mjs';
function ref(value, prefix) {
if (typeof value !== 'string' || !new RegExp(`^${prefix}:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`).test(value)) throw b2Error('b2_reference_invalid');
return value.slice(prefix.length + 1);
}
function opaque(value) {
if (typeof value !== 'string' || !/^[a-f0-9]{32}$/.test(value)) throw b2Error('b2_identifier_invalid');
return value;
}
function fields(input, names) {
if (Object.keys(input).some((key) => !['projectRef', 'hostRef', 'action', ...names].includes(key))) throw b2Error('b2_unexpected_field');
}
export class B2Infrastructure {
constructor({ pool, secrets, clientFactory = createB2Client }) {
this.pool = pool; this.secrets = secrets; this.clientFactory = clientFactory;
this.clients = new Map();
}
async clientFor(source) {
// Private file refs are immutable. Re-importing/replacing a key creates a
// new ref and therefore cannot reuse the previous OAuth token cache.
const cached = this.clients.get(source.secret_ref);
if (cached) return cached;
const client = this.clientFactory(await this.secrets.read(source.secret_ref));
if (this.clients.size >= 64) this.clients.delete(this.clients.keys().next().value);
this.clients.set(source.secret_ref, client);
return client;
}
async execute(actor, input, requestId) {
const projectId = ref(input.projectRef, 'project');
const hostId = ref(input.hostRef, 'host');
const action = input.action;
const readOnly = ['status', 'devices'].includes(action);
const db = await this.pool.connect();
try {
await db.query('begin');
const project = await findProjectWithCapability(db, actor, projectId, readOnly ? 'infrastructure.read' : 'infrastructure.manage');
// Host management can affect all projects of the company. A project-only
// grant must not turn into company-wide administration.
if (action !== 'devices') assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref });
if (['connect', 'key-issue', 'key-revoke'].includes(action)) {
await findProjectWithCapability(db, actor, projectId, 'credential.manage');
}
const host = (await db.query('select id,host_key,display_name,provider_ref from device_infrastructure_hosts where id=$1 and project_id=$2 and lifecycle_state <> $3 for share',
[hostId, projectId, 'retired'])).rows[0];
if (!host) throw b2Error('b2_project_host_not_found', 404);
const source = (await db.query(`select s.* from device_b2_hosts s join device_b2_host_views v on v.source_id=s.id
where v.host_id=$1 and v.project_id=$2 ${readOnly ? '' : 'for update of s'}`, [hostId, projectId])).rows[0];
let result;
if (action === 'connect') {
fields(input, ['connection']);
const pkg = connectionPackage(typeof input.connection === 'string' ? JSON.parse(input.connection) : input.connection);
if (source && (source.remote_host_id !== pkg.host_id || source.integration_id !== pkg.integration_id)) {
throw b2Error('b2_connection_identity_conflict', 409);
}
const remote = this.clientFactory(pkg);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const status = pkg.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409);
const secret = await this.secrets.save(pkg);
const saved = (await db.query(`insert into device_b2_hosts
(id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref)
values($1,$2,$3,$4,$5,$6,$7,$8)
on conflict(owner_scope_id,remote_host_id) do update set
secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now()
where device_b2_hosts.integration_id=excluded.integration_id
and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint
and device_b2_hosts.authority=excluded.authority returning id`,
[randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0];
if (!saved) throw b2Error('b2_connection_identity_conflict', 409);
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4) on conflict(host_id) do nothing`, [hostId, projectId, project.owner_scope_id, saved.id]);
result = { connected: true, endpoint: pkg.endpoint, authority: pkg.authority };
} else if (!source) {
if (action !== 'status') throw b2Error('b2_host_not_connected', 409);
result = { connected: false };
} else {
const remote = await this.clientFor(source);
const links = (await db.query('select contour_id,project_id from device_b2_contour_links where source_id=$1 order by contour_id', [source.id])).rows;
if (action === 'status') {
fields(input, []);
const value = source.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
result = { connected: true, endpoint: source.endpoint, authority: source.authority,
contours: value.contours || value.items, applications: value.applications || [],
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
} else if (action === 'link') {
fields(input, ['contourId', 'targetProjectRef']);
const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
const contour = opaque(input.contourId);
const permitted = await remote.call('/v2/contours');
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
const current = links.find((link) => link.contour_id === contour);
if (current && current.project_id !== targetId) throw b2Error('b2_contour_already_linked', 409);
await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref)
values($1,$2,$3,$4,$5) on conflict(source_id,contour_id) do nothing`,
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
if (targetId !== projectId) {
const related = (await db.query('select host_id from device_b2_host_views where source_id=$1 and project_id=$2', [source.id, targetId])).rows[0];
if (!related) {
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name,
providerRef: host.provider_ref, externalRef: source.remote_host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]);
}
}
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
} else if (action === 'devices') {
fields(input, []);
const contours = links.filter((link) => link.project_id === projectId);
const items = [];
for (const link of contours) {
const snapshot = await remote.call(`/v2/contours/${link.contour_id}/devices`);
items.push(...snapshot.items.map((device) => ({ id: device.id, name: device.name, number: device.number, active: device.active,
identifier: { masked: '…' + String(device.imei).slice(-5) }, contourId: link.contour_id })));
}
result = { items };
} else {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
if (action === 'contour-create') {
fields(input, ['key', 'name']);
result = await remote.call('/v2/management/contours', { key: input.key, name: input.name });
} else if (action === 'application-create') {
fields(input, ['key', 'name', 'contourId']);
result = await remote.call('/v2/management/applications', {
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
});
} else if (action === 'key-issue') {
fields(input, ['integrationId', 'replace']);
if (typeof input.replace !== 'boolean') throw b2Error('b2_replace_invalid');
// Server reserves this request before generation. No automatic replay.
const packageValue = await remote.call('/v2/management/credentials', {
integration_id: opaque(input.integrationId), replace: input.replace, request_id: requestId,
});
result = { connection: packageValue };
} else if (action === 'key-revoke') {
fields(input, ['clientId']);
if (!/^[A-Za-z0-9_-]{1,128}$/.test(input.clientId)) throw b2Error('b2_client_invalid');
result = await remote.call('/v2/management/credentials/revoke', { client_id: input.clientId });
} else throw b2Error('b2_action_invalid');
}
}
if (!readOnly) await db.query(`insert into device_audit_events(id,event_type,actor_ref,payload,project_id)
values($1,$2,$3,$4::jsonb,$5)`, [randomUUID(), 'b2.' + action, actor.userRef,
JSON.stringify({ projectRef: input.projectRef, hostRef: input.hostRef, requestId }), projectId]);
await db.query('commit');
return result;
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
}
}
@@ -0,0 +1,43 @@
import { constants } from 'node:fs';
import { open, lstat } from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { b2Error, connectionPackage } from './connection.mjs';
// Dedicated persistent private mount provisioned by the canonical installer.
// It is not served, included in images, stored in audit payloads or returned by reads.
export class B2Secrets {
constructor(root) { this.root = root; }
async directory() {
if (!this.root) throw b2Error('b2_private_storage_unavailable', 503);
const info = await lstat(this.root);
if (!info.isDirectory() || info.isSymbolicLink() || (info.mode & 0o077) || info.uid !== process.getuid()) {
throw b2Error('b2_private_storage_invalid', 503);
}
}
path(ref) {
if (!/^b2-secret:[a-f0-9-]{36}$/.test(ref)) throw b2Error('b2_secret_reference_invalid');
return join(this.root, ref.slice(10) + '.json');
}
async save(input) {
const value = connectionPackage(input);
await this.directory();
const ref = 'b2-secret:' + randomUUID();
const file = await open(this.path(ref), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
try { await file.writeFile(JSON.stringify(value)); await file.sync(); } finally { await file.close(); }
const directory = await open(this.root, 'r');
try { await directory.sync(); } finally { await directory.close(); }
return ref;
}
async read(ref) {
await this.directory();
const file = await open(this.path(ref), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
try {
const info = await file.stat();
if (!info.isFile() || info.nlink !== 1 || info.uid !== process.getuid() || (info.mode & 0o077) || info.size > 16384) {
throw b2Error('b2_private_storage_invalid', 503);
}
return connectionPackage(JSON.parse(await file.readFile('utf8')));
} finally { await file.close(); }
}
}
@@ -15,6 +15,9 @@ import { createDeviceGatewayIngest } from "./gateway-ingest.mjs";
import { PostgresDeviceRepository } from "./postgres-repository.mjs"; import { PostgresDeviceRepository } from "./postgres-repository.mjs";
import { createTypedCommandRuntime } from "./typed-command-runtime.mjs"; import { createTypedCommandRuntime } from "./typed-command-runtime.mjs";
import { B2Infrastructure } from "./b2/infrastructure.mjs";
import { B2Secrets } from "./b2/secrets.mjs";
const config = await readConfig(); const config = await readConfig();
const repository = new PostgresDeviceRepository({ const repository = new PostgresDeviceRepository({
databaseUrl: config.databaseUrl, databaseUrl: config.databaseUrl,
@@ -57,6 +60,9 @@ const server = createControlCoreApp({
? () => edgeChannelSupervisor.status() ? () => edgeChannelSupervisor.status()
: null, : null,
typedCommandRuntime, typedCommandRuntime,
b2Infrastructure: process.env.DEVICE_B2_SECRET_ROOT ? new B2Infrastructure({
pool: repository.pool, secrets: new B2Secrets(process.env.DEVICE_B2_SECRET_ROOT),
}) : null,
}); });
server.listen(config.port, config.host, () => { server.listen(config.port, config.host, () => {
@@ -0,0 +1,158 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { mkdtemp, chmod, rm, readFile, symlink } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { connectionPackage, createB2Client, isPublicIPv4, pinnedFetch } from '../src/b2/connection.mjs';
import { B2Secrets } from '../src/b2/secrets.mjs';
import { B2Infrastructure } from '../src/b2/infrastructure.mjs';
const pkg = { schema: 'nodedc.b2-connection/v2', endpoint: 'https://vps.example.invalid:19443',
fingerprint: 'a'.repeat(64), issuer: 'https://vps.example.invalid:19443/',
audience: 'https://vps.example.invalid:19443/v2', scope: 'b2', host_id: 'synthetic-host',
integration_id: 'b'.repeat(32), client_id: 'b2_test', client_secret: 'synthetic-test-secret-not-production', authority: 'host' };
const projectId = '11111111-1111-4111-8111-111111111111';
const otherProject = '22222222-2222-4222-8222-222222222222';
const hostId = '33333333-3333-4333-8333-333333333333';
const ownerId = '44444444-4444-4444-8444-444444444444';
const actor = { userRef: 'user:operator', hubRole: 'owner', groupRefs: [], ownerScopes: [{ scopeKind: 'company', ownerRef: 'company:example' }] };
const source = { id: '55555555-5555-4555-8555-555555555555', owner_scope_id: ownerId,
remote_host_id: pkg.host_id, endpoint: pkg.endpoint, fingerprint: pkg.fingerprint,
integration_id: pkg.integration_id, authority: pkg.authority, secret_ref: 'private-ref' };
function repository({ role = 'owner', links = [], otherOwner = ownerId } = {}) {
const writes = [];
const db = { release() {}, async query(sql, values) {
if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] };
if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner,
lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
if (sql.includes('from device_project_grants')) return { rows: [{ id: 'grant', principal_kind: 'user', principal_ref: actor.userRef,
project_role: role, capability_allow: [], capability_deny: [], lifecycle_state: 'active' }] };
if (sql.includes('from device_infrastructure_hosts')) return { rows: [{ id: hostId }] };
if (sql.includes('from device_b2_hosts')) return { rows: [source] };
if (sql.includes('from device_b2_contour_links')) return { rows: links };
if (sql.startsWith('insert')) { writes.push({ sql, values }); return { rows: [] }; }
throw new Error('unexpected test query: ' + sql);
} };
return { pool: { connect: async () => db }, writes };
}
test('connection import fixes issuer, audience and authority to the supplied host', () => {
assert.equal(connectionPackage(pkg).endpoint, pkg.endpoint);
for (const change of [{ endpoint: 'http://vps.example.invalid' }, { issuer: 'https://other.invalid/' },
{ audience: 'https://other.invalid/v2' }, { fingerprint: 'x' }, { authority: 'owner' }]) {
assert.throws(() => connectionPackage({ ...pkg, ...change }));
}
});
test('standard OAuth client caches access token and does not log or return credentials', async () => {
let tokens = 0; let calls = 0;
const client = createB2Client(pkg, { fetchImpl: async (url, init) => {
if (String(url).endsWith('/oauth2/token')) {
tokens += 1;
const headers = new Headers(init.headers);
assert.match(headers.get('authorization'), /^Basic /);
const body = new URLSearchParams(init.body);
assert.equal(body.get('grant_type'), 'client_credentials');
assert.equal(body.get('audience'), pkg.audience);
return new Response(JSON.stringify({ access_token: 'opaque-test-token', token_type: 'Bearer', expires_in: 300 }), { headers: { 'content-type': 'application/json' } });
}
calls += 1;
assert.equal(new Headers(init.headers).get('authorization'), 'Bearer opaque-test-token');
return new Response('{"items":[]}');
} });
await Promise.all([client.call('/v2/contours'), client.call('/v2/contours')]);
assert.equal(tokens, 1); assert.equal(calls, 2);
await assert.rejects(client.call('/admin/clients'));
});
test('outbound adapter rejects private networks, redirects and foreign origins before TLS', async () => {
for (const address of ['127.0.0.1', '10.1.2.3', '172.16.1.1', '192.168.1.3', '169.254.169.254', '::1', '100.64.1.1']) assert.equal(isPublicIPv4(address), false);
const fetcher = pinnedFetch(pkg, { lookupImpl: async () => [{ address: '127.0.0.1' }], connectImpl: () => assert.fail('must not connect') });
await assert.rejects(fetcher(pkg.endpoint + '/v2/contours'), /b2_public_endpoint_required/);
await assert.rejects(fetcher('https://other.invalid/v2/contours'), /b2_endpoint_invalid/);
await assert.rejects(fetcher(pkg.endpoint + '/admin/clients'), /b2_endpoint_invalid/);
});
test('private file store uses unique 0600 files and rejects permissive roots and symlinks', async () => {
const root = await mkdtemp(join(tmpdir(), 'ndc-b2-secrets-'));
try {
await chmod(root, 0o700);
const store = new B2Secrets(root);
const ref = await store.save(pkg);
assert.equal((await store.read(ref)).client_secret, pkg.client_secret);
assert.equal(JSON.parse(await readFile(store.path(ref), 'utf8')).client_id, pkg.client_id);
const bad = 'b2-secret:66666666-6666-4666-8666-666666666666';
await symlink(store.path(ref), store.path(bad));
await assert.rejects(store.read(bad));
await chmod(root, 0o755);
await assert.rejects(store.read(ref), /b2_private_storage_invalid/);
await assert.rejects(store.save(pkg), /b2_private_storage_invalid/);
} finally { await rm(root, { recursive: true, force: true }); }
});
test('DNS resolution consumes the same bounded request deadline and respects cancellation', async () => {
const stalled = pinnedFetch(pkg, { timeoutMs: 20, lookupImpl: () => new Promise(() => {}),
connectImpl: () => assert.fail('no connection after DNS timeout') });
await assert.rejects(stalled(pkg.endpoint + '/v2/identity'), /b2_request_timeout/);
const controller = new AbortController(); controller.abort();
await assert.rejects(stalled(pkg.endpoint + '/v2/identity', { signal: controller.signal }), /b2_request_timeout/);
});
test('service reuses tokens only for the same immutable secret reference', async () => {
let reads = 0; let created = 0;
const service = new B2Infrastructure({ pool: {}, secrets: { read: async () => { reads += 1; return pkg; } },
clientFactory: () => ({ generation: ++created }) });
assert.equal((await service.clientFor(source)).generation, 1);
assert.equal((await service.clientFor(source)).generation, 1);
assert.equal((await service.clientFor({ ...source, secret_ref: 'new-private-ref' })).generation, 2);
assert.equal(reads, 2);
});
test('project reader sees only explicitly linked fleet, even with a host-management connection', async () => {
const own = 'a'.repeat(32); const other = 'b'.repeat(32);
const repo = repository({ role: 'viewer', links: [{ contour_id: own, project_id: projectId }, { contour_id: other, project_id: otherProject }] });
const calls = [];
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) { calls.push(path); return { items: [] }; } }) });
assert.deepEqual(await service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'devices' }, '1'.repeat(32)), { items: [] });
assert.deepEqual(calls, [`/v2/contours/${own}/devices`]);
await assert.rejects(service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, action: 'contour-create', key: 'foreign', name: 'Foreign' }, '2'.repeat(32)));
});
test('company management refuses linking to another company before any remote request', async () => {
const repo = repository({ otherOwner: '77777777-7777-4777-8777-777777777777' });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: () => assert.fail('no remote mutation') }) });
await assert.rejects(service.execute(actor, { action: 'link', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`,
targetProjectRef: `project:${otherProject}`, contourId: 'c'.repeat(32) }, '3'.repeat(32)), /b2_company_mismatch/);
assert.deepEqual(repo.writes, []);
});
test('TLS pin is verified before any HTTP credential reaches the peer', async () => {
const { execFileSync } = await import('node:child_process');
const { createServer } = await import('node:https');
const tls = await import('node:tls');
const { X509Certificate, createHash } = await import('node:crypto');
const root = await mkdtemp(join(tmpdir(), 'ndc-b2-tls-'));
let server;
try {
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=unit.invalid',
'-keyout', join(root, 'key.pem'), '-out', join(root, 'cert.pem')], { stdio: 'ignore' });
const key = await readFile(join(root, 'key.pem')); const cert = await readFile(join(root, 'cert.pem'));
let received = 0;
server = createServer({ key, cert }, (req, res) => {
received += 1;
assert.equal(req.headers.authorization, 'Bearer synthetic-token');
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"ok":true}');
});
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
const deps = { lookupImpl: async () => [{ address: '8.8.8.8' }],
connectImpl: (options) => tls.connect({ ...options, host: '127.0.0.1', port: server.address().port }) };
const good = { ...pkg, fingerprint: createHash('sha256').update(new X509Certificate(cert).raw).digest('hex') };
const response = await pinnedFetch(good, deps)(pkg.endpoint + '/v2/contours', { headers: { Authorization: 'Bearer synthetic-token' } });
assert.equal(response.status, 200); assert.equal(received, 1);
await assert.rejects(pinnedFetch(pkg, deps)(pkg.endpoint + '/v2/contours', { headers: { Authorization: 'Bearer must-never-arrive' } }), /b2_certificate_mismatch/);
assert.equal(received, 1);
} finally {
if (server?.listening) await new Promise((resolve) => server.close(resolve));
await rm(root, { recursive: true, force: true });
}
});