// Bounded cross-repository qualification on private temporary data, no sockets. // node scripts/qualify-b2-user-flow.mjs // PostgreSQL WASM + real Device Core repository + real VPS SQLite/API/CLI. // OAuth provider, TLS transport, root privilege and hardware are simulated. import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { createInterface } from 'node:readline'; import { readFile, readdir, writeFile, mkdtemp, rm } from 'node:fs/promises'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { resolve, join } from 'node:path'; import { tmpdir } from 'node:os'; import { randomUUID, createHash } from 'node:crypto'; import { PostgresDeviceRepository } from '../services/device-control-core/src/postgres-repository.mjs'; import { normalizeManagementCommand } from '../services/device-control-core/src/project-management.mjs'; import { B2Infrastructure } from '../services/device-control-core/src/b2/infrastructure.mjs'; import { B2Secrets } from '../services/device-control-core/src/b2/vault.mjs'; import { createB2Client } from '../services/device-control-core/src/b2/connection.mjs'; const root = fileURLToPath(new URL('../', import.meta.url)); const vps = resolve(process.argv[3]); const { PGlite } = await import(pathToFileURL(resolve(process.argv[2]))); const db = new PGlite(); const child = spawn(join(vps, '.venv/bin/python3'), [join(root, 'scripts/b2-flow-vps-fixture.py'), vps], { stdio: ['pipe', 'pipe', 'pipe'] }); const waiting = []; let childError = ''; child.stderr.on('data', data => { childError += data; }); createInterface({ input: child.stdout }).on('line', line => waiting.shift()?.resolve(JSON.parse(line))); child.on('exit', code => { for (const item of waiting.splice(0)) item.reject(Error(`VPS fixture exited ${code}: ${childError}`)); }); const bridge = body => new Promise((resolve, reject) => { waiting.push({ resolve, reject }); child.stdin.write(JSON.stringify(body) + '\n'); }); async function command(body) { const result = await bridge(body); assert.equal(result.ok, true, JSON.stringify({ status: result.status, error: result.error, detail: result.detail })); return result.result; } const secretsRoot = await mkdtemp(join(tmpdir(), 'b2-flow-secrets-')); const checks = []; async function check(name, action) { await action(); checks.push({ name, result: 'pass' }); console.log('PASS ' + name); } const pool = { connect: async () => ({ query: (...args) => db.query(...args), release() {} }), query: (...args) => db.query(...args), end: async () => {} }; const repository = new PostgresDeviceRepository({ pool }); const owner = { scopeKind: 'company', ownerRef: 'company:flow-fixture' }; const actor = { userRef: 'user:flow-owner', hubRole: 'owner', groupRefs: [], ownerScopes: [owner] }; const clientFactory = pkg => createB2Client(pkg, { fetchImpl: async (url, init) => { const headers = Object.fromEntries(new Headers(init.headers)); const body = String(url).includes('/oauth2/token') ? null : init.body ? JSON.parse(init.body) : null; const response = await bridge({ kind: 'http', url: String(url), method: init.method || 'GET', headers, body }); return new Response(JSON.stringify(response.ok ? response.result : { error: response.error }), { status: response.ok ? 200 : response.status, headers: { 'content-type': 'application/json' }, }); } }); const service = new B2Infrastructure({ pool, secrets: new B2Secrets(secretsRoot), clientFactory }); const requestId = () => randomUUID().replaceAll('-', ''); async function management(commandKind, input, as = actor) { const command = normalizeManagementCommand(commandKind, input); return (await repository.executeManagementCommand({ actor: as, commandKind, command, idempotencyKey: requestId(), requestDigest: 'sha256:' + createHash('sha256').update(JSON.stringify(command)).digest('hex') })).result; } const execute = (common, action, fields = {}, id = requestId(), as = actor) => service.execute(as, { ...common, action, ...fields }, id); const cli = args => command({ kind: 'cli', args }); let projectA, projectB, projectC, host, contour, pkg, appA, appB, appClientA, appClientB, device; let common, second, third; try { await check('fresh schema and project creation use the real management repository', async () => { for (const name of (await readdir(join(root, 'services/device-control-core/migrations'))).filter(name => name.endsWith('.sql')).sort()) { await db.exec(await readFile(join(root, 'services/device-control-core/migrations', name), 'utf8')); } await db.exec(await readFile(join(root, 'deployment/device-b2-foundation-v1.sql'), 'utf8')); await management('owner_scope.ensure', { ...owner, displayName: 'Flow fixture' }); for (const [key, name] of [['first', 'Project A'], ['second', 'Project B'], ['unlinked', 'Project C']]) { const value = await management('project.ensure', { ...owner, projectKey: key, name }); if (key === 'first') projectA = value.project.projectRef; if (key === 'second') projectB = value.project.projectRef; if (key === 'unlinked') projectC = value.project.projectRef; } assert.equal((await repository.listAccessibleProjects(actor)).length, 3); }); await check('empty VPS registers through onboarding and repeated import reuses host', async () => { pkg = await command({ kind: 'bootstrap' }); host = await execute({ projectRef: projectA }, 'register-host', { name: 'New ARNavi VPS', connection: pkg }); const repeated = await execute({ projectRef: projectA }, 'register-host', { name: 'New ARNavi VPS', connection: pkg }); assert.equal(repeated.hostRef, host.hostRef); common = { projectRef: projectA, hostRef: host.hostRef }; const status = await execute(common, 'status'); assert.deepEqual(status.contours, []); assert.equal(status.sharedProjects, false); }); await check('new contour creates and binds with stable retry identity', async () => { const id = requestId(); contour = (await execute(common, 'contour-connect', { name: 'Shared fleet', targetProjectRef: projectA }, id)).contourId; assert.equal((await execute(common, 'contour-connect', { name: 'Shared fleet', targetProjectRef: projectA }, id)).contourId, contour); assert.equal((await execute(common, 'status')).contours.length, 1); }); await check('old schema refuses sharing explicitly and forward migration preserves old links', async () => { await assert.rejects(execute(common, 'link', { contourId: contour, targetProjectRef: projectB }), /b2_shared_projects_migration_required/); const before = (await db.query('select * from device_b2_contour_links')).rows; await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.sql'), 'utf8')); assert.deepEqual((await db.query('select * from device_b2_contour_links')).rows, before); assert.equal((await execute(common, 'status')).sharedProjects, true); }); await check('one contour links to two projects with separate host views and idempotent edges', async () => { await execute(common, 'link', { contourId: contour, targetProjectRef: projectB }); await execute(common, 'link', { contourId: contour, targetProjectRef: projectB }); const links = (await execute(common, 'status')).links; assert.equal(links.length, 2); const view = (await db.query('select host_id from device_b2_host_views where project_id=$1', [projectB.slice(8)])).rows[0]; second = { projectRef: projectB, hostRef: 'host:' + view.host_id }; assert.notEqual(second.hostRef, common.hostRef); assert.equal((await db.query('select * from device_b2_hosts')).rows.length, 1); }); await check('unlinked project can add the shared VPS without seeing another fleet', async () => { const other = await execute({ projectRef: projectC }, 'register-host', { name: 'Same VPS', connection: pkg }); third = { projectRef: projectC, hostRef: other.hostRef }; assert.deepEqual((await execute(third, 'inventory')).items, []); }); await check('two independent application packages connect to the same contour', async () => { appA = await execute(common, 'application-connect', { name: 'Partner management', contourId: contour, access: 'manage' }); appB = await execute(common, 'application-connect', { name: 'Partner observer', contourId: contour, access: 'read' }); assert.notEqual(appA.connection.client_id, appB.connection.client_id); assert.notEqual(appA.id, appB.id); appClientA = clientFactory(appA.connection); appClientB = clientFactory(appB.connection); assert.deepEqual((await appClientA.call('/v2/contours')).items.map(item => item.id), [contour]); assert.deepEqual((await appClientB.call('/v2/contours')).items.map(item => item.id), [contour]); await assert.rejects(appClientA.call('/v2/management'), /b2_access_denied/); await assert.rejects(execute(third, 'register-host', { name: 'Wrong role', connection: appA.connection }), /b2_host_management_required/); }); await check('manual device enrollment works and duplicate retry creates no second device', async () => { const options = await execute(common, 'enrollment-options'); assert.equal(options.hosts[0].contours[0].id, contour); const fields = { contourId: contour, request: { action: 'register', name: 'Synthetic ARNavi B2', imei: '123456789012345', number: 1001 } }; device = await execute(common, 'enrollment', fields); assert.deepEqual(await execute(common, 'enrollment', fields), device); await assert.rejects(appClientB.call(`/v2/contours/${contour}/enrollment`, fields.request), /b2_access_denied/); assert.equal((await appClientA.call(`/v2/contours/${contour}/devices`)).items.length, 1); }); await check('both projects see the same device while an unlinked project sees none', async () => { const a = await execute(common, 'inventory'), b = await execute(second, 'inventory'), c = await execute(third, 'inventory'); assert.equal(a.items[0].id, b.items[0].id); assert.equal(a.items.length, 1); assert.equal(b.items.length, 1); assert.equal(c.items.length, 0); assert.equal(JSON.stringify(a).includes('123456789012345'), false); await assert.rejects(execute(third, 'enrollment', { contourId: contour, request: { action: 'catalog' } }), /b2_access_denied/); }); await check('independent application cursors cannot consume or acknowledge each other', async () => { const base = `/v2/contours/${contour}/subscriptions`; const a = await appClientA.call(base, { stream: 'registry' }); const b = await appClientB.call(base, { stream: 'registry' }); assert.notEqual(a.id, b.id); const first = await appClientA.call(`${base}/${a.id}`); assert.ok(first.items.length > 0); await appClientA.call(`${base}/${a.id}/ack`, { through: first.through }); assert.equal((await appClientA.call(`${base}/${a.id}`)).items.length, 0); assert.equal((await appClientB.call(`${base}/${b.id}`)).items.length, first.items.length); await assert.rejects(appClientB.call(`${base}/${a.id}`), /b2_access_denied/); }); await check('external CLI contours appear in catalogue without automatic local access grants', async () => { const before = (await repository.listAccessibleProjects(actor)).length; for (let n = 1; n <= 3; n++) await cli(['contour-create', `external-${n}`, '--name', `External ${n}`]); const status = await execute(common, 'status'); assert.equal(status.contours.length, 4); assert.equal(status.links.length, 2); assert.equal((await repository.listAccessibleProjects(actor)).length, before); const external = status.contours.find(item => item.key === 'external-1'); await assert.rejects(appClientA.call(`/v2/contours/${external.id}/devices`), /b2_access_denied/); await execute(common, 'link', { contourId: external.id, targetProjectRef: projectA }); assert.equal((await execute(common, 'enrollment-options')).hosts[0].contours.length, 2); const application = await cli(['app-create', 'external-client', '--name', 'External client', '--grant', `${external.id}:manage`]); const connection = await cli(['key-issue', application.id]); const client = clientFactory(connection); await client.call(`/v2/contours/${external.id}/enrollment`, { action: 'register', name: 'External B2', imei: '123456789012346', number: 1002 }); assert.equal((await execute(common, 'inventory')).items.length, 2); assert.equal((await execute(second, 'inventory')).items.length, 1); }); await check('rotation invalidates the old key and preserves application identity and fleet', async () => { const replacement = await execute(common, 'key-issue', { integrationId: appA.id, replace: true }); await assert.rejects(appClientA.call('/v2/contours'), /b2_access_denied/); appClientA = clientFactory(replacement.connection); assert.equal(replacement.connection.integration_id, appA.id); assert.equal((await appClientA.call(`/v2/contours/${contour}/devices`)).items.length, 1); assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1); }); await check('lost key response is not replayed and explicit reissue recovers safely', async () => { const id = requestId(), fields = { name: 'Lost response', contourId: contour, access: 'read' }; const first = await execute(common, 'application-connect', fields, id); await assert.rejects(execute(common, 'application-connect', fields, id), /b2_conflict/); const status = await execute(common, 'status'); assert.equal(status.applications.filter(app => app.id === first.id).length, 1); const replacement = await execute(common, 'key-issue', { integrationId: first.id, replace: true }); await assert.rejects(clientFactory(first.connection).call('/v2/contours'), /b2_access_denied/); assert.equal((await clientFactory(replacement.connection).call('/v2/contours')).items.length, 1); }); await check('application deletion revokes access without deleting devices or other clients', async () => { await execute(common, 'application-delete', { integrationId: appA.id }); await assert.rejects(appClientA.call('/v2/contours'), /b2_access_denied/); assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1); assert.equal((await execute(second, 'inventory')).items.length, 1); }); await check('cross-company assignment is rejected and cannot leak a host view', async () => { const otherOwner = { scopeKind: 'company', ownerRef: 'company:foreign-fixture' }; const otherActor = { ...actor, ownerScopes: [owner, otherOwner] }; await management('owner_scope.ensure', { ...otherOwner, displayName: 'Foreign' }, otherActor); const value = await management('project.ensure', { ...otherOwner, projectKey: 'foreign', name: 'Foreign project' }, otherActor); await assert.rejects(execute(common, 'link', { contourId: contour, targetProjectRef: value.project.projectRef }, requestId(), otherActor), /b2_company_mismatch/); assert.equal((await db.query('select * from device_b2_host_views where project_id=$1', [value.project.projectRef.slice(8)])).rows.length, 0); }); await check('rollback refuses to discard multiple project bindings', async () => { await assert.rejects(db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.rollback.sql'), 'utf8')), /rollback_would_lose_links/); await db.exec('rollback'); assert.equal((await execute(common, 'status')).links.filter(link => link.contourId === contour).length, 2); }); await check('unlink is local to one project and leaves external keys and other project intact', async () => { await execute(common, 'unlink', { contourId: contour, targetProjectRef: projectB }); await execute(common, 'unlink', { contourId: contour, targetProjectRef: projectB }); assert.equal((await execute(second, 'inventory')).items.length, 0); assert.equal((await execute(common, 'inventory')).items.length, 2); assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1); }); await check('VPS restart preserves contours devices credentials and project mappings', async () => { await command({ kind: 'restart' }); assert.equal((await execute(common, 'status')).contours.length, 4); assert.equal((await execute(common, 'inventory')).items.length, 2); assert.equal((await appClientB.call(`/v2/contours/${contour}/devices`)).items.length, 1); }); await check('audit and database metadata never contain exported credential secrets', async () => { const audit = JSON.stringify((await db.query('select payload from device_audit_events')).rows); const sources = JSON.stringify((await db.query('select * from device_b2_hosts')).rows); for (const secret of [pkg.client_secret, appA.connection.client_secret, appB.connection.client_secret]) { assert.equal(audit.includes(secret), false); assert.equal(sources.includes(secret), false); } }); await check('lossless rollback and reapplication preserve remaining associations', async () => { const before = (await db.query('select * from device_b2_contour_links order by contour_id,project_id')).rows; await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.rollback.sql'), 'utf8')); await db.exec(await readFile(join(root, 'deployment/device-b2-shared-contours-v1.sql'), 'utf8')); assert.deepEqual((await db.query('select * from device_b2_contour_links order by contour_id,project_id')).rows, before); }); const report = { ok: true, checkedAt: new Date().toISOString(), checks, engine: 'PGlite PostgreSQL WASM and VPS SQLite', real: ['Device Core management repository', 'B2Infrastructure', 'OAuth client library', 'VPS SharedAPI', 'VPS CLI parser and domain', 'credential issue/revoke domain', 'private file vault'], simulated: ['OAuth provider', 'TLS transport', 'CLI root privilege', 'hardware'], productionMutation: false, cleanUbuntuInstallation: false, boundedDevices: 2, boundedExternalContours: 3 }; await writeFile(resolve(process.argv[4]), JSON.stringify(report, null, 2) + '\n'); console.log(JSON.stringify({ ok: true, checks: checks.length })); } finally { child.stdin.end(); await new Promise(resolve => child.once('exit', resolve)); await db.close(); await rm(secretsRoot, { recursive: true, force: true }); }