Files
Agent-Workbench/tests/companion.test.mjs
T
2026-10-31 17:53:15 +08:00

357 lines
27 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, call, until, workspace } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { installUpgrade } from '../src/server/hot-upgrade.mjs';
import { createTask, createRun } from '../src/shared/contracts/execution.mjs';
import http from 'node:http';
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);
const me = await f.request('/mobile-api/me', undefined, { cookie });
assert.equal(me.body.operations.at(-1).status, 'unknown'); assert.equal(me.body.operations.at(-1).requestId, value.requestId);
assert.ok(!JSON.stringify(me.body).includes('credentialHash') && !JSON.stringify(me.body).includes('"hash"'));
});
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);
});
function realRuntime(f, command) {
const provider = new Provider(), runtime = new Runtime(f.store, provider);
provider.complete = async (_config, messages) => ({ message: messages.some(value => value.role === 'tool') ? { role: 'assistant', content: '本地夹具完成。' }
: { role: 'assistant', content: '', tool_calls: [call('owned-mobile-command', 'run_command', { command, reason: '原Runtime手机审批夹具' })] }, usage: null });
f.gateway.runtime = runtime; f.onCleanup(() => runtime.stopAll()); return runtime;
}
const fixtureCommand = source => (process.platform === 'win32' ? '& ' : '') + '"' + process.execPath + '" -e "' + source + '"';
test('mobile approval executes the original Runtime command exactly once and rejects the later desktop decision', async t => {
const f = await running(t), runtime = realRuntime(f, fixtureCommand("require('node:fs').appendFileSync('phone-approved.txt','one\\n')"));
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
runtime.start(f.session.id, '只运行这个自有夹具命令。');
await until(() => f.session.status === 'awaiting_approval');
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie }), approval = before.body.approvals[0];
const value = { requestId: randomUUID(), taskId: before.body.taskId, runId: before.body.runId, revision: before.body.revision,
approvalId: approval.id, fingerprint: approval.fingerprint, allow: true };
const route = '/mobile-api/sessions/' + f.session.id + '/approve';
const results = await Promise.all([f.request(route, value, { cookie }), f.request(route, value, { cookie })]);
assert.ok(results.every(value => value.status === 200));
assert.throws(() => runtime.decide(f.session.id, approval.id, true), /过期/);
await until(() => !runtime.active.has(f.session.id));
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'phone-approved.txt'), 'utf8'), 'one\n');
assert.equal(f.session.events.filter(value => value.tool === 'run_command').length, 1);
assert.equal((await f.request(route, value, { cookie })).body.duplicate, true);
});
test('desktop rejection wins a concurrent mobile request and original command remains unexecuted', async t => {
const f = await running(t), runtime = realRuntime(f, fixtureCommand("require('node:fs').writeFileSync('should-not-exist.txt','no')"));
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
runtime.start(f.session.id, '原桌面和手机审批竞争夹具。'); await until(() => f.session.status === 'awaiting_approval');
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie }), approval = before.body.approvals[0];
const pending = f.request('/mobile-api/sessions/' + f.session.id + '/approve', { requestId: randomUUID(), taskId: before.body.taskId,
runId: before.body.runId, revision: before.body.revision, approvalId: approval.id, fingerprint: approval.fingerprint, allow: true }, { cookie });
runtime.decide(f.session.id, approval.id, false);
assert.equal((await pending).status, 409); await until(() => !runtime.active.has(f.session.id));
assert.equal(fs.existsSync(path.join(f.projectRoot, 'should-not-exist.txt')), false);
});
test('phone stop waits for the original process exit and prevents later heartbeats and command replay', async t => {
const f = await running(t), runtime = realRuntime(f, fixtureCommand("setInterval(()=>require('node:fs').appendFileSync('heartbeat.txt','x'),80)"));
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
runtime.start(f.session.id, '手机停止自有心跳进程。'); await until(() => f.session.status === 'awaiting_approval');
runtime.decide(f.session.id, f.session.approvals.at(-1).id, true);
await until(() => fs.existsSync(path.join(f.projectRoot, 'heartbeat.txt')));
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie });
const value = { requestId: randomUUID(), taskId: before.body.taskId, runId: before.body.runId, revision: before.body.revision };
const route = '/mobile-api/sessions/' + f.session.id + '/stop', result = await f.request(route, value, { cookie });
assert.equal(result.status, 200); assert.equal(runtime.active.has(f.session.id), false);
const bytes = fs.readFileSync(path.join(f.projectRoot, 'heartbeat.txt'));
await new Promise(resolve => setTimeout(resolve, 250));
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'heartbeat.txt')), bytes);
assert.equal((await f.request(route, value, { cookie })).body.duplicate, true);
assert.equal(f.session.events.filter(value => value.tool === 'run_command').length, 1);
});
test('Run replacement during parent-stop wait is rejected rather than stopping the new Run', async t => {
const f = setup(t), runtime = new Runtime(f.store, new Provider());
f.session.taskId = randomUUID(); f.session.runId = randomUUID(); const expected = { taskId: f.session.taskId, runId: f.session.runId };
let stopped = 0;
runtime.workers = { async stopParent() { f.session.runId = randomUUID(); runtime.active.set(f.session.id, { controller: { abort() { stopped++; } }, promise: Promise.resolve() }); } };
await assert.rejects(runtime.stop(f.session.id, expected), /已变化/); assert.equal(stopped, 0);
runtime.active.clear();
});
test('diff pages preserve source SHA; report reads verify blobs and exclude unrelated artifact kinds', async t => {
const f = await running(t), task = createTask(f.session, '原差异及工件夹具', f.store.config);
const run = createRun(f.session, task, f.store.config);
f.store.core.task.set(task.id, task); f.store.core.run.set(run.id, run); f.session.taskId = task.id; f.session.runId = run.id;
const text = '+line\\n'.repeat(17000), change = { id: randomUUID(), taskId: f.session.taskId, sha256: companionHash('new file'), baseSha256: companionHash('old'), path: 'long/path.ts', diff: [{ value: text, added: true }] };
f.session.changes.push(change); f.store.save(f.session);
const report = f.store.artifactStore.write(f.session, null, '# 原报告\nfixture-secret\n', { kind: 'delivery-report-markdown', mediaType: 'text/markdown' });
const raw = f.store.artifactStore.write(f.session, null, 'never expose tool input', { kind: 'tool-result' });
f.store.core.artifact.set(report.id, report); f.store.core.artifact.set(raw.id, raw); f.store.save(f.session);
const { cookie } = await f.pair(); let assembled = '', offset = 0, hash;
for (let page = 0; page < 20; page++) {
const value = await f.request('/mobile-api/sessions/' + f.session.id + '/changes/' + change.id + '?offset=' + offset, undefined, { cookie }); assert.equal(value.status, 200);
assert.equal(value.body.sourceSha256, change.sha256); if (hash) assert.equal(value.body.sha256, hash); hash = value.body.sha256;
assembled += value.body.text; offset = value.body.nextOffset; if (!value.body.hasMore) break;
}
assert.equal(companionHash(assembled), hash); assert.ok(assembled.length > 100000);
const route = '/mobile-api/sessions/' + f.session.id + '/reports/';
const delivered = await f.request(route + report.id, undefined, { cookie }); assert.equal(delivered.status, 200);
assert.equal(delivered.body.sourceSha256, report.sha256); assert.equal(delivered.body.sha256, companionHash(delivered.body.text)); assert.equal(delivered.body.redacted, true);
assert.equal((await f.request(route + raw.id, undefined, { cookie })).status, 404);
fs.appendFileSync(path.join(f.store.artifactStore.root, report.relative), 'corrupt');
assert.equal((await f.request(route + report.id, undefined, { cookie })).status, 500);
});
test('hot upgrade refuses an active gateway and restores closed gateway ownership on failure', async t => {
const f = setup(t), provider = new Provider(), runtime = new Runtime(f.store, provider), server = http.createServer((_request, response) => response.end('old'));
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
f.onCleanup(() => new Promise(resolve => server.close(resolve)));
const context = { server, store: f.store, provider, runtime, token: 'test-upgrade-owned', clients: new Set(), started: Date.now() };
const gateway = { server: { listening: true }, busy: false }; server.workbenchCompanion = gateway;
assert.throws(() => installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false }), /Close the mobile/);
gateway.server = null;
f.store.claimRuntime = () => { throw new Error('fixture upgrade failure'); };
assert.throws(() => installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false }), /fixture upgrade failure/);
assert.equal(server.workbenchCompanion, gateway);
});
test('damaged device permissions or expiry fail closed and never overwrite the original registry', t => {
const f = setup(t), accepted = f.registry.consume(f.registry.pair(f.grant, 'g').token, 'phone', 'g');
const original = f.store.storage.meta('mobileCompanion');
for (const damage of [value => { value.devices[accepted.device.id].permissions.stop = 'true'; }, value => { value.devices[accepted.device.id].expiresAt = 'invalid'; }]) {
const changed = structuredClone(original); damage(changed); f.store.storage.setMeta('mobileCompanion', changed);
assert.throws(() => f.registry.authenticate(accepted.token), /原手机登记无法核对/);
assert.throws(() => f.registry.initialize(), /原手机登记无法核对/);
assert.deepEqual(f.store.storage.meta('mobileCompanion'), changed);
}
});
test('device revocation destroys its actual authenticated TLS connection', async t => {
const f = await running(t), { cookie, device } = await f.pair();
const agent = new https.Agent({ keepAlive: true, ca: f.gateway.registry.read().tls.certificate });
let socket;
await new Promise((resolve, reject) => {
const request = https.get(f.gateway.origin + '/mobile-api/me', { agent, servername: '', headers: { Cookie: cookie } }, response => {
socket = response.socket; response.resume(); response.on('end', resolve);
}); request.on('error', reject);
});
assert.ok(socket && !socket.destroyed); f.gateway.revoke(device.id, device.revision);
await until(() => socket.destroyed); agent.destroy();
});