Files
client/app/main/update-source.js
T
2026-10-24 06:34:33 +03:00

278 lines
13 KiB
JavaScript

'use strict';
// Where updates come from and which published release this installation may move to.
// Pure Node (no Electron): the complete Gitea release list is fetched anonymously from one fixed HTTPS host,
// releases are filtered by channel, version (semver) and platform, and only complete releases are offered.
// electron-updater then reads the feed of the chosen release and verifies size and sha512.
const path = require('node:path');
const semver = require('semver');
const FORGE_ORIGIN = 'https://git.eeee.moe';
const OWNER = 'TeamsPeach';
const REPO = 'client';
const RELEASES_API = `${FORGE_ORIGIN}/api/v1/repos/${OWNER}/${REPO}/releases`;
const PAGE_SIZE = 50;
const MAX_PAGES = 20;
const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
const PRODUCT = 'TeamsPeach';
const LINUX_EXECUTABLE = 'teamspeach';
const ASSET_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
const SHA512_BASE64 = /^[A-Za-z0-9+/]{86}==$/;
/**
* Failure with a stable machine code and parameters; the renderer shows the localized text for `code`.
* `message` is English technical text for logs only.
*/
class UpdateError extends Error {
constructor(code, params = {}, message = code) {
super(message);
this.code = code;
this.params = params;
}
}
/** Strict SemVer 2.0 without build metadata (`0.1.2`, `0.1.2-rc.1`); null otherwise (`01.1.1`, `0.1`, `1.0.0+x`). */
function cleanVersion(text) {
if (typeof text !== 'string' || text.includes('+')) return null;
return semver.valid(text) === text ? text : null;
}
/** Release tag `v<version>`; returns the version or null. */
function tagVersion(tag) {
return typeof tag === 'string' && tag.startsWith('v') ? cleanVersion(tag.slice(1)) : null;
}
/**
* What this installation is and how it can be updated.
* mode 'auto': electron-updater installs (NSIS-installed Windows x64, Linux AppImage).
* mode 'manual': user is told and replaces files himself (Windows zip, Linux tar.gz).
* mode 'none': dev run or a platform that has no published build.
*/
function detectTarget({ platform, arch, packaged, env, execPath, exists }) {
const none = (id, disabledCode) => ({ id, platform, arch, mode: 'none', kind: null, disabledCode });
if (!packaged) return none(`${platform}-${arch}-dev`, 'dev-build');
if (platform === 'win32') {
if (arch !== 'x64') return none(`win-${arch}`, 'unsupported-platform');
// The NSIS installer leaves its uninstaller next to the executable; the portable zip does not.
if (exists(path.join(path.dirname(execPath), `Uninstall ${PRODUCT}.exe`))) {
return { id: 'win-x64-nsis', platform, arch, mode: 'auto', kind: 'nsis', disabledCode: null };
}
return { id: 'win-x64-zip', platform, arch, mode: 'manual', kind: 'zip', disabledCode: null };
}
if (platform === 'linux') {
if (arch !== 'x64' && arch !== 'arm64') return none(`linux-${arch}`, 'unsupported-platform');
if (env.APPIMAGE) return { id: `linux-${arch}-appimage`, platform, arch, mode: 'auto', kind: 'appimage', disabledCode: null };
return { id: `linux-${arch}-tar.gz`, platform, arch, mode: 'manual', kind: 'tar.gz', disabledCode: null };
}
if (platform === 'darwin') return none(`mac-${arch}`, 'unsupported-platform');
return none(`${platform}-${arch}`, 'unsupported-platform');
}
/** electron-builder names the feed after the version's first prerelease identifier, else "latest". */
function feedChannel(version) {
const pre = semver.prerelease(version);
return pre && pre.length > 0 ? String(pre[0]) : 'latest';
}
/** Exact feed file electron-builder writes for this target (app-builder-lib getUpdateInfoFileName). */
function feedFileName(target, version) {
const channel = feedChannel(version);
if (target.kind === 'nsis') return `${channel}.yml`;
if (target.kind === 'appimage') return target.arch === 'x64' ? `${channel}-linux.yml` : `${channel}-linux-${target.arch}.yml`;
return null;
}
/**
* Exact installer electron-builder produces for this target (package.json build config: AppImage default
* name, nsis.artifactName "${productName}-${version}-win-${arch}-setup.${ext}").
*/
function packageFileName(target, version) {
if (target.kind === 'appimage') return target.arch === 'x64' ? `${PRODUCT}-${version}.AppImage` : `${PRODUCT}-${version}-${target.arch}.AppImage`;
if (target.kind === 'nsis') return `${PRODUCT}-${version}-win-${target.arch}-setup.exe`;
return null;
}
/** Package names a manual-mode user downloads (builder defaults, plus the historical "-local" Windows zip). */
function manualAssetNames(target, version) {
if (target.kind === 'tar.gz') return [target.arch === 'x64' ? `${LINUX_EXECUTABLE}-${version}.tar.gz` : `${LINUX_EXECUTABLE}-${version}-${target.arch}.tar.gz`];
if (target.kind === 'zip') return [`${PRODUCT}-${version}-win-x64.zip`, `${PRODUCT}-${version}-win.zip`, `${PRODUCT}-${version}-win-x64-local.zip`];
return [];
}
function releaseDownloadBase(tag) {
return `${FORGE_ORIGIN}/${OWNER}/${REPO}/releases/download/${tag}/`;
}
function releasePageUrl(tag) {
return `${FORGE_ORIGIN}/${OWNER}/${REPO}/releases/tag/${tag}`;
}
/**
* Picks the releases this installation may update to, newest first.
* Every published, non-draft release with a valid tag is considered. A release is "preview" when Gitea
* marks it prerelease or its version has a prerelease part; the stable channel never sees previews.
* Same or older versions are never offered. A release counts only when it carries this target's feed and
* installer (auto) or package (manual); newer releases without one are reported in `withoutBuild`.
*/
function selectReleases(releases, { currentVersion, channel, target }) {
const current = cleanVersion(currentVersion);
if (!current) throw new UpdateError('bad-version', { version: String(currentVersion) }, `app version ${currentVersion} is not semver`);
if (channel !== 'preview' && channel !== 'stable') throw new UpdateError('bad-channel', { channel: String(channel) }, `unknown channel ${channel}`);
if (!Array.isArray(releases)) throw new UpdateError('bad-response', { detail: 'release list is not an array' }, 'release list is not an array');
const candidates = [];
const withoutBuild = [];
const previews = [];
for (const release of releases) {
if (!release || typeof release !== 'object' || release.draft !== false) continue;
const version = tagVersion(release.tag_name);
if (!version || !semver.gt(version, current)) continue;
const preview = release.prerelease !== false || semver.prerelease(version) !== null;
if (channel === 'stable' && preview) {
previews.push(version);
continue;
}
const assets = new Map();
for (const asset of Array.isArray(release.assets) ? release.assets : []) {
if (asset && typeof asset.name === 'string' && ASSET_NAME.test(asset.name) && Number.isSafeInteger(asset.size) && asset.size > 0) {
assets.set(asset.name, asset.size);
}
}
const tag = release.tag_name;
const entry = {
tag,
version,
preview,
publishedAt: typeof release.published_at === 'string' ? release.published_at : null,
assets,
downloadBase: releaseDownloadBase(tag),
releaseUrl: releasePageUrl(tag),
feedChannel: feedChannel(version),
feedFile: null,
packageFile: null,
manualAsset: null,
};
if (target.mode === 'auto') {
const feed = feedFileName(target, version);
const pkg = packageFileName(target, version);
if (!assets.has(feed) || !assets.has(pkg)) {
const missing = assets.has(feed) ? pkg : feed;
withoutBuild.push({ version, code: assets.has(feed) ? 'no-package' : 'no-feed', params: { version, file: missing, target: target.id } });
continue;
}
entry.feedFile = feed;
entry.packageFile = pkg;
} else if (target.mode === 'manual') {
const name = manualAssetNames(target, version).find((n) => assets.has(n));
if (!name) {
withoutBuild.push({ version, code: 'no-package', params: { version, file: manualAssetNames(target, version)[0], target: target.id } });
continue;
}
entry.manualAsset = name;
} else {
continue;
}
candidates.push(entry);
}
candidates.sort((a, b) => semver.rcompare(a.version, b.version));
withoutBuild.sort((a, b) => semver.rcompare(a.version, b.version));
previews.sort(semver.rcompare);
return { candidates, withoutBuild, newestPreview: previews.length > 0 ? previews[0] : null };
}
/**
* Checks the feed electron-updater parsed against the release it was taken from: same version, and exactly
* one package — this target's installer by its exact builder name (so an arm64 feed pointing at the x64
* AppImage, or a renamed/foreign file, is refused) — present in THIS release with the declared size and a sha512.
*/
function verifyFeed(candidate, target, updateInfo) {
const mismatch = (detail) => new UpdateError('feed-mismatch', { tag: candidate.tag, detail }, `${candidate.tag}: ${detail}`);
if (!updateInfo || typeof updateInfo !== 'object') throw mismatch('feed is empty');
if (cleanVersion(updateInfo.version) !== candidate.version) throw mismatch(`feed describes version ${String(updateInfo.version)}`);
const expected = packageFileName(target, candidate.version);
const files = Array.isArray(updateInfo.files) ? updateInfo.files : [];
if (files.length !== 1 || !files[0] || files[0].url !== expected) {
const listed = files.map((f) => (f && typeof f.url === 'string' ? f.url : '?')).join(', ') || 'nothing';
throw mismatch(`feed for ${target.id} must list only ${expected}, lists: ${listed}`);
}
if (updateInfo.path !== undefined && updateInfo.path !== expected) throw mismatch(`feed path ${String(updateInfo.path)} is not ${expected}`);
const file = files[0];
if (typeof file.sha512 !== 'string' || !SHA512_BASE64.test(file.sha512)) throw mismatch(`no sha512 for ${expected}`);
if (!candidate.assets.has(expected)) {
throw new UpdateError('incomplete-release', { tag: candidate.tag, file: expected }, `${candidate.tag} has no asset ${expected}`);
}
if (file.size !== candidate.assets.get(expected)) {
throw new UpdateError('incomplete-release', { tag: candidate.tag, file: expected }, `${candidate.tag}: size of ${expected} differs from the feed`);
}
}
/**
* Anonymous GET of EVERY published release (paged; Gitea reports the total in X-Total-Count).
* `fetchImpl` is Electron's net.fetch in the app. Network failure, timeout (whole listing), HTTP errors,
* malformed bodies and a listing that cannot be completed within MAX_PAGES all throw UpdateError —
* never a partial list that could hide a newer release.
*/
async function fetchReleases({ fetchImpl, timeoutMs = 20000 }) {
const badResponse = (detail) => new UpdateError('bad-response', { detail }, `release list: ${detail}`);
const signal = AbortSignal.timeout(timeoutMs);
const all = [];
let total = null;
for (let page = 1; page <= MAX_PAGES; page += 1) {
const url = `${RELEASES_API}?draft=false&limit=${PAGE_SIZE}&page=${page}`;
let text;
let headerTotal;
try {
const res = await fetchImpl(url, { signal, redirect: 'error', cache: 'no-store', headers: { Accept: 'application/json' } });
if (!res.ok) throw new UpdateError('http', { status: res.status }, `release list: HTTP ${res.status}`);
if (Number(res.headers.get('content-length')) > MAX_RESPONSE_BYTES) throw badResponse('response too large');
headerTotal = res.headers.get('x-total-count');
text = await res.text();
} catch (err) {
if (err instanceof UpdateError) throw err;
const seconds = Math.round(timeoutMs / 1000);
if (signal.aborted) throw new UpdateError('timeout', { seconds }, `release list: no answer in ${seconds} s`);
const detail = err && err.cause && err.cause.message ? `${err.message}: ${err.cause.message}` : String(err && err.message ? err.message : err);
throw new UpdateError('network', { detail }, `release list: ${detail}`);
}
if (text.length > MAX_RESPONSE_BYTES) throw badResponse('response too large');
let items;
try {
items = JSON.parse(text);
} catch {
throw badResponse('not JSON');
}
if (!Array.isArray(items)) throw badResponse('not a release list');
if (headerTotal !== null) {
if (!/^\d+$/.test(headerTotal)) throw badResponse('invalid X-Total-Count');
total = Number(headerTotal);
}
all.push(...items);
// Done when the server's total is reached, or (no total reported) when a page comes back empty.
if (total !== null ? all.length >= total || items.length === 0 : items.length === 0) {
if (total !== null && all.length < total) {
throw new UpdateError('incomplete-list', { fetched: all.length, total }, `release list: got ${all.length} of ${total}`);
}
return all;
}
}
throw new UpdateError('incomplete-list', { fetched: all.length, total }, `release list longer than ${MAX_PAGES} pages`);
}
module.exports = {
FORGE_ORIGIN,
RELEASES_API,
PAGE_SIZE,
UpdateError,
cleanVersion,
detectTarget,
feedFileName,
packageFileName,
manualAssetNames,
releaseDownloadBase,
releasePageUrl,
selectReleases,
verifyFeed,
fetchReleases,
};