261 lines
12 KiB
JavaScript
261 lines
12 KiB
JavaScript
'use strict';
|
|
|
|
// Electron main-process harness for test/update-engine.test.mjs. Runs the real update service with the real
|
|
// electron-updater (NSIS updater on Windows, AppImage updater on Linux) against a release server emulated at
|
|
// the protocol layer of BOTH sessions involved (default session: release list; "electron-updater": feeds and
|
|
// packages), so HTTP handling, sha512 verification and the download cache are the library's own.
|
|
// Never installs anything. Prints one JSON line with the scenario results and exits.
|
|
// With UPDATE_HARNESS_LIVE=1 it instead checks and downloads from the real public release server
|
|
// (scripts/update-live-check.mjs).
|
|
|
|
const crypto = require('node:crypto');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { app, session } = require('electron');
|
|
|
|
const repo = process.env.UPDATE_HARNESS_REPO;
|
|
const tmp = process.env.UPDATE_HARNESS_TMP;
|
|
app.setPath('userData', path.join(tmp, 'userData'));
|
|
|
|
const source = require(path.join(repo, 'app/main/update-source.js'));
|
|
const { createUpdateService, createElectronUpdater } = require(path.join(repo, 'app/main/updates.js'));
|
|
|
|
const TARGET = process.platform === 'win32'
|
|
? { id: 'win-x64-nsis', platform: 'win32', arch: 'x64', mode: 'auto', kind: 'nsis', disabledCode: null }
|
|
: { id: `linux-${process.arch}-appimage`, platform: 'linux', arch: process.arch, mode: 'auto', kind: 'appimage', disabledCode: null };
|
|
const OTHER_ARCH = TARGET.kind === 'nsis' ? { ...TARGET, arch: 'arm64' } : { ...TARGET, arch: TARGET.arch === 'x64' ? 'arm64' : 'x64' };
|
|
|
|
const sha512 = (b) => crypto.createHash('sha512').update(b).digest('base64');
|
|
|
|
// ---------- emulated release server ----------
|
|
let releases = [];
|
|
const files = new Map(); // "<tag>/<name>" → { bytes } | { status } | { gate: Promise<Buffer> }
|
|
const requests = [];
|
|
|
|
function feedYaml(version, name, bytes, shaOf = bytes) {
|
|
return Buffer.from(
|
|
`version: ${version}\nfiles:\n - url: ${name}\n sha512: ${sha512(shaOf)}\n size: ${bytes.length}\npath: ${name}\nsha512: ${sha512(shaOf)}\nreleaseDate: '2026-10-24T00:00:00.000Z'\n`,
|
|
);
|
|
}
|
|
|
|
/** Adds a release; options shape its feed: corrupt sha, other-arch package, missing feed file, gated feed. */
|
|
function addRelease(tag, { prerelease = true, draft = false, corrupt = false, otherArch = false, feedStatus = null, gate = null } = {}) {
|
|
const version = tag.slice(1);
|
|
const bytes = crypto.randomBytes(200 * 1024);
|
|
const pkg = source.packageFileName(TARGET, version);
|
|
const otherPkg = source.packageFileName(OTHER_ARCH, version);
|
|
const feed = source.feedFileName(TARGET, version);
|
|
const assets = new Map([[pkg, bytes], [otherPkg, bytes]]);
|
|
const feedName = otherArch ? otherPkg : pkg;
|
|
const feedBytes = feedYaml(version, feedName, bytes, corrupt ? crypto.randomBytes(bytes.length) : bytes);
|
|
assets.set(feed, feedBytes);
|
|
for (const [name, b] of assets) files.set(`${tag}/${name}`, { bytes: b });
|
|
if (feedStatus) files.set(`${tag}/${feed}`, { status: feedStatus });
|
|
if (gate) files.set(`${tag}/${feed}`, { gate: gate.then(() => feedBytes) });
|
|
releases.push({ tag_name: tag, draft, prerelease, published_at: '2026-10-24T00:00:00Z', assets: [...assets].map(([name, b]) => ({ name, size: b.length })) });
|
|
return { bytes, pkg };
|
|
}
|
|
|
|
async function handle(req) {
|
|
const url = new URL(req.url);
|
|
requests.push({ url: req.url, auth: req.headers.get('authorization') });
|
|
if (url.host !== 'git.eeee.moe') return new Response('unexpected host', { status: 599 });
|
|
if (url.pathname === '/api/v1/repos/TeamsPeach/client/releases') {
|
|
if (releases === 'network-error') return Response.error();
|
|
const page = Number(url.searchParams.get('page'));
|
|
const body = page === 1 ? releases : [];
|
|
return new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json', 'x-total-count': String(releases.length) } });
|
|
}
|
|
const m = /^\/TeamsPeach\/client\/releases\/download\/([^/]+)\/([^/]+)$/.exec(url.pathname);
|
|
const entry = m && files.get(`${m[1]}/${decodeURIComponent(m[2])}`);
|
|
if (!entry) return new Response('not found', { status: 404 });
|
|
if (entry.status) return new Response('x', { status: entry.status });
|
|
const bytes = entry.gate ? await entry.gate : entry.bytes;
|
|
return new Response(bytes, { headers: { 'content-length': String(bytes.length) } });
|
|
}
|
|
|
|
// ---------- scenarios ----------
|
|
const cacheDirName = `teamspeach-updater-harness-${process.pid}`;
|
|
const updateConfig = path.join(tmp, 'app-update.yml');
|
|
fs.writeFileSync(updateConfig, `provider: generic\nurl: https://git.eeee.moe/\nupdaterCacheDirName: ${cacheDirName}\n`);
|
|
|
|
function service({ channel = 'preview', sessionActive = false, feedTimeoutMs, profileOverride = null, electronApp = app, installCalls = null } = {}) {
|
|
const prefsValues = { updateChannel: channel };
|
|
const session = { active: sessionActive };
|
|
const svc = createUpdateService({
|
|
prefs: { get: () => ({ ...prefsValues }), set: (p) => Object.assign(prefsValues, p) },
|
|
isSessionActive: () => session.active,
|
|
send: () => {},
|
|
target: TARGET,
|
|
feedTimeoutMs,
|
|
profileOverride,
|
|
electronApp,
|
|
createUpdater: (t, logger, ch) => {
|
|
const u = createElectronUpdater(t, logger, ch);
|
|
u.forceDevUpdateConfig = true;
|
|
u.updateConfigPath = updateConfig;
|
|
// Recorded instead of executed: the harness never installs or quits.
|
|
if (installCalls) u.quitAndInstall = (...args) => installCalls.push(args);
|
|
return u;
|
|
},
|
|
});
|
|
return { svc, session };
|
|
}
|
|
|
|
function reset() {
|
|
releases = [];
|
|
files.clear();
|
|
requests.length = 0;
|
|
}
|
|
|
|
const pick = (s) => ({ phase: s.phase, available: s.available && s.available.version, error: s.error, newerWithoutBuild: s.newerWithoutBuild, newerPreview: s.newerPreview, lastCheckedAt: s.lastCheckedAt });
|
|
|
|
function cachedPackageSha() {
|
|
const dir = path.join(process.env.LOCALAPPDATA || process.env.XDG_CACHE_HOME, cacheDirName, 'pending');
|
|
const name = fs.existsSync(dir) ? fs.readdirSync(dir).find((n) => n !== 'update-info.json' && !n.startsWith('temp')) : null;
|
|
return name ? sha512(fs.readFileSync(path.join(dir, name))) : null;
|
|
}
|
|
|
|
const scenarios = {
|
|
async happy() {
|
|
addRelease('v0.1.1');
|
|
const good = addRelease('v0.1.2-rc.2');
|
|
addRelease('v0.1.3', { draft: true });
|
|
const { svc } = service();
|
|
const s = await svc.check({ manual: true });
|
|
return {
|
|
...pick(s),
|
|
cachedShaMatches: cachedPackageSha() === sha512(good.bytes),
|
|
draftFetched: requests.some((r) => r.url.includes('/v0.1.3/')),
|
|
anyAuth: requests.some((r) => r.auth),
|
|
};
|
|
},
|
|
async sessionGate() {
|
|
addRelease('v0.1.2-rc.2');
|
|
const { svc } = service({ sessionActive: true });
|
|
const deferred = await svc.check({ manual: false });
|
|
const packageRequestedWhileDeferred = requests.some((r) => /\.(exe|AppImage)(\?|$)/.test(r.url));
|
|
const downloaded = await svc.download({ manual: true });
|
|
const install = svc.install({});
|
|
return { deferred: deferred.phase, packageRequestedWhileDeferred, downloaded: downloaded.phase, install, stillDownloaded: svc.getState().phase };
|
|
},
|
|
async checksum() {
|
|
addRelease('v0.1.2-rc.2', { corrupt: true });
|
|
const { svc } = service();
|
|
const s = await svc.check({ manual: true });
|
|
return { ...pick(s), install: svc.install({ confirmInterrupt: true }) };
|
|
},
|
|
async wrongArch() {
|
|
addRelease('v0.1.3', { otherArch: true });
|
|
addRelease('v0.1.2-rc.2');
|
|
const { svc } = service();
|
|
return pick(await svc.check({ manual: true }));
|
|
},
|
|
async missingFeedFile() {
|
|
addRelease('v0.1.3', { feedStatus: 404 });
|
|
const { svc } = service();
|
|
return pick(await svc.check({ manual: true }));
|
|
},
|
|
async timeoutThenLateResult() {
|
|
let open;
|
|
const gate = new Promise((r) => {
|
|
open = r;
|
|
});
|
|
addRelease('v0.1.3', { gate });
|
|
const { svc, session } = service({ feedTimeoutMs: 1500 });
|
|
const timedOut = pick(await svc.check({ manual: true }));
|
|
reset();
|
|
addRelease('v0.1.2-rc.2');
|
|
const second = pick(await svc.check({ manual: true }));
|
|
open();
|
|
await new Promise((r) => setTimeout(r, 1500));
|
|
session.active = true;
|
|
return { timedOut, second, afterLate: pick(svc.getState()), install: svc.install({}) };
|
|
},
|
|
async networkDown() {
|
|
releases = 'network-error';
|
|
const { svc } = service();
|
|
return pick(await svc.check({ manual: true }));
|
|
},
|
|
async stableChannel() {
|
|
addRelease('v0.1.2-rc.2');
|
|
addRelease('v0.1.3', { prerelease: true });
|
|
const { svc } = service({ channel: 'stable' });
|
|
return pick(await svc.check({ manual: true }));
|
|
},
|
|
async customProfile() {
|
|
addRelease('v0.1.2-rc.2');
|
|
const installCalls = [];
|
|
const relaunches = [];
|
|
let quits = 0;
|
|
const fakeApp = { getVersion: () => app.getVersion(), isPackaged: false, relaunch: (o) => relaunches.push(o), quit: () => (quits += 1) };
|
|
const { svc } = service({ profileOverride: path.join(tmp, 'custom-profile'), electronApp: fakeApp, installCalls });
|
|
const checked = await svc.check({ manual: true });
|
|
const afterManualDownload = (await svc.download({ manual: true })).phase;
|
|
const install = svc.install({ confirmInterrupt: true });
|
|
return {
|
|
target: TARGET.kind,
|
|
mode: checked.mode,
|
|
manualReason: checked.manualReason,
|
|
phase: checked.phase,
|
|
available: checked.available && checked.available.version,
|
|
afterManualDownload,
|
|
packageRequested: requests.some((r) => /\.(exe|AppImage)(\?|$)/.test(r.url)),
|
|
install,
|
|
installCalls,
|
|
relaunches: relaunches.map((o) => ({ execPathIsAppImage: o.execPath === process.env.APPIMAGE })),
|
|
quits,
|
|
};
|
|
},
|
|
async sameAndOlder() {
|
|
addRelease('v0.1.2-rc.1');
|
|
addRelease('v0.1.1');
|
|
addRelease('v0.1.2-beta.9');
|
|
const { svc } = service();
|
|
const s = pick(await svc.check({ manual: true }));
|
|
return { ...s, feedRequests: requests.filter((r) => r.url.endsWith('.yml') || r.url.includes('.yml?')).length };
|
|
},
|
|
};
|
|
|
|
/** UPDATE_HARNESS_LIVE=1: the REAL release server, no interception; checks and downloads, never installs. */
|
|
async function live() {
|
|
const { svc } = service({ channel: process.env.UPDATE_HARNESS_CHANNEL || 'preview' });
|
|
const s = await svc.check({ manual: true });
|
|
const out = { ...pick(s), target: TARGET.id, cachedSha512: cachedPackageSha() };
|
|
if (s.available) {
|
|
const feedName = source.feedFileName(TARGET, s.available.version);
|
|
const res = await fetch(`${source.releaseDownloadBase(s.available.tag)}${feedName}`);
|
|
const feed = await res.text();
|
|
out.feed = { name: feedName, sha512: (/^ {4}sha512: (\S+)$/m.exec(feed) || [])[1], url: (/^ {2}- url: (\S+)$/m.exec(feed) || [])[1] };
|
|
out.cachedMatchesFeed = out.cachedSha512 === out.feed.sha512;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
async function run() {
|
|
const results = { version: app.getVersion(), target: TARGET.id };
|
|
if (process.env.UPDATE_HARNESS_LIVE === '1') {
|
|
results.live = await live();
|
|
process.stdout.write(`UPDATE_HARNESS_RESULT ${JSON.stringify(results)}\n`);
|
|
return;
|
|
}
|
|
for (const ses of [session.defaultSession, session.fromPartition('electron-updater', { cache: false })]) ses.protocol.handle('https', handle);
|
|
for (const [name, fn] of Object.entries(scenarios)) {
|
|
reset();
|
|
try {
|
|
results[name] = await fn();
|
|
} catch (err) {
|
|
results[name] = { thrown: err && err.stack ? err.stack : String(err) };
|
|
}
|
|
}
|
|
process.stdout.write(`UPDATE_HARNESS_RESULT ${JSON.stringify(results)}\n`);
|
|
}
|
|
|
|
app.whenReady().then(run).then(
|
|
() => app.exit(0),
|
|
(err) => {
|
|
process.stdout.write(`UPDATE_HARNESS_FATAL ${err && err.stack}\n`);
|
|
app.exit(1);
|
|
},
|
|
);
|