224 lines
16 KiB
JavaScript
224 lines
16 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import https from 'node:https';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { randomBytes, randomUUID, createCipheriv, createDecipheriv, X509Certificate } from 'node:crypto';
|
|
import { fixture } from './helpers.mjs';
|
|
import { CompanionGateway } from '../src/server/companion-gateway.mjs';
|
|
import { DeviceRegistry } from '../src/core/companion/device-registry.mjs';
|
|
import { CompanionTLS } from '../src/core/companion/tls-authority.mjs';
|
|
import { approvalBinding, companionHash } from '../src/shared/contracts/companion.mjs';
|
|
|
|
function setup(t) {
|
|
const value = fixture(t), host = { instanceId: randomUUID(), ownerId: randomUUID(), userSid: 'fixture-current-user', pid: process.pid, createdAt: new Date().toISOString() };
|
|
let clock = Date.now();
|
|
const registry = new DeviceRegistry(value.store, () => host, { clock: () => clock });
|
|
const grant = { projectIds: [value.project.id], permissions: { observe: true, approve: false, stop: false }, expiresInHours: 24 };
|
|
registry.initialize();
|
|
return { ...value, registry, grant, host, advance: ms => { clock += ms; } };
|
|
}
|
|
function testSealing() {
|
|
// This explicit dependency is confined to tests. Product code always uses
|
|
// Windows CurrentUser DPAPI and has no plaintext/non-Windows fallback.
|
|
const key = randomBytes(32);
|
|
return { protect: (bytes, entropy) => {
|
|
const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', key, iv); cipher.setAAD(entropy);
|
|
const encrypted = Buffer.concat([cipher.update(bytes), cipher.final()]); return Buffer.concat([iv, cipher.getAuthTag(), encrypted]);
|
|
}, unprotect: (bytes, entropy) => {
|
|
const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12)); decipher.setAuthTag(bytes.subarray(12, 28)); decipher.setAAD(entropy);
|
|
return Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]);
|
|
} };
|
|
}
|
|
async function running(t) {
|
|
const f = setup(t), runtime = { waiters: new Map(), decide() { throw new Error('No approval'); }, async stop() {} };
|
|
const appDirectory = path.join(f.root, 'app'); fs.mkdirSync(path.join(appDirectory, 'dist-client'), { recursive: true });
|
|
fs.writeFileSync(path.join(appDirectory, 'dist-client', 'mobile.html'), '<!doctype html><title>Test mobile entry</title>');
|
|
fs.writeFileSync(path.join(appDirectory, 'dist-client', 'mobile-assets.json'), '[]');
|
|
const gateway = new CompanionGateway({ store: f.store, runtime, appDirectory, identity: () => f.host, redact: value => String(value).replaceAll('fixture-secret', '[REDACTED]') },
|
|
{ tlsOptions: testSealing(), allowLoopback: true });
|
|
f.onCleanup(() => gateway.close());
|
|
assert.equal(gateway.status().enabled, false);
|
|
await gateway.start({ address: '127.0.0.1', port: 0 });
|
|
const ca = gateway.registry.read().tls.certificate;
|
|
const request = (route, data, { cookie = '', origin = gateway.origin, headers = {} } = {}) => new Promise((resolve, reject) => {
|
|
const req = https.request(gateway.origin + route, { ca, servername: '', method: data === undefined ? 'GET' : 'POST', headers: {
|
|
...(cookie ? { Cookie: cookie } : {}), ...(origin ? { Origin: origin } : {}), ...(data === undefined ? {} : { 'Content-Type': 'application/json' }), Connection: 'close', ...headers } }, res => {
|
|
const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => {
|
|
const text = Buffer.concat(chunks).toString('utf8'); let body; try { body = JSON.parse(text); } catch { body = text; }
|
|
resolve({ status: res.statusCode, headers: res.headers, body });
|
|
});
|
|
}); req.on('error', reject); req.end(data === undefined ? undefined : JSON.stringify(data));
|
|
});
|
|
async function pair(grant = f.grant) {
|
|
const ticket = await gateway.pairing(grant), token = new URLSearchParams(new URL(ticket.url).hash.slice(1)).get('pair');
|
|
const result = await request('/mobile-api/pair', { token, name: '测试iPhone' });
|
|
assert.equal(result.status, 201, JSON.stringify(result.body));
|
|
const cookie = result.headers['set-cookie'][0].split(';')[0]; return { ticket, token, cookie, device: result.body.device };
|
|
}
|
|
return { ...f, gateway, runtime, request, pair };
|
|
}
|
|
|
|
test('pairing is short lived, single-use, generation-bound and validates exact permissions', t => {
|
|
const f = setup(t), pair = f.registry.pair(f.grant, 'generation');
|
|
assert.match(pair.token, /^[A-Za-z0-9_-]{43}$/);
|
|
assert.throws(() => f.registry.consume(pair.token, 'phone', 'other'), /无效/);
|
|
const accepted = f.registry.consume(pair.token, 'phone', 'generation');
|
|
assert.equal(f.registry.authenticate(accepted.token).id, accepted.device.id);
|
|
assert.throws(() => f.registry.consume(pair.token, 'phone', 'generation'), /无效/);
|
|
const next = f.registry.pair(f.grant, 'generation'); f.advance(120001);
|
|
assert.throws(() => f.registry.consume(next.token, 'phone', 'generation'), /过期/);
|
|
assert.throws(() => f.registry.pair({ ...f.grant, permissions: { ...f.grant.permissions, execute: true } }, 'g'), /字段/);
|
|
assert.throws(() => f.registry.pair({ ...f.grant, projectIds: [randomUUID()] }, 'g'), /项目/);
|
|
});
|
|
|
|
test('device transaction failure neither consumes the ticket nor leaves a credential', t => {
|
|
const f = setup(t), pair = f.registry.pair(f.grant, 'g');
|
|
f.store.storage.faultInjector = () => { throw new Error('disk fixture'); };
|
|
assert.throws(() => f.registry.consume(pair.token, 'phone', 'g'), /disk fixture/);
|
|
assert.equal(f.registry.view().devices.length, 0);
|
|
f.store.storage.faultInjector = null;
|
|
assert.equal(f.registry.consume(pair.token, 'phone', 'g').device.name, 'phone');
|
|
});
|
|
|
|
test('devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority', t => {
|
|
const f = setup(t), pair = f.registry.pair(f.grant, 'g'), accepted = f.registry.consume(pair.token, 'phone', 'g');
|
|
const device = f.registry.authenticate(accepted.token);
|
|
assert.throws(() => f.registry.authorize(device, randomUUID()), /权限/);
|
|
assert.throws(() => f.registry.authorize(device, f.project.id, 'stop'), /权限/);
|
|
const rotated = f.registry.rotate(device);
|
|
assert.throws(() => f.registry.authenticate(accepted.token), /轮换/);
|
|
const current = f.registry.authenticate(rotated); f.registry.revoke(current.id, current.revision);
|
|
assert.throws(() => f.registry.authenticate(rotated), /撤销/);
|
|
const fresh = f.registry.consume(f.registry.pair(f.grant, 'g').token, 'other', 'g'); f.advance(25 * 3600000);
|
|
assert.throws(() => f.registry.authenticate(fresh.token), /到期/);
|
|
f.host.instanceId = randomUUID(); assert.throws(() => f.registry.authenticate(fresh.token), /宿主/);
|
|
});
|
|
|
|
test('persistent registry stores hashes and a bounded audit, never raw credentials', t => {
|
|
const f = setup(t), ticket = f.registry.pair(f.grant, 'g'), accepted = f.registry.consume(ticket.token, 'iPhone', 'g');
|
|
const text = JSON.stringify(f.store.storage.meta('mobileCompanion'));
|
|
assert.ok(!text.includes(ticket.token) && !text.includes(accepted.token));
|
|
const nextHost = { ...f.host, instanceId: randomUUID() };
|
|
const registry = new DeviceRegistry(f.store, () => nextHost);
|
|
assert.equal(registry.authenticate(accepted.token).name, 'iPhone');
|
|
assert.ok(!JSON.stringify(registry.view()).includes('credentialHash'));
|
|
});
|
|
|
|
test('real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint', async t => {
|
|
const f = await running(t), first = f.gateway.tls.publicCertificate();
|
|
assert.equal(new X509Certificate(first.bytes).ca, true);
|
|
assert.equal(companionHash(first.bytes), first.sha256);
|
|
assert.equal((await f.request('/')).status, 200);
|
|
const record = f.gateway.registry.read().tls;
|
|
assert.ok(!Buffer.from(record.ciphertext, 'base64').toString('utf8').includes('pkcs8'));
|
|
const origin = f.gateway.origin; await f.gateway.close();
|
|
await f.gateway.start({ address: '127.0.0.1', port: Number(new URL(origin).port) });
|
|
assert.equal(f.gateway.tls.publicCertificate().sha256, first.sha256);
|
|
assert.equal((await f.request('/')).status, 200);
|
|
});
|
|
|
|
test('TLS sealing failure leaves listener closed and no plaintext or successful TLS registration', async t => {
|
|
const f = setup(t), tls = new CompanionTLS(f.registry, { protect() { throw new Error('fixture encryption failure'); } });
|
|
await assert.rejects(tls.material('127.0.0.1'), /encryption/);
|
|
assert.equal(f.registry.read().tls, undefined);
|
|
});
|
|
|
|
test('HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks', async t => {
|
|
const f = await running(t), ticket = await f.gateway.pairing(f.grant), token = new URLSearchParams(new URL(ticket.url).hash.slice(1)).get('pair');
|
|
assert.match(ticket.qr, /^data:image\/png;base64,/);
|
|
const attempts = await Promise.all([f.request('/mobile-api/pair', { token, name: 'first' }), f.request('/mobile-api/pair', { token, name: 'second' })]);
|
|
assert.deepEqual(attempts.map(value => value.status).sort(), [201, 401]);
|
|
const accepted = attempts.find(value => value.status === 201);
|
|
assert.match(accepted.headers['set-cookie'][0], /; Secure; HttpOnly; SameSite=Strict/);
|
|
assert.equal((await f.request('/mobile-api/pair', { token, name: 'third' }, { origin: 'https://unrelated.invalid' })).status, 403);
|
|
assert.equal((await f.request('/', undefined, { headers: { Host: 'localhost:443' } })).status, 421);
|
|
});
|
|
|
|
test('gateway never exposes management routes, arbitrary assets or unpaired project data', async t => {
|
|
const f = await running(t);
|
|
assert.equal((await f.request('/mobile-api/projects')).status, 401);
|
|
const { cookie } = await f.pair();
|
|
for (const route of ['/api/bootstrap', '/api/config', '/index.html', '/assets/desktop.js', '/src/server/index.mjs', '/mobile-api/config', '/mobile-api/projects?expand=all']) {
|
|
const result = await f.request(route, undefined, { cookie }); assert.ok(result.status >= 400, route);
|
|
assert.ok(!JSON.stringify(result.body).includes('Workbench-Token'));
|
|
}
|
|
});
|
|
|
|
test('authorized project events paginate from original seq without leaking other project events or payloads', async t => {
|
|
const f = await running(t), otherRoot = path.join(f.root, 'other'); fs.mkdirSync(otherRoot);
|
|
const otherProject = f.store.addProject(otherRoot), other = f.store.createSession(otherProject.id);
|
|
for (let i = 0; i < 7; i++) { f.store.save(other, { detail: { secret: 'fixture-secret' } }); f.store.save(f.session); }
|
|
const { cookie } = await f.pair(); let after = 0, events = [];
|
|
for (let i = 0; i < 20; i++) {
|
|
const page = await f.request('/mobile-api/events?after=' + after + '&limit=2', undefined, { cookie }); assert.equal(page.status, 200);
|
|
events.push(...page.body.events); after = page.body.nextCursor;
|
|
if (!page.body.hasMore) break;
|
|
}
|
|
assert.ok(events.length >= 8); assert.equal(new Set(events.map(event => event.seq)).size, events.length);
|
|
assert.ok(events.every(event => event.projectId === f.project.id && !Object.hasOwn(event, 'payload')));
|
|
assert.equal((await f.request('/mobile-api/sessions/' + other.id, undefined, { cookie })).status, 403);
|
|
const projects = await f.request('/mobile-api/projects', undefined, { cookie });
|
|
assert.equal(projects.body.length, 1); assert.equal(projects.body[0].root, undefined);
|
|
});
|
|
|
|
test('remote task projection excludes raw model history, host configuration, tool input and credentials', async t => {
|
|
const f = await running(t); f.session.providerMessages.push({ role: 'system', content: 'private-model-history' });
|
|
f.session.events.push({ id: randomUUID(), label: 'check', input: { token: 'private-input' }, output: 'fixture-secret' }); f.store.save(f.session);
|
|
const { cookie } = await f.pair(), result = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie });
|
|
assert.equal(result.status, 200); const text = JSON.stringify(result.body);
|
|
assert.ok(!text.includes('private-model-history') && !text.includes('private-input') && !text.includes('fixture-secret'));
|
|
assert.equal(result.body.events.at(-1).output, '[REDACTED]');
|
|
});
|
|
|
|
test('permission checks apply to direct remote mutation, not only UI controls', async t => {
|
|
const f = await running(t), { cookie } = await f.pair();
|
|
f.session.taskId = randomUUID(); f.session.runId = randomUUID(); f.store.save(f.session);
|
|
const result = await f.request('/mobile-api/sessions/' + f.session.id + '/stop', { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }, { cookie });
|
|
assert.equal(result.status, 403);
|
|
});
|
|
|
|
test('approval fingerprint and exact task/revision are bound; duplicate requests never execute twice', async t => {
|
|
const f = await running(t), grant = { ...f.grant, permissions: { observe: true, approve: true, stop: true } }, { cookie } = await f.pair(grant);
|
|
f.session.taskId = randomUUID(); f.session.runId = randomUUID();
|
|
const approval = { id: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, projectId: f.project.id, command: 'echo owned', reason: 'fixture', status: 'pending' };
|
|
f.session.approvals.push(approval); f.runtime.waiters.set(approval.id, { sessionId: f.session.id, runId: f.session.runId }); f.store.save(f.session);
|
|
let calls = 0;
|
|
f.runtime.decide = (_session, _approval, allow) => { calls++; assert.equal(allow, true); approval.status = 'approved'; f.runtime.waiters.delete(approval.id); f.store.save(f.session); };
|
|
const value = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision, approvalId: approval.id, fingerprint: approvalBinding(f.session, approval), allow: true };
|
|
const route = '/mobile-api/sessions/' + f.session.id + '/approve';
|
|
assert.equal((await f.request(route, { ...value, fingerprint: '0'.repeat(64) }, { cookie })).status, 409);
|
|
const results = await Promise.all([f.request(route, value, { cookie }), f.request(route, value, { cookie })]);
|
|
assert.ok(results.every(result => result.status === 200)); assert.equal(calls, 1);
|
|
assert.equal((await f.request(route, { ...value, allow: false }, { cookie })).status, 409);
|
|
});
|
|
|
|
test('unknown original operation is recorded and never replayed after response failure', async t => {
|
|
const f = await running(t), { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: false, stop: true } });
|
|
f.session.taskId = randomUUID(); f.session.runId = randomUUID(); f.store.save(f.session);
|
|
let calls = 0; f.runtime.stop = async () => { calls++; throw new Error('fixture interrupted receipt'); };
|
|
const value = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }, route = '/mobile-api/sessions/' + f.session.id + '/stop';
|
|
assert.equal((await f.request(route, value, { cookie })).status, 409);
|
|
const retry = await f.request(route, value, { cookie }); assert.equal(retry.body.status, 'unknown'); assert.equal(calls, 1);
|
|
});
|
|
|
|
test('revocation and gateway closure reject old access without invoking runtime stop', async t => {
|
|
const f = await running(t), { cookie, device } = await f.pair(); let stopped = 0; f.runtime.stop = () => { stopped++; };
|
|
f.gateway.revoke(device.id, device.revision);
|
|
assert.equal((await f.request('/mobile-api/projects', undefined, { cookie })).status, 401);
|
|
await f.gateway.close(); assert.equal(stopped, 0); assert.equal(f.gateway.status().enabled, false);
|
|
});
|
|
|
|
test('rate limits reject pairing brute force and do not persist candidate secrets', async t => {
|
|
const f = await running(t); let last;
|
|
for (let i = 0; i < 9; i++) last = await f.request('/mobile-api/pair', { token: randomBytes(32).toString('base64url'), name: 'phone' });
|
|
assert.equal(last.status, 429); assert.equal(f.gateway.registry.view().devices.length, 0);
|
|
});
|
|
|
|
test('real Windows CurrentUser DPAPI persists only a sealed CA and reopens it', { skip: process.platform !== 'win32' }, async t => {
|
|
const f = setup(t), tls = new CompanionTLS(f.registry);
|
|
await tls.material('127.0.0.1'); const hash = tls.publicCertificate().sha256;
|
|
await new CompanionTLS(f.registry).material('127.0.0.1');
|
|
assert.equal(tls.publicCertificate().sha256, hash);
|
|
});
|