121 lines
11 KiB
JavaScript
121 lines
11 KiB
JavaScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import net from 'node:net';
|
|
import assert from 'node:assert/strict';
|
|
import { spawn, execFileSync } from 'node:child_process';
|
|
import { publicSnapshot, hash, canonical } from './retained-host-state.mjs';
|
|
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
|
import { inspectHostInstallation } from '../src/core/desktop/app-installation.mjs';
|
|
import { openDefaults } from '../src/shared/contracts/execution-policy.mjs';
|
|
|
|
// One write-once receipt per explicit operation. Never replay a failed installer
|
|
// or resume a user project. Only public configuration and row/byte hashes leave
|
|
// the host; private Provider credentials are not read or saved.
|
|
const mode = process.argv[2], attempt = process.argv[3] ?? 'formal';
|
|
if (mode === '--help') { console.log('node scripts/open-permissions-formal-1.25.5.mjs before|upgrade|configure|restart|final [formal[-attempt-N]]'); process.exit(0); }
|
|
assert.ok(['before', 'upgrade', 'configure', 'restart', 'final'].includes(mode));
|
|
assert.match(attempt, /^formal(?:-attempt-\d+)?$/);
|
|
const root = path.resolve('.qa/unrestricted-1.25.5', attempt), url = 'http://127.0.0.1:4318';
|
|
const read = file => JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
|
|
fs.mkdirSync(root, { recursive: true });
|
|
const save = (name, value) => fs.writeFileSync(path.join(root, name), JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
|
|
assert.equal(fs.existsSync(path.join(root, mode + '.json')), false, 'Preserve the original operation receipt.');
|
|
assert.equal(execFileSync('git', ['status', '--porcelain'], { encoding: 'utf8', windowsHide: true }).trim(), '', 'Use reviewed, committed inputs.');
|
|
const sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8', windowsHide: true }).trim();
|
|
async function api(route, input) {
|
|
const boot = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' }, signal: AbortSignal.timeout(30000) })).json();
|
|
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST', headers: { 'X-Workbench-Token': boot.token,
|
|
Connection: 'close', ...(input === undefined ? {} : { 'Content-Type': 'application/json' }) }, body: input === undefined ? undefined : JSON.stringify(input), signal: AbortSignal.timeout(60000) });
|
|
const result = await response.json(); assert.equal(response.ok, true, route + ': ' + JSON.stringify(result)); return result;
|
|
}
|
|
async function inspectorClosed() {
|
|
await new Promise((resolve, reject) => { const socket = net.createConnection({ host: '127.0.0.1', port: 9229 }); socket.setTimeout(1500);
|
|
socket.once('connect', () => { socket.destroy(); reject(Error('Inspector is open.')); });
|
|
socket.once('error', error => { socket.destroy(); error.code === 'ECONNREFUSED' ? resolve() : reject(error); });
|
|
socket.once('timeout', () => { socket.destroy(); reject(Error('Inspector state unknown.')); }); });
|
|
}
|
|
async function state() {
|
|
const host = await api('/host/status'); assert.equal(host.activity.active, false, 'Do not stop an active user task.');
|
|
const snapshot = await publicSnapshot(url, host.identity.dataRoot), boot = await api('/bootstrap');
|
|
assert.deepEqual(snapshot.active, []); return { ...snapshot, host, publicConfig: boot.config };
|
|
}
|
|
function sameBusiness(before, after, { configuration = false } = {}) {
|
|
for (const key of ['projectsSha256', 'sessionsSha256', 'eventCursor']) assert.equal(after[key], before[key], key);
|
|
assert.deepEqual(after.database.sessionIds, before.database.sessionIds); assert.deepEqual(after.exports, before.exports, 'Every original session export');
|
|
assert.deepEqual(Object.keys(after.database.tables), Object.keys(before.database.tables));
|
|
for (const [name, table] of Object.entries(before.database.tables)) {
|
|
const next = after.database.tables[name]; assert.equal(next.count, table.count, name); assert.equal(next.schemaSha256, table.schemaSha256, name);
|
|
const rows = value => configuration && name === 'metadata' ? value.rows.filter(row => row.id !== 'config') : value.rows;
|
|
assert.deepEqual(rows(next), rows(table), 'All original rows: ' + name);
|
|
}
|
|
assert.deepEqual(after.persistent.artifacts, before.persistent.artifacts, 'Every original artifact byte');
|
|
const files = value => configuration ? value.filter(row => row.path !== 'config.json') : value;
|
|
assert.deepEqual(files(after.persistent.files), files(before.persistent.files), 'Original compatibility files');
|
|
return { originalRows: configuration ? 'exact except explicitly saved metadata/config' : 'exact', originalExports: 'exact', originalArtifactBytes: 'exact',
|
|
originalFiles: configuration ? 'exact except explicitly saved config.json' : 'exact' };
|
|
}
|
|
let result; const startedAt = new Date().toISOString();
|
|
try {
|
|
await inspectorClosed(); const current = await state(); assert.equal(current.host.desktopWindows.count, 0);
|
|
const dataRoot = current.host.identity.dataRoot, installRoot = path.dirname(path.dirname(current.runtimeRoot));
|
|
assert.equal(path.basename(path.dirname(current.runtimeRoot)), 'versions');
|
|
if (mode === 'before') {
|
|
assert.equal(current.version, '1.25.4'); save('state-before.json', current); save('pointer-before.json', read(path.join(installRoot, 'current.json')));
|
|
result = { success: true, version: current.version, pid: current.pid, instanceId: current.host.identity.instanceId, projects: current.projects,
|
|
sessions: current.database.sessionIds.length, hasKey: current.hasKey, dataRoot, installRoot };
|
|
} else if (mode === 'upgrade') {
|
|
const before = read(path.join(root, 'state-before.json')); sameBusiness(before, current); assert.equal(current.pid, before.pid);
|
|
assert.deepEqual(read(path.join(installRoot, 'current.json')), read(path.join(root, 'pointer-before.json')));
|
|
const candidate = read('releases/latest.json'); assert.equal(candidate.documentation.sourceCommit, sourceCommit);
|
|
const manifest = read(path.join(candidate.portableRoot, 'MANIFEST.json')); assert.equal(manifest.version, '1.25.5');
|
|
assert.equal(hash(fs.readFileSync(candidate.installer.path)), candidate.installer.sha256); save('candidate.json', candidate);
|
|
const fd = fs.openSync(path.join(root, 'installer-process.log'), 'wx'), began = Date.now(); let code;
|
|
try { code = await new Promise((resolve, reject) => { const child = spawn(candidate.installer.path,
|
|
['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/LOG=' + path.join(root, 'installer.log'), '/DIR=' + installRoot, '/DATA_ROOT=' + dataRoot, '/PORT=4318'],
|
|
{ windowsHide: true, stdio: ['ignore', fd, fd] }); child.once('error', reject); child.once('close', resolve); }); } finally { fs.closeSync(fd); }
|
|
save('installer-exit.json', { code, elapsedMs: Date.now() - began }); assert.equal(code, 0, 'Do not replay the installer.');
|
|
const after = await state(); const retention = sameBusiness(before, after);
|
|
assert.equal(after.version, '1.25.5'); assert.equal(after.pid, before.pid); assert.equal(after.host.identity.instanceId, before.host.identity.instanceId);
|
|
assert.equal(after.hasKey, before.hasKey); assert.equal(after.configSha256, before.configSha256);
|
|
const installed = path.join(installRoot, 'versions', path.basename(candidate.portableRoot)), identity = inspectHostInstallation(installed);
|
|
assert.equal(fs.realpathSync.native(after.runtimeRoot), fs.realpathSync.native(installed));
|
|
const pointer = read(path.join(installRoot, 'current.json')); assert.equal(pointer.active.manifestSha256, identity.manifestSha256);
|
|
save('state-upgraded.json', after); result = { success: true, pid: after.pid, version: after.version, retention, runtimeRoot: after.runtimeRoot, pointerRevision: pointer.revision };
|
|
} else if (mode === 'configure') {
|
|
assert.equal(read(path.join(root, 'upgrade.json')).success, true);
|
|
const before = read(path.join(root, 'state-upgraded.json')); sameBusiness(before, current); assert.equal(current.pid, before.pid);
|
|
await api('/model-center/runtime-budgets', { executionMode: 'unrestricted' });
|
|
await api('/model-center/permissions', { approvalMode: 'full' });
|
|
const after = await state(), retention = sameBusiness(before, after, { configuration: true });
|
|
const expected = { ...before.publicConfig, ...openDefaults, approvalMode: 'full', configRevision: before.publicConfig.configRevision + 2 };
|
|
assert.deepEqual(canonical(after.publicConfig), canonical(expected), 'Only the requested defaults and saved permission change');
|
|
assert.equal(after.pid, before.pid); assert.equal(after.hasKey, before.hasKey); save('state-configured.json', after);
|
|
result = { success: true, pid: after.pid, version: after.version, retention, policy: openDefaults, approvalMode: after.publicConfig.approvalMode,
|
|
configRevision: after.publicConfig.configRevision, selected: after.modelCenter.selected };
|
|
} else if (mode === 'restart') {
|
|
assert.equal(read(path.join(root, 'configure.json')).success, true);
|
|
const before = read(path.join(root, 'state-configured.json')); sameBusiness(before, current); assert.equal(current.pid, before.pid); assert.equal(current.configSha256, before.configSha256);
|
|
const controller = new HostController({ appRoot: current.runtimeRoot, dataRoot, port: 4318, timeoutMs: 60000 });
|
|
const connection = await controller.connect(); assert.equal(connection.identity.pid, before.pid);
|
|
const stopped = await controller.stop(); save('stopped.json', stopped); assert.equal(stopped.processExited, true);
|
|
const launched = await controller.start(); save('started.json', launched);
|
|
const after = await state(), retention = sameBusiness(before, after); assert.equal(after.version, '1.25.5'); assert.notEqual(after.pid, before.pid);
|
|
assert.notEqual(after.host.identity.instanceId, before.host.identity.instanceId);
|
|
const expected = { ...before.publicConfig, hasKey: after.publicConfig.hasKey }; assert.deepEqual(after.publicConfig, expected);
|
|
assert.equal(after.publicConfig.approvalMode, 'full'); save('state-restarted.json', after);
|
|
result = { success: true, version: after.version, previousPid: before.pid, pid: after.pid, previousInstanceId: before.host.identity.instanceId,
|
|
instanceId: after.host.identity.instanceId, retention, hasKeyBefore: before.hasKey, hasKeyAfter: after.hasKey,
|
|
publicCredentialPresence: after.modelCenter.connections.map(({ id, name, hasKey }) => ({ id, name, hasKey })), approvalMode: after.publicConfig.approvalMode };
|
|
} else {
|
|
assert.equal(read(path.join(root, 'restart.json')).success, true);
|
|
const before = read(path.join(root, 'state-restarted.json')), retention = sameBusiness(before, current);
|
|
assert.equal(current.pid, before.pid); assert.equal(current.host.identity.instanceId, before.host.identity.instanceId); assert.equal(current.configSha256, before.configSha256);
|
|
assert.equal(current.publicConfig.approvalMode, 'full'); save('state-final.json', current);
|
|
result = { success: true, version: current.version, pid: current.pid, projects: current.projects, sessions: current.database.sessionIds.length,
|
|
hasKey: current.hasKey, retention, runtimeRoot: current.runtimeRoot, approvalMode: current.publicConfig.approvalMode, desktopWindows: current.host.desktopWindows.count };
|
|
}
|
|
await inspectorClosed();
|
|
} catch (error) { result = { success: false, error: error.stack }; process.exitCode = 1; }
|
|
result = { ...result, mode, sourceCommit, startedAt, finishedAt: new Date().toISOString(), realModelRequests: 0, keyReadOrResaved: false };
|
|
save(mode + '.json', result); console.log(JSON.stringify({ root, ...result }, null, 2));
|