Restructure ARNavi contour UX and expose project-scoped VPS inventory
Device Core qualification / qualify (push) Successful in 7m42s

This commit is contained in:
DCCONSTRUCTIONS
2026-09-30 19:35:18 +03:00
parent 1bf3ee6d41
commit c0487ca17b
17 changed files with 508 additions and 388 deletions
@@ -32,7 +32,46 @@ export class B2Infrastructure {
this.clients.set(source.secret_ref, client);
return client;
}
async inventory(actor, input) {
fields(input, []);
const projectId = ref(input.projectRef, 'project');
const db = await this.pool.connect();
let sources;
try {
await db.query('begin');
await findProjectWithCapability(db, actor, projectId, 'inventory.read');
sources = (await db.query(`select s.*, v.host_id, h.display_name,
coalesce((select json_agg(l.contour_id order by l.contour_id) from device_b2_contour_links l
where l.source_id=s.id and l.project_id=v.project_id), '[]'::json) as contour_ids
from device_b2_hosts s join device_b2_host_views v on v.source_id=s.id
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
where v.project_id=$1 and h.lifecycle_state='active'`, [projectId])).rows;
await db.query('commit');
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
// Release the database transaction before waiting for any external host.
const results = await Promise.all(sources.map(async (source) => {
const host = { hostRef: `host:${source.host_id}`, name: source.display_name,
endpoint: source.endpoint, contours: source.contour_ids.length };
try {
const remote = await this.clientFor(source);
const identity = await remote.call('/v2/identity');
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
const items = [];
for (const contourId of source.contour_ids) {
const snapshot = await remote.call(`/v2/contours/${opaque(contourId)}/devices`);
items.push(...snapshot.items.map((device) => ({ id: device.id, name: device.name, number: device.number,
active: device.active, identifier: { masked: '…' + String(device.imei).slice(-5) },
contourId, hostRef: host.hostRef, hostName: host.name })));
}
return { host: { ...host, reachable: true, checkedAt: new Date().toISOString(), devices: items.length }, items };
} catch {
return { host: { ...host, reachable: false, checkedAt: new Date().toISOString(), devices: null }, items: [] };
}
}));
return { items: results.flatMap((result) => result.items), hosts: results.map((result) => result.host) };
}
async execute(actor, input, requestId) {
if (input.action === 'inventory') return this.inventory(actor, input);
const projectId = ref(input.projectRef, 'project');
const hostId = ref(input.hostRef, 'host');
const action = input.action;
@@ -44,6 +44,16 @@ export function normalizeLifecycleManagementCommand(kind, input) {
});
}
if (kind === "device.update" && Object.prototype.hasOwnProperty.call(input, "archived")) {
assertAllowedKeys(input, ["projectRef", "deviceRef", "archived"]);
if (typeof input.archived !== "boolean") throw new TypeError("device_archive_state_invalid");
return Object.freeze({
projectId: normalizeEntityRef(input.projectRef, "project"),
deviceId: normalizeEntityRef(input.deviceRef, "device"),
archived: input.archived,
});
}
if (kind === "device.update") {
assertAllowedKeys(input, [
"projectRef",
@@ -91,7 +91,24 @@ export async function authorizeLifecycleManagementReplay(
}
}
async function archiveDevice(client, actor, command) {
const project = await findProjectWithCapability(client, actor, command.projectId, "project.manage");
const current = await findDeviceForUpdate(client, command.deviceId);
if (current.project_id !== project.id) throw domainError("device_update_project_mismatch", 409);
// Archive is a reversible registry operation. It never closes a live channel.
if (!["claimed", "suspended"].includes(current.lifecycle_state)) throw domainError("device_archive_lifecycle_blocked", 409);
const sessions = await client.query(`select exists(select 1 from device_sessions where device_id=$1
and lifecycle_state in ('connecting','online','closing')) as active`, [current.id]);
if (sessions.rows[0]?.active) throw domainError("device_archive_active_session", 409);
const state = command.archived ? "suspended" : "claimed";
await client.query('update device_instances set lifecycle_state=$3, updated_at=now() where id=$1 and project_id=$2', [current.id, project.id, state]);
await addAudit(client, { eventType: command.archived ? "device.archived" : "device.restored", actorRef: actor.userRef,
projectId: project.id, deviceId: current.id, payload: { deviceRef: `device:${current.id}`, lifecycleState: state } });
return { archived: command.archived };
}
async function updateDevice(client, actor, command) {
if (typeof command.archived === "boolean") return archiveDevice(client, actor, command);
const project = await findProjectWithCapability(
client,
actor,
@@ -81,6 +81,16 @@ export function normalizeOntologyManagementCommand(kind, input) {
});
}
if (kind === "infrastructure_host.ensure" && Object.prototype.hasOwnProperty.call(input, "archived")) {
assertAllowedKeys(input, ["projectRef", "hostRef", "archived"]);
if (typeof input.archived !== "boolean") throw new TypeError("device_archive_state_invalid");
return Object.freeze({
projectId: normalizeEntityRef(input.projectRef, "project"),
hostId: normalizeEntityRef(input.hostRef, "host"),
archived: input.archived,
});
}
if (kind === "infrastructure_host.ensure") {
assertAllowedKeys(input, [
"projectRef", "hostKey", "displayName", "providerRef", "externalRef",
@@ -201,7 +201,18 @@ async function closeAssetBinding(client, actor, project, command) {
return { closed: true, assetBinding: assetBindingView(row) };
}
async function archiveHost(client, actor, project, command) {
const result = await client.query(`update device_infrastructure_hosts set lifecycle_state=$3, updated_at=now()
where id=$1 and project_id=$2 and lifecycle_state in ('active','suspended') returning *`,
[command.hostId, project.id, command.archived ? 'suspended' : 'active']);
const row = requireRow(result, "device_host_not_archivable", 409);
await addAudit(client, { actor, project, eventType: command.archived ? 'infrastructure_host.archived' : 'infrastructure_host.restored',
payload: { hostRef: `host:${row.id}`, lifecycleState: row.lifecycle_state } });
return { archived: command.archived };
}
async function ensureHost(client, actor, project, command) {
if (typeof command.archived === "boolean") return archiveHost(client, actor, project, command);
const result = await client.query(
`insert into device_infrastructure_hosts (
id, owner_scope_id, project_id, host_key, display_name, provider_ref,
@@ -0,0 +1,50 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { normalizeDeviceManagementCommand } from '../src/management-command.mjs';
import { applyLifecycleManagementCommand, authorizeLifecycleManagementReplay } from '../src/lifecycle-repository.mjs';
import { applyOntologyManagementCommand } from '../src/ontology-repository.mjs';
const projectId='11111111-1111-4111-8111-111111111111', entityId='22222222-2222-4222-8222-222222222222';
const actor={ userRef:'user:operator', hubRole:'owner', groupRefs:[], ownerScopes:[] };
function db({role='owner', entityProject=projectId, active=false}={}) {
const writes=[];
return { writes, async query(sql, values) {
if (sql.includes('from device_projects')) return {rows:[{id:projectId,owner_scope_id:'owner',scope_kind:'company',owner_ref:'company:test',lifecycle_state:'active',owner_lifecycle_state:'active'}]};
if (sql.includes('from device_project_grants')) return {rows:[{id:'grant',principal_kind:'user',principal_ref:actor.userRef,project_role:role,capability_allow:[],capability_deny:[],lifecycle_state:'active'}]};
if (sql.includes('from device_instances')) return {rows:[{id:entityId,project_id:entityProject,lifecycle_state:'claimed'}]};
if (sql.includes('from device_sessions')) return {rows:[{active}]};
if (sql.startsWith('update device_infrastructure_hosts')) { writes.push({sql,values}); return {rows:entityProject === projectId ? [{id:entityId,lifecycle_state:values[2]}] : []}; }
if (sql.startsWith('update') || sql.includes('insert into device_audit_events')) {writes.push({sql,values});return {rows:[]};}
throw Error('Unexpected query '+sql);
}};
}
for (const [kind, ref, apply] of [['device.update','deviceRef',applyLifecycleManagementCommand],['infrastructure_host.ensure','hostRef',applyOntologyManagementCommand]]) {
test(`${kind} archive and restore preserve identity and private bindings`,async()=>{
for (const archived of [true,false]) {
const command=normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived});
const client=db(); const result=await apply(client,{actor,commandKind:kind,command});
assert.equal(result.archived,archived);
const update=client.writes.find((write)=>write.sql.startsWith('update'));
assert.match(update.sql,/where id\s*=\s*\$1 and project_id\s*=\s*\$2/);
assert.equal(update.sql.includes('management_credential_ref'),false);
assert.equal(update.sql.includes('display_name'),false);
assert.equal(update.values[2],archived?'suspended':ref==='hostRef'?'active':'claimed');
assert.ok(client.writes.some((write)=>write.sql.includes('device_audit_events')));
}
});
test(`${kind} rejects unauthorized and cross-project archive`,async()=>{
const command=normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:true});
for (const options of [{role:'viewer'},{entityProject:'different'}]) {
const client=db(options); await assert.rejects(apply(client,{actor,commandKind:kind,command}));
if (options.role) assert.equal(client.writes.length,0);
}
assert.throws(()=>normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:'true'}));
assert.throws(()=>normalizeDeviceManagementCommand(kind,{projectRef:`project:${projectId}`,[ref]:`${ref==='hostRef'?'host':'device'}:${entityId}`,archived:true,displayName:'unexpected'}));
});
}
test('archive cannot interrupt an active device and replay rechecks its project',async()=>{
const command=normalizeDeviceManagementCommand('device.update',{projectRef:`project:${projectId}`,deviceRef:`device:${entityId}`,archived:true});
const client=db({active:true});
await assert.rejects(applyLifecycleManagementCommand(client,{actor,commandKind:'device.update',command}),/device_archive_active_session/);
assert.equal(client.writes.length,0);
await assert.rejects(authorizeLifecycleManagementReplay(db({entityProject:'different'}),{actor,commandKind:'device.update',command}),/project_mismatch/);
});
@@ -156,3 +156,42 @@ test('TLS pin is verified before any HTTP credential reaches the peer', async ()
await rm(root, { recursive: true, force: true });
}
});
test('project inventory releases DB before networking and never exposes other projects or credentials', async () => {
const contour = 'c'.repeat(32); let released = false; const calls = [];
const repo = repository({ role: 'viewer' });
const db = await repo.pool.connect(); const original = db.query;
db.release = () => { released = true; };
db.query = async (sql, values) => {
if (sql.includes('from device_b2_hosts')) {
assert.match(sql, /v.project_id=\$1 and h.lifecycle_state='active'/);
assert.match(sql, /l.project_id=v.project_id/);
assert.deepEqual(values, [projectId]);
return { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [contour] }] };
}
return original(sql, values);
};
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path) {
assert.equal(released, true); calls.push(path);
return path === '/v2/identity' ? { host_id: pkg.host_id } : { items: [{ id: 'device', imei: '123456789012345', number: 1, name: 'B2', active: true }] };
} }) });
const result = await service.execute({ ...actor, hubRole: 'member' }, { projectRef: `project:${projectId}`, action: 'inventory' });
assert.deepEqual(calls, ['/v2/identity', `/v2/contours/${contour}/devices`]);
assert.equal(result.items[0].identifier.masked, '…12345');
assert.equal(result.hosts[0].reachable, true);
assert.equal(result.hosts[0].devices, 1);
const json = JSON.stringify(result);
for (const secret of [pkg.client_secret, source.secret_ref, '123456789012345', otherProject]) assert.equal(json.includes(secret), false);
assert.equal('online' in result.items[0], false);
});
test('unreachable or mismatched host is reported as unavailable, not an empty healthy fleet', async () => {
for (const fail of [false, true]) {
const repo = repository(); const db = await repo.pool.connect(); const original = db.query;
db.query = (sql, values) => sql.includes('from device_b2_hosts') ? { rows: [{ ...source, host_id: hostId, display_name: 'VPS', contour_ids: [] }] } : original(sql, values);
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call() { if (fail) throw Error('contains-private-details'); return { host_id: 'wrong-host' }; } }) });
const result = await service.execute(actor, { projectRef: `project:${projectId}`, action: 'inventory' });
assert.equal(result.hosts[0].reachable, false); assert.equal(result.hosts[0].devices, null);
assert.deepEqual(result.items, []); assert.equal(JSON.stringify(result).includes('private-details'), false);
}
});