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
+12
View File
@@ -81,6 +81,7 @@ export function createControlCoreApp({
gatewayIngest = null,
edgeChannelStatusProvider = null,
typedCommandRuntime = null,
b2Infrastructure = null,
} = {}) {
if (!repository || typeof repository.health !== "function") {
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);
if (request.method === "POST" && managementCommandKind) {
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 { createTypedCommandRuntime } from "./typed-command-runtime.mjs";
import { B2Infrastructure } from "./b2/infrastructure.mjs";
import { B2Secrets } from "./b2/secrets.mjs";
const config = await readConfig();
const repository = new PostgresDeviceRepository({
databaseUrl: config.databaseUrl,
@@ -57,6 +60,9 @@ const server = createControlCoreApp({
? () => edgeChannelSupervisor.status()
: null,
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, () => {