Signed per-component updater, release 1.1.55

This commit is contained in:
2026-10-30 22:38:38 -07:00
parent 0c6a9d1e5b
commit 79dd5e7465
10 changed files with 586 additions and 162 deletions

267
main.js
View File

@@ -82,6 +82,11 @@ function getReplacementsConfig() {
} catch (e) { return {}; }
}
function liveReposEnabled() {
const cfg = getEnvConfig();
return !!(cfg.updater && cfg.updater.liveRepos === true);
}
const updateClient = new UpdateClient(APPDATA_DIR);
const fileUpdater = new FileUpdater(APPDATA_DIR, updateClient);
fileUpdater.onNotice = (message) => sendToTauri('notice', { message });
@@ -122,93 +127,113 @@ async function start() {
const patcher = new Patcher(APPDATA_DIR);
serviceManager = new ServiceManager(APPDATA_DIR, getEnvConfig());
const installBuild = async (release) => {
const tempZipPath = path.join(APPDATA_DIR, 'download-temp.zip');
if (fs.existsSync(tempZipPath)) {
try { fs.unlinkSync(tempZipPath); } catch (e) { }
}
let attempts = 0;
let downloadSuccess = false;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
while (attempts < 3 && !downloadSuccess) {
attempts++;
const downloadVerified = async (name, item, dest) => {
let lastError;
for (let attempt = 1; attempt <= 3; attempt++) {
fs.rmSync(dest, { force: true });
try {
debugLog(`Attempting to download update (Attempt ${attempts})...`);
sendToTauri('status', { message: `Connecting to download servers (Attempt ${attempts}/3)...` });
sendToTauri('status', { message: `Downloading ${name} (attempt ${attempt}/3)...` });
let lastPercent = -1;
await updateClient.downloadUpdate(release, tempZipPath, (downloaded, total) => {
await updateClient.downloadUpdate(item, dest, (downloaded, total) => {
const percent = total > 0 ? Math.round((downloaded / total) * 100) : 0;
if (percent !== lastPercent) {
lastPercent = percent;
sendToTauri('download-progress', { downloaded, total, percent });
}
});
debugLog('Download complete. Verifying checksum...');
sendToTauri('status', { message: 'Verifying SHA-256 integrity...' });
if (!release.sha256) {
throw new Error('Release has no SHA-256 in manifest.json; refusing unverified install.');
}
if (!patcher.verifyChecksum(tempZipPath, release.sha256)) {
sendToTauri('status', { message: `Verifying ${name} SHA-256...` });
if (!patcher.verifyChecksum(dest, item.sha256)) {
throw new Error('SHA-256 checksum verification failed.');
}
return;
} catch (err) {
lastError = err;
fs.rmSync(dest, { force: true });
debugLog(`Download error for ${name} on attempt ${attempt}: ${err.message}`);
if (attempt < 3) {
await sleep(err.retryAfterMs || 2000 * 2 ** (attempt - 1) + Math.floor(Math.random() * 500));
}
}
}
throw new Error(`Failed to download ${name} after 3 attempts: ${lastError.message}`);
};
debugLog('Checksum verified. Extracting to staging...');
sendToTauri('status', { message: 'Unpacking update archive...' });
const installBuild = async (release) => {
const names = patcher.staleComponents(release);
if (names.length === 0) return;
const stagingDir = path.join(APPDATA_DIR, '.staging');
fs.rmSync(stagingDir, { recursive: true, force: true });
fs.mkdirSync(stagingDir, { recursive: true });
const tempFiles = [];
try {
for (let i = 0; i < names.length; i++) {
const name = names[i];
const tempZip = path.join(APPDATA_DIR, `download-${name}.zip`);
tempFiles.push(tempZip);
await downloadVerified(name, release.components[name], tempZip);
sendToTauri('status', { message: `Unpacking ${name}...` });
let lastEmit = 0;
const stagingDir = await patcher.extractToStaging(tempZipPath, (file, done, total) => {
await patcher.extractToStaging(tempZip, (file, done, total) => {
const now = Date.now();
if (done !== total && now - lastEmit < 40) return;
lastEmit = now;
sendToTauri('extract-progress', {
file,
done,
total,
percent: Math.round((done / total) * 100)
});
});
sendToTauri('status', { message: 'Verifying file integrity...' });
if (!patcher.verifyExtraction(stagingDir)) {
fs.rmSync(stagingDir, { recursive: true, force: true });
throw new Error('Extraction verification failed: critical startup files missing.');
}
sendToTauri('status', { message: 'Replacing old version...' });
patcher.commitStaging(stagingDir);
debugLog('Extraction complete. Applying patches...');
sendToTauri('status', { message: 'Applying configuration patches...' });
fileUpdater.snapshotBase();
patcher.applyPatches(getReplacementsConfig());
sendToTauri('status', { message: 'Migrating security credentials...' });
patcher.bridgeCredentials(serviceManager.credentialManager);
patcher.saveCurrentVersion(release.version, release.sha256);
serviceManager.envConfig = getEnvConfig();
if (fs.existsSync(tempZipPath)) {
fs.unlinkSync(tempZipPath);
}
downloadSuccess = true;
debugLog('Update installed successfully!');
} catch (err) {
debugLog(`Download/Install error on attempt ${attempts}: ${err.message}`);
sendToTauri('status', { message: `Install error: ${err.message}. Retrying...` });
if (fs.existsSync(tempZipPath)) {
try { fs.unlinkSync(tempZipPath); } catch (e) { }
}
if (attempts >= 3) {
throw new Error(`Failed to download and verify build after 3 attempts: ${err.message}`);
}
await new Promise(r => setTimeout(r, 2000));
sendToTauri('extract-progress', { file, done, total, percent: Math.round((done / total) * 100) });
}, i > 0);
fs.rmSync(tempZip, { force: true });
}
sendToTauri('status', { message: 'Verifying file integrity...' });
if (!patcher.verifyStaged(stagingDir, names)) {
throw new Error('Extraction verification failed: critical startup files missing.');
}
sendToTauri('status', { message: 'Replacing old version...' });
patcher.commitStaging(stagingDir);
} catch (err) {
fs.rmSync(stagingDir, { recursive: true, force: true });
for (const f of tempFiles) fs.rmSync(f, { force: true });
throw err;
}
try {
sendToTauri('status', { message: 'Applying configuration patches...' });
patcher.applyPatches(getReplacementsConfig(), names);
sendToTauri('status', { message: 'Migrating security credentials...' });
patcher.bridgeCredentials(serviceManager.credentialManager);
if (!patcher.verifyExtraction()) {
throw new Error('Post-install verification failed.');
}
const current = patcher.getCurrentComponents();
const next = {};
for (const name of Object.keys(release.components)) {
next[name] = names.includes(name) ? release.components[name].id : current[name];
}
patcher.saveCurrentVersion(release.version, release.sha256, next);
} catch (err) {
try { patcher.rollback(); } catch (x) { debugLog(`Rollback failed: ${x.message}`); }
throw err;
}
patcher.finalizeCommit();
if (liveReposEnabled()) fileUpdater.snapshotBase();
serviceManager.envConfig = getEnvConfig();
debugLog(`Update installed successfully: ${names.join(', ')}`);
};
try {
if (patcher.recoverInterrupted()) {
debugLog('Recovered from an interrupted update.');
sendToTauri('notice', { message: 'Recovered from an interrupted update.' });
}
fileUpdater.recoverSdk();
sendToTauri('status', { message: 'Inspecting local workspace and installed files...' });
const isFirstRun = !patcher.verifyExtraction();
const localVersion = patcher.getCurrentVersion();
@@ -219,10 +244,10 @@ async function start() {
let release = null;
try {
debugLog("Fetching updates from updateClient...");
release = await updateClient.checkForUpdates();
release = await updateClient.checkForUpdates(isFirstRun);
debugLog(`Update check finished. Found: ${release ? release.version : 'None'}`);
} catch (e) {
debugLog(`Update check failed (offline?): ${e.message}`);
debugLog(`Update check failed: ${e.message}`);
sendToTauri('notice', { message: `Update check skipped: ${e.message}` });
}
@@ -240,44 +265,73 @@ async function start() {
};
if (release) {
const versionNewer = isNewer(release.version, localVersion);
const sameVerNewBuild = normalizeVer(release.version) === normalizeVer(localVersion) &&
!!release.sha256 && !!localSha && release.sha256 !== localSha;
const hasUpdate = versionNewer || sameVerNewBuild;
const stale = patcher.staleComponents(release);
const broken = stale.some((name) => !patcher.componentIntact(name));
const sameVersion = normalizeVer(release.version) === normalizeVer(localVersion);
const hasUpdate = stale.length > 0 && (broken || isNewer(release.version, localVersion) || sameVersion);
if (isFirstRun) {
debugLog("First run with no local payload. Installing remote build...");
sendToTauri('status', { message: 'First run detected. Preparing initial installation...' });
await installBuild(release);
} else if (hasUpdate) {
debugLog("Update available. Installing update...");
sendToTauri('status', { message: `Updating to ${release.version}...` });
await installBuild(release);
if (hasUpdate) {
debugLog(`Installing components: ${stale.join(', ')}`);
sendToTauri('status', {
message: isFirstRun ? 'First run detected. Preparing initial installation...' : `Updating to ${release.version}...`
});
try {
await installBuild(release);
updateClient.recordSuccess();
} catch (err) {
updateClient.recordFailure();
debugLog(`Update failed: ${err.message}`);
sendToTauri('notice', { message: `Update failed: ${err.message}` });
}
} else {
debugLog("Already on the latest version.");
sendToTauri('status', { message: 'Up to date.' });
}
} else if (isFirstRun) {
debugLog("No remote release found, but it's the first run. Looking for local update-payload.zip...");
}
if (!patcher.verifyExtraction()) {
debugLog("No usable install. Looking for local update-payload.zip...");
sendToTauri('status', { message: 'Looking for local payload archive...' });
const localZip = path.join(__dirname, 'update-payload.zip');
if (fs.existsSync(localZip)) {
const payloadRoots = [
process.env.VYLA_PAYLOAD_DIR,
__dirname,
process.cwd(),
path.resolve(__dirname, '..', '..', '..', '..'),
APPDATA_DIR
].filter(Boolean);
const payloadRoot = payloadRoots.find((r) => fs.existsSync(path.join(r, 'update-payload.zip')));
const localZip = payloadRoot ? path.join(payloadRoot, 'update-payload.zip') : null;
if (localZip) {
sendToTauri('status', { message: 'Extracting local baseline payload...' });
patcher.purgeOldCode();
patcher.extractZipPayload(localZip);
fileUpdater.snapshotBase();
patcher.applyPatches(getReplacementsConfig());
patcher.bridgeCredentials(serviceManager.credentialManager);
const stagingDir = await patcher.extractToStaging(localZip);
if (!patcher.verifyStaged(stagingDir, ['frontend', 'player'])) {
fs.rmSync(stagingDir, { recursive: true, force: true });
throw new Error('Bundled payload is incomplete.');
}
patcher.commitStaging(stagingDir);
let ver = "1.0.0";
let manSha = null;
try {
const man = JSON.parse(fs.readFileSync(path.join(__dirname, 'manifest.json'), 'utf8'));
ver = man.version || ver;
manSha = man.sha256 || null;
} catch (e) { }
patcher.applyPatches(getReplacementsConfig());
patcher.bridgeCredentials(serviceManager.credentialManager);
patcher.saveCurrentVersion(ver, manSha);
let ver = "1.0.0";
let manSha = null;
let ids = {};
try {
const man = JSON.parse(fs.readFileSync(path.join(payloadRoot, 'manifest.json'), 'utf8'));
ver = man.version || ver;
manSha = man.sha256 || null;
ids = Object.fromEntries(Object.entries(man.components || {}).map(([k, v]) => [k, v.id]));
} catch (e) { }
patcher.saveCurrentVersion(ver, manSha, ids);
} catch (e) {
try { patcher.rollback(); } catch (x) { }
throw e;
}
patcher.finalizeCommit();
if (liveReposEnabled()) fileUpdater.snapshotBase();
serviceManager.envConfig = getEnvConfig();
debugLog("Local payload extracted successfully.");
} else {
@@ -287,23 +341,28 @@ async function start() {
sendToTauri('status', { message: 'Validating critical components...' });
if (!patcher.verifyExtraction()) {
throw new Error('Could not download the app files. Check your internet connection and relaunch.');
throw new Error('No usable install and no valid signed release or bundled payload was found. Check your internet connection and relaunch, or reinstall the app.');
}
sendToTauri('status', { message: 'Checking UI files and SDK...' });
const liveRepos = liveReposEnabled();
sendToTauri('status', { message: liveRepos ? 'Checking UI files and SDK...' : 'Checking SDK...' });
const [filesCheck, sdkCheck] = await Promise.all([
withTimeout(fileUpdater.checkRepos().catch((e) => {
debugLog(`Live file check failed: ${e.message}`);
sendToTauri('notice', { message: `File check failed: ${e.message}` });
return null;
}), 240000),
liveRepos
? withTimeout(fileUpdater.checkRepos().catch((e) => {
debugLog(`Live file check failed: ${e.message}`);
sendToTauri('notice', { message: `File check failed: ${e.message}` });
return null;
}), 60000)
: Promise.resolve(null),
withTimeout(fileUpdater.checkSdk().catch((e) => {
debugLog(`SDK check failed: ${e.message}`);
sendToTauri('notice', { message: `SDK check failed: ${e.message}` });
return null;
}), 12000)
]);
debugLog(`Repo check result: ${filesCheck ? `${filesCheck.changes.length} change(s)` : 'failed or timed out'}`);
if (liveRepos) {
debugLog(`Repo check result: ${filesCheck ? `${filesCheck.changes.length} change(s)` : 'failed or timed out'}`);
}
if (filesCheck && (filesCheck.changes.length > 0 || filesCheck.removed.length > 0)) {
sendToTauri('status', { message: `Updating ${filesCheck.changes.length} file(s)...` });