226 lines
13 KiB
JavaScript
226 lines
13 KiB
JavaScript
// End-to-end self-update of a real, published Linux AppImage (no mocks, no credentials):
|
|
// 1. start the OLD published AppImage with a disposable profile and create an identity, bookmark, device pref;
|
|
// 2. let its updater find, download and verify the NEWER published release from git.eeee.moe;
|
|
// 3. confirm install: the AppImage file is replaced and the app relaunches by itself after exiting;
|
|
// 4. the relaunched process reports the new version; its file matches the release feed's sha512;
|
|
// 5. start the new AppImage again: version, UID, nickname, bookmark and device pref are unchanged.
|
|
//
|
|
// xvfb-run -a node scripts/update-e2e.mjs --from <old.AppImage> --to-tag v0.1.3 --out update-e2e-out \
|
|
// [--new-prefs '{"transmitMode":"vad","vadSensitivity":"high"}']
|
|
//
|
|
// The old app stores non-default values it supports itself (transmitMode 'open', devices, …). --new-prefs are
|
|
// settings that exist only in the new version; they are applied after the update (the app is never connected to
|
|
// a server in this run) and must survive one more restart.
|
|
//
|
|
// Runs AppImages with APPIMAGE_EXTRACT_AND_RUN=1 (no FUSE needed). Everything lives in a temp directory:
|
|
// profile, updater cache, the "installed" AppImage. The user's own installation is never touched.
|
|
import { chromium } from 'playwright-core';
|
|
import { createHash } from 'node:crypto';
|
|
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import path from 'node:path';
|
|
import { launchApp } from './lib/electron-app.mjs';
|
|
import { parseFeed } from './update-feed-check.mjs';
|
|
|
|
const argv = process.argv.slice(2);
|
|
const opt = (n) => (argv.indexOf(`--${n}`) >= 0 ? argv[argv.indexOf(`--${n}`) + 1] : undefined);
|
|
const fromImage = opt('from');
|
|
const toTag = opt('to-tag');
|
|
const out = path.resolve(opt('out') ?? 'update-e2e-out');
|
|
if (!fromImage || !toTag || process.platform !== 'linux') {
|
|
console.error('usage (Linux): update-e2e.mjs --from <old.AppImage> --to-tag <vX> [--out dir] [--new-prefs <json>]');
|
|
process.exit(2);
|
|
}
|
|
const toVersion = toTag.slice(1);
|
|
const newPrefs = opt('new-prefs') ? JSON.parse(opt('new-prefs')) : null;
|
|
const RELEASE = 'https://git.eeee.moe/TeamsPeach/client/releases/download';
|
|
mkdirSync(out, { recursive: true });
|
|
|
|
const work = mkdtempSync(path.join(tmpdir(), 'teamspeach-update-e2e-'));
|
|
const apps = path.join(work, 'apps');
|
|
const profile = path.join(work, 'profile');
|
|
mkdirSync(apps);
|
|
const installed = path.join(apps, path.basename(fromImage));
|
|
copyFileSync(fromImage, installed);
|
|
chmodSync(installed, 0o755);
|
|
const env = { XDG_CACHE_HOME: path.join(work, 'cache'), APPIMAGE_EXTRACT_AND_RUN: '1' };
|
|
|
|
const result = { startedAt: new Date().toISOString(), fromImage: path.basename(fromImage), toTag, steps: [] };
|
|
const step = (name, data = {}) => {
|
|
result.steps.push({ name, at: new Date().toISOString(), ...data });
|
|
console.log(`[update-e2e] ${name} ${JSON.stringify(data)}`);
|
|
};
|
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
const sha512 = (file) => createHash('sha512').update(readFileSync(file)).digest('base64');
|
|
const updaterLog = () => {
|
|
const file = path.join(profile, 'logs', 'updater.log');
|
|
return existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
};
|
|
|
|
async function launch(image, label) {
|
|
const app = await launchApp({ exe: image, profile, args: ['--no-sandbox'], env, timeout: 120000 });
|
|
const page = await app.firstWindow({ timeout: 120000 });
|
|
page.on('console', (m) => m.type() === 'error' && step(`${label} console error`, { text: m.text().slice(0, 300) }));
|
|
return { app, page };
|
|
}
|
|
const diag = (page) => page.evaluate(() => window.teamspeachDiagnostics.snapshot());
|
|
|
|
async function waitFor(fn, ms, what) {
|
|
const end = Date.now() + ms;
|
|
for (;;) {
|
|
const v = await fn();
|
|
if (v) return v;
|
|
if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);
|
|
await sleep(1000);
|
|
}
|
|
}
|
|
|
|
let failed = null;
|
|
try {
|
|
// 1. Old version, fresh profile.
|
|
let { app, page } = await launch(installed, 'old');
|
|
await page.waitForSelector('#view-onboarding', { state: 'visible', timeout: 60000 });
|
|
await page.fill('#onboarding-nick', 'UpdateProof');
|
|
await page.click('#onboarding-submit');
|
|
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
|
|
const before = await diag(page);
|
|
const oldInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
|
|
const bookmark = { id: 'upd0001', name: 'Update proof', address: '192.0.2.10:9987' };
|
|
// Non-default values for every pref the OLD version knows (voice/transmit/devices included). Each key is set
|
|
// on its own so that a value the old schema rejects is simply skipped and reported.
|
|
const wanted = {
|
|
savedServers: [bookmark], inputDeviceId: 'update-proof-device', outputDeviceId: 'update-proof-output',
|
|
transmitMode: 'open', pttCode: 'F9', echoCancellation: false, noiseSuppression: false, autoGainControl: false,
|
|
voiceVolume: 150, streamVolume: 80, theme: 'light', lastAddress: '192.0.2.10:9987',
|
|
};
|
|
const oldKeys = Object.keys(await page.evaluate(() => window.teamspeach.getPrefs()));
|
|
const rejected = [];
|
|
for (const [key, value] of Object.entries(wanted)) {
|
|
if (!oldKeys.includes(key)) continue;
|
|
const res = await page.evaluate(([k, v]) => window.teamspeach.setPrefs({ [k]: v }), [key, value]);
|
|
if (!res || !res.ok) rejected.push(key);
|
|
}
|
|
const prefsBefore = await page.evaluate(() => window.teamspeach.getPrefs());
|
|
step('old version running', { version: oldInfo.appVersion, uid: before.profile.uid, nickname: before.profile.nickname, prefsBefore, rejected });
|
|
|
|
// 2. Real check + download from the public release server.
|
|
const checked = await page.evaluate(() => window.teamspeach.checkForUpdates());
|
|
step('check', { phase: checked.phase, available: checked.available, error: checked.error, skipped: checked.newerWithoutBuild });
|
|
const ready = await waitFor(async () => {
|
|
const s = await page.evaluate(() => window.teamspeach.getUpdateState());
|
|
if (s.phase === 'error') throw new Error(`updater error ${JSON.stringify(s.error)}`);
|
|
return s.phase === 'downloaded' && s;
|
|
}, 600000, 'download');
|
|
step('downloaded and verified by electron-updater', { available: ready.available, target: ready.target });
|
|
if (ready.available.version !== toVersion) throw new Error(`offered ${ready.available.version}, expected ${toVersion}`);
|
|
|
|
// 3. User confirms install (also confirming interruption, as the UI would). The relaunched process inherits
|
|
// this process's environment: drop the test-only window hold so it starts exactly like a normal launch, and
|
|
// remove the old DevToolsActivePort so the new process's port can be found.
|
|
await app.evaluate(() => {
|
|
delete process.env.TEAMSPEACH_TEST_HOLD_WINDOW;
|
|
});
|
|
rmSync(path.join(profile, 'DevToolsActivePort'), { force: true });
|
|
const exited = new Promise((r) => app.process().once('exit', (code, signal) => r({ code, signal })));
|
|
const install = await page.evaluate(() => window.teamspeach.installUpdate(true)).catch((e) => ({ evaluateEnded: e.message.slice(0, 200) }));
|
|
step('install requested', { install });
|
|
step('old process exited', await Promise.race([exited, sleep(180000).then(() => ({ timeout: true }))]));
|
|
|
|
// 4. Relaunch happened by itself: the new version logs its start with its pid.
|
|
const started = await waitFor(() => {
|
|
const m = new RegExp(`updater: version ${toVersion.replace(/\./g, '\\.')} pid (\\d+) target (\\S+)`).exec(updaterLog());
|
|
return m && { pid: Number(m[1]), target: m[2] };
|
|
}, 180000, 'relaunched new version');
|
|
step('new version relaunched automatically', started);
|
|
|
|
// The relaunched app inherited --remote-debugging-port=0: attach over CDP and read its own window.
|
|
const port = await waitFor(() => {
|
|
const f = path.join(profile, 'DevToolsActivePort');
|
|
return existsSync(f) && Number(readFileSync(f, 'utf8').split('\n')[0]);
|
|
}, 120000, 'DevToolsActivePort of the relaunched app');
|
|
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
|
|
const relaunchedPage = await waitFor(async () => {
|
|
for (const ctx of browser.contexts()) for (const p of ctx.pages()) if (p.url().startsWith('app://')) return p;
|
|
return null;
|
|
}, 120000, 'window of the relaunched app');
|
|
await relaunchedPage.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
|
|
const relaunched = {
|
|
version: (await relaunchedPage.evaluate(() => window.teamspeach.getAppInfo())).appVersion,
|
|
uid: (await diag(relaunchedPage)).profile.uid,
|
|
};
|
|
await relaunchedPage.screenshot({ path: path.join(out, 'relaunched.png') });
|
|
await browser.close().catch(() => {});
|
|
step('relaunched window', { ...relaunched, uidSame: relaunched.uid === before.profile.uid });
|
|
if (relaunched.version !== toVersion || relaunched.uid !== before.profile.uid) throw new Error('relaunched app has the wrong version or identity');
|
|
const files = readdirSync(apps);
|
|
const newImage = path.join(apps, files.find((f) => f.endsWith('.AppImage')));
|
|
const feedName = `${toVersion.includes('-') ? toVersion.split('-')[1].split('.')[0] : 'latest'}-linux.yml`;
|
|
const feedRes = await fetch(`${RELEASE}/${toTag}/${feedName}`);
|
|
if (!feedRes.ok) throw new Error(`feed ${feedName}: HTTP ${feedRes.status}`);
|
|
const feed = parseFeed(await feedRes.text());
|
|
const fileSha = sha512(newImage);
|
|
step('installed file', { files, sha512MatchesFeed: fileSha === feed.files[0].sha512, feedFile: feed.files[0].url });
|
|
if (files.length !== 1 || path.basename(newImage) !== feed.files[0].url || fileSha !== feed.files[0].sha512) {
|
|
throw new Error('installed AppImage does not match the release feed');
|
|
}
|
|
process.kill(started.pid, 'SIGTERM');
|
|
await waitFor(() => !existsSync(`/proc/${started.pid}`), 60000, 'relaunched app to exit');
|
|
await sleep(2000);
|
|
|
|
// 5. Start the new AppImage again: same identity and preferences, new version.
|
|
({ app, page } = await launch(newImage, 'new'));
|
|
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
|
|
const after = await diag(page);
|
|
const newInfo = await page.evaluate(() => window.teamspeach.getAppInfo());
|
|
const prefs = await page.evaluate(() => window.teamspeach.getPrefs());
|
|
const state = await page.evaluate(() => window.teamspeach.getUpdateState());
|
|
await page.screenshot({ path: path.join(out, 'after-update.png') });
|
|
// The old choice must be what the new version shows before any new setting is applied.
|
|
const oldTransmitMode = prefsBefore.transmitMode;
|
|
const transmitModeKept = prefs.transmitMode === oldTransmitMode;
|
|
// 6. Optional: apply settings that exist only in the new version (e.g. VAD) while disconnected — the app
|
|
// never connects to a server in this run, so nothing is captured or sent — then restart and read them back.
|
|
let newSettings = null;
|
|
if (newPrefs) {
|
|
const applied = await page.evaluate((p) => window.teamspeach.setPrefs(p), newPrefs);
|
|
newSettings = { requested: newPrefs, applied: Boolean(applied && applied.ok), rejectedBy: applied && !applied.ok ? applied.message : null };
|
|
}
|
|
await app.close();
|
|
if (newPrefs) {
|
|
await sleep(2000);
|
|
({ app, page } = await launch(newImage, 'new-restart'));
|
|
await page.waitForSelector('#view-app', { state: 'visible', timeout: 60000 });
|
|
const reread = await page.evaluate(() => window.teamspeach.getPrefs());
|
|
const again = await diag(page);
|
|
await app.close();
|
|
newSettings.afterRestart = Object.fromEntries(Object.keys(newPrefs).map((k) => [k, reread[k]]));
|
|
newSettings.kept = newSettings.applied && Object.keys(newPrefs).every((k) => JSON.stringify(reread[k]) === JSON.stringify(newPrefs[k]));
|
|
newSettings.uidSame = again.profile.uid === before.profile.uid;
|
|
step('new settings after restart', newSettings);
|
|
}
|
|
const kept = {
|
|
version: newInfo.appVersion,
|
|
uidSame: after.profile.uid === before.profile.uid,
|
|
nicknameSame: after.profile.nickname === before.profile.nickname,
|
|
bookmarkSame: JSON.stringify(prefs.savedServers) === JSON.stringify([bookmark]),
|
|
deviceSame: prefs.inputDeviceId === 'update-proof-device',
|
|
transmitMode: { old: oldTransmitMode, afterUpdate: prefs.transmitMode, kept: transmitModeKept },
|
|
// Every pref of the old version keeps its value; keys introduced by the new version are listed with defaults.
|
|
prefsChanged: Object.keys(prefsBefore).filter((k) => JSON.stringify(prefs[k]) !== JSON.stringify(prefsBefore[k])),
|
|
prefsAdded: Object.fromEntries(Object.keys(prefs).filter((k) => !(k in prefsBefore)).map((k) => [k, prefs[k]])),
|
|
updater: { phase: state.phase, target: state.target, mode: state.mode },
|
|
};
|
|
step('after update', kept);
|
|
if (kept.version !== toVersion || !kept.uidSame || !kept.nicknameSame || !kept.bookmarkSame || !kept.deviceSame || !transmitModeKept || kept.prefsChanged.length > 0) {
|
|
throw new Error('state after update is wrong');
|
|
}
|
|
if (newSettings && (!newSettings.kept || !newSettings.uidSame)) throw new Error('new-version settings were not kept across a restart');
|
|
} catch (err) {
|
|
failed = err;
|
|
step('FAILED', { error: err.message });
|
|
}
|
|
result.updaterLog = updaterLog().split('\n').filter((l) => / updater: /.test(l));
|
|
result.ok = !failed;
|
|
writeFileSync(path.join(out, 'result.json'), JSON.stringify(result, null, 2));
|
|
process.exit(failed ? 1 : 0);
|