"use strict"; // Khaos auto-update for the installed client (docs/LAUNCH.md section 4). Required by player.cjs. // // Feed (khaos-build.json env.updates, R2 download.khaosdofus.com/khaos/stable/), written by client/release/publish.mjs: // khaos-manifest.json (+ .sig) the Khaos release manifest, Ed25519-signed (raw bytes; public key in khaos-build.json). // Auth reads its clientVersion to refuse outdated clients (KHAOS_CLIENT_MANIFEST_URL). // latest.yml, Khaos-Setup-.exe(.blockmap) electron-builder's NSIS feed: electron-updater downloads only // the changed blocks of the installer (differential download), runs it with its progress // window (updateFlow.cjs visibleInstallArgs), restarts. // latest-mac.yml, Khaos--mac.zip(.blockmap) the macOS feed (manifest "mac"). Squirrel.Mac only swaps an app // signed with the same Developer ID, so only a Developer ID build (khaos-build.json // macSigned) updates itself; any other macOS build offers the website download instead. // latest-linux.yml, Khaos--x86_64.AppImage the Linux feed (manifest "linux"). AppImageUpdater writes the new // AppImage over the one the player started ($APPIMAGE; differential through the blockmap // embedded in the AppImage). Linux has no code signing: the file must match the signed // manifest before it replaces anything. Not started as an AppImage: website download. // Order: the signed manifest decides whether there is an update; electron-updater downloads it; before installing, // the downloaded installer's sha512 must equal the signed manifest's (verifyUpdateCodeSignature). An unsigned or // mismatching feed is never installed. No feed / offline: the installed version keeps running (Auth refuses it // once a newer release is published, with the "restart through the launcher" message). const crypto = require("crypto"); const { execFileSync, spawn } = require("child_process"); const fs = require("fs"); const path = require("path"); const { app, dialog, shell, BrowserWindow, webContents } = require("electron"); const texts = require("./texts.cjs"); const { verifySigned } = require("./assetRoot.cjs"); const { createUpdateFlow, installMarkerPath, writeInstallMarker, dropInstallMarker, visibleInstallArgs } = require("./updateFlow.cjs"); const zlib = require("zlib"); const nodeFetch = globalThis.fetch; // captured before main.cjs wraps fetch (it blocks remote https) const MAC = process.platform === "darwin"; const LINUX = process.platform === "linux"; const WIN = !MAC && !LINUX; /** The signed manifest's package for this platform, and its name in logs. */ const PACKAGE_KEY = MAC ? "mac" : LINUX ? "linux" : "installer"; const PLATFORM_NAME = MAC ? "macOS" : LINUX ? "Linux" : "Windows"; /** Semver compare of x.y.z strings (the app versions are yyyy.mdd.n, client/release/lib.mjs parseClientVersion). */ function cmp(a, b) { const pa = String(a).split(".").map(Number); const pb = String(b).split(".").map(Number); for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) < (pb[i] || 0) ? -1 : 1; return 0; } /** The manifest's bytes, verified against khaos-manifest.json.sig with the build's public key; throws otherwise. */ async function fetchManifest(feed, publicKeys) { const get = async (name) => { const res = await nodeFetch(new URL(name, feed), { cache: "no-store", signal: AbortSignal.timeout(15000) }); if (!res.ok) throw new Error(`${name}: HTTP ${res.status}`); return Buffer.from(await res.arrayBuffer()); }; const [bytes, sig] = await Promise.all([get("khaos-manifest.json"), get("khaos-manifest.json.sig")]); // Signed by the hot or the cold release key (assetRoot.cjs verifySigned; owner question 7). if (!verifySigned(bytes, sig.toString("utf8"), publicKeys)) throw new Error("khaos-manifest.json: bad signature"); const manifest = JSON.parse(bytes.toString("utf8")); if (manifest.schemaVersion !== 1 || manifest.product !== "khaos" || !manifest.installer?.sha512) { throw new Error("khaos-manifest.json: unexpected content"); } return manifest; } /** * electron-updater's differential download diffs the new installer against `installer.exe` in its cache folder (the * installer of the installed version, copied there by every NSIS install) using `current.blockmap` from that folder * when present, else the feed's blockmap of the installed version. `current.blockmap` is written when an update is * downloaded, so after a manual reinstall (or a downloaded update that was never installed) it describes another * installer: the delta then fails its sha512 and the whole installer is downloaded (rehearsal: 121 MB instead of 2.6). * We note which version that blockmap belongs to (khaos-blockmap-version, written at update-downloaded) and drop it when * it is not the running version, so the feed's blockmap of the installed version is used. */ function updaterCacheDir() { try { const yml = fs.readFileSync(path.join(process.resourcesPath, "app-update.yml"), "utf8"); const name = /^updaterCacheDirName:\s*(.+?)\s*$/m.exec(yml)?.[1]; const base = process.env.LOCALAPPDATA; return name && base ? path.join(base, name.replace(/^['"]|['"]$/g, "")) : null; } catch { return null; } } function dropStaleBlockmap(version, log) { const dir = updaterCacheDir(); if (!dir) return; const blockmap = path.join(dir, "current.blockmap"); if (!fs.existsSync(blockmap)) return; let noted = ""; try { noted = fs.readFileSync(path.join(dir, "khaos-blockmap-version"), "utf8").trim(); } catch { /* none: written by an older client, or never */ } if (noted === version) return; try { fs.rmSync(blockmap, { force: true }); log(`updates: cached blockmap is for ${noted || "an unknown version"}, not ${version}; dropped (the feed's is used)`); } catch (e) { log(`updates: could not drop the cached blockmap (${e.message})`); } } function noteBlockmapVersion(version, log) { const dir = updaterCacheDir(); if (!dir) return; try { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, "khaos-blockmap-version"), version); } catch (e) { log(`updates: could not note the blockmap version (${e.message})`); } } /** * Security audit U6: electron-updater gunzips the two blockmaps it takes from the CDN (unsigned) with no output cap, * so a CDN-controlled bomb could exhaust the main process's memory during an update. Once an update is under way, * gunzipSync calls that pass no options of their own get a 64 MB output cap (a Khaos blockmap is ~0.5 MB unzipped). * Nothing else in the main process calls gunzipSync without options (khaos-delta.mjs passes its own cap). */ let gunzipCapped = false; function capBlockmapGunzip() { if (gunzipCapped) return; gunzipCapped = true; const gunzipSync = zlib.gunzipSync; zlib.gunzipSync = (buffer, options) => gunzipSync(buffer, options ?? { maxOutputLength: 64 * 1024 * 1024 }); } function sha512File(file) { return new Promise((resolve, reject) => { const h = crypto.createHash("sha512"); fs.createReadStream(file).on("data", (d) => h.update(d)).on("error", reject).on("end", () => resolve(h.digest("base64"))); }); } /** * macOS build that cannot replace itself (no Developer ID: Squirrel.Mac refuses it): the player is told a new version * is out and sent to the website's macOS download. Shown at every start while outdated (Auth refuses the old release). * Linux: the same for a Khaos that was not started as its AppImage ($APPIMAGE unset: extracted, repackaged). */ async function offerDownload({ build, manifest, log, userData }) { const page = new URL(LINUX ? "download/linux" : "download/macos", build.env.website || "https://play.khaosdofus.com/").href; log(`updates: ${manifest.clientVersion} must be downloaded (${page}): this build cannot update itself`); const { response } = await dialog.showMessageBox({ type: "info", title: "Khaos", message: texts.t(userData, "updateAvailableManual", manifest.clientVersion), detail: texts.t(userData, LINUX ? "updateAvailableManualDetailLinux" : "updateAvailableManualDetail"), buttons: [texts.t(userData, "download"), texts.t(userData, "later")], defaultId: 0, cancelId: 1, }); if (response === 0) await shell.openExternal(page).catch((e) => log(`updates: could not open ${page} (${e.message})`)); } exports.start = async function start({ build, logDir, log, userData }) { // The game's "update required" dialog reaches this flow through globalThis.__khaosUpdater (updateFlow.cjs header). let updater = null; // Windows: a relaunch while the silent installer replaces the files crashed (2026-10-16 19:26:16Z); the marker lets // the next start say "finishing the update" instead (player.cjs, updateFlow.cjs installGuard). // Linux swaps one file (mv) and starts it: nothing half-replaced to guard against. const marker = WIN ? installMarkerPath(logDir) : null; let verification = null; // the installer check started by update-downloaded let current = null; // { manifest, pkg } of the release being downloaded / installed const flow = createUpdateFlow({ log, install: () => { writeInstallMarker(marker, current.manifest.version, log); // Not silent, restart after: the installer shows its progress window (Windows: createUpdater's spawnLog wrapper // also covers the install-on-quit path, which electron-updater always asks for silently). updater.quitAndInstall(false, true); // electron-updater resets quitAndInstallCalled when it refused the install (no installer file, a failed spawn) and // only reports it as an "error" event: fail the attempt so the game's dialog offers a retry (updateFlow.cjs). if (updater.quitAndInstallCalled !== true) { dropInstallMarker(marker); throw new Error("electron-updater did not start the installer (see updater.log)"); } }, // The app did not quit after the installer started: let electron-updater install again on the next try. onStall: () => { dropInstallMarker(marker); if (updater) updater.quitAndInstallCalled = false; }, recheck: () => checkAndDownload("the game asked for the update"), }); globalThis.__khaosUpdater = flow; const feed = build.env.updates; const keys = Array.isArray(build.releasePublicKeys) && build.releasePublicKeys.length ? build.releasePublicKeys : [build.releasePublicKey].filter(Boolean); let modules = null; const updateLog = path.join(logDir, "updater.log"); const write = (level) => (m) => { try { fs.appendFileSync(updateLog, `${new Date().toISOString()} ${level} ${m}\n`); } catch { /* ignore */ } }; let verifiedFile = null; // Linux: the last downloaded AppImage that matched the signed manifest (install gate) const checkInstaller = async (file) => { const got = await sha512File(file); if (got !== current.pkg.sha512) { verifiedFile = null; return `${MAC ? "app zip" : LINUX ? "AppImage" : "installer"} sha512 ${got} differs from the signed manifest`; } verifiedFile = file; return null; }; // The download runs in the background: its progress shows on the taskbar button (cleared when done or failed) and in // a small in-game card (renderer khaos/updateNotice.js, window.__khaosUpdateNotice). Display only: no update logic here. const progress = (value) => { for (const w of BrowserWindow.getAllWindows()) if (!w.isDestroyed()) w.setProgressBar(value); }; // The game page is a WebContentsView inside the window (not the window's own webContents), so the notice goes to every // page. The card's code arrives with the khaos mod (in game only), after most of the download: the last state is left on // the page (window.__khaosUpdateState, shown when the card installs) and sent again after each page load. let lastNotice = null; const sendNotice = (contents) => { if (!lastNotice || contents.isDestroyed() || contents.getType() === "remote") return; const json = JSON.stringify(lastNotice); contents.executeJavaScript(`window.__khaosUpdateState = ${json}; window.__khaosUpdateNotice && window.__khaosUpdateNotice(${json})`).catch(() => {}); }; const notice = (info) => { lastNotice = info; for (const contents of webContents.getAllWebContents()) sendNotice(contents); }; app.on("web-contents-created", (_event, contents) => contents.on("did-finish-load", () => sendNotice(contents))); /** electron-updater, built once (the first time a release is found). */ function createUpdater() { const { NsisUpdater, MacUpdater, AppImageUpdater, ElectronAppAdapter, ElectronHttpExecutor } = modules; capBlockmapGunzip(); // The launcher keeps app.isPackaged false at runtime (the client's dev-mode paths); the updater must see a packaged app. class KhaosAppAdapter extends ElectronAppAdapter { get isPackaged() { return true; } get version() { return build.version; } } const Updater = MAC ? MacUpdater : LINUX ? AppImageUpdater : NsisUpdater; const u = new Updater(null, new KhaosAppAdapter()); // A custom app adapter leaves the HTTP executor unset (electron-updater's test hook): give it the real one, then the // feed (setFeedURL builds the provider with the executor it has at that moment). u.httpExecutor = new ElectronHttpExecutor((authInfo, callback) => u.emit("login", authInfo, callback)); // One Range per request: R2 (like the rehearsal stand-in) answers multi-range requests with the whole file, which // made electron-updater drop the differential download (rehearsal: 560 KB needed, 98 MB fetched). u.setFeedURL({ provider: "generic", url: feed, useMultipleRangeRequest: false }); u.disableWebInstaller = true; u.logger = { info: write("info"), warn: write("warn"), error: write("error"), debug: () => {} }; if (WIN) { // Every installer start goes through spawnLog (NsisUpdater.doInstall, also its elevate.exe fallback): the // arguments lose /S, and an install that must not restart the game gets the installer's no-run flag // (updateFlow.cjs visibleInstallArgs: owner 2026-11-11, "le dernier patch delete le launcher"). if (typeof u.spawnLog === "function") { const spawnLog = u.spawnLog.bind(u); u.spawnLog = (cmd, args, ...rest) => spawnLog(cmd, visibleInstallArgs(args), ...rest); } else { log("updates: this electron-updater has no spawnLog; the installer stays silent"); } } u.autoDownload = false; u.autoInstallOnAppQuit = true; // Security audit U1: electron-updater calls verifyUpdateCodeSignature only when app-update.yml names a publisher, // which only an Authenticode-signed build has. An unsigned Khaos build skipped the check, and the installer was then // trusted on latest.yml's sha512, which whoever controls the CDN writes. verifySignature runs on every downloaded // installer before it can be installed: it now always compares it with the Ed25519-signed manifest. u.verifyUpdateCodeSignature = async (_publishers, file) => checkInstaller(file); u.verifySignature = checkInstaller; if (MAC) { // MacUpdater has no verifySignature step: it hands the downloaded zip to Squirrel.Mac (which checks the Developer // ID) in updateDownloaded. The zip must match the signed manifest before Squirrel ever sees it. const handOver = u.updateDownloaded.bind(u); u.updateDownloaded = async (zipFileInfo, event) => { const refused = await checkInstaller(event.downloadedFile); if (refused) throw new Error(`${current.manifest.clientVersion} not installed: ${refused}`); return handOver(zipFileInfo, event); }; } if (LINUX) { // AppImageUpdater has no verifySignature step either, and its own install runs the new AppImage at once: on quit // it waits for it (execFileSync, an old AppRun convention), and on "restart now" the new Khaos can start before this // one has let go of its single-instance lock and loopback ports, then quit. Here: only an AppImage that matched // the signed manifest (checkInstaller) takes the old one's place (mv, kept name unless it carries a version), and // a restart starts it once this process is gone. Must stay synchronous (electron-updater's quit handler). u.doInstall = (options) => { const file = u.installerPath; const old = process.env.APPIMAGE; if (!old) throw new Error("Khaos was not started as an AppImage ($APPIMAGE is not set)"); if (!file || file !== verifiedFile) throw new Error("the downloaded AppImage was not checked against the signed manifest"); const keepName = path.basename(file) === path.basename(old) || !/\d+\.\d+\.\d+/.test(path.basename(old)); const destination = keepName ? old : path.join(path.dirname(old), path.basename(file)); execFileSync("mv", ["-f", file, destination]); fs.chmodSync(destination, 0o755); if (destination !== old) fs.rmSync(old, { force: true }); verifiedFile = null; log(`updates: ${current.manifest.clientVersion} installed as ${destination}`); if (options.isForceRunAfter) { const relaunch = spawn("/bin/sh", ["-c", 'while kill -0 "$1" 2>/dev/null; do sleep 0.5; done; exec "$0"', destination, String(process.pid)], { detached: true, stdio: "ignore", }); relaunch.unref(); } return true; }; } let shownPercent = -1; u.on("error", (e) => { progress(-1); notice({ state: "hide" }); log(`updates: ${e && e.message}`); flow.set("failed", (e && e.message) || "update error"); }); u.on("download-progress", (p) => { progress(Math.max(0, Math.min(1, p.percent / 100))); const percent = Math.floor(p.percent); if (percent !== shownPercent) { shownPercent = percent; notice({ state: "downloading", percent }); } if (Math.round(p.percent) % 25 === 0) log(`updates: ${Math.round(p.percent)} % of ${Math.round(p.total / 1048576)} MB`); }); // U1: an installer electron-updater reuses from its cache skips verifySignature; check it here too, and never // install on quit what does not match the signed manifest. Resolves true once the flow is "downloaded". const verifyDownloaded = async (info) => { const refused = info.downloadedFile ? await checkInstaller(info.downloadedFile) : "no downloaded file"; if (refused) { u.autoInstallOnAppQuit = false; progress(-1); notice({ state: "hide" }); log(`updates: ${info.version} not installed: ${refused}`); flow.set("failed", refused); return false; } u.autoInstallOnAppQuit = true; // Windows: electron-updater registers its install-on-quit handler right after update-downloaded only when the // flag is set, and it was cleared there (below): register it now that the installer matches. if (typeof u.addQuitHandler === "function") u.addQuitHandler(); log(`updates: ${info.version} downloaded`); // electron-updater saves this version's blockmap as the cache's current.blockmap (see dropStaleBlockmap). noteBlockmapVersion(info.version, log); progress(-1); notice({ state: "ready", version: current.manifest.clientVersion }); // The game's "update required" dialog already asked: set() installs at once, no second question. flow.set("downloaded"); return true; }; const offerInstall = async () => { if (flow.getState().phase !== "downloaded") return; // Rehearsal builds only: install at once without the dialog (scripted install -> update -> login runs). if (build.env.debug && process.env.KHAOS_UPDATE_AUTO === "1") { log("updates: installing now (KHAOS_UPDATE_AUTO, rehearsal build)"); await flow.requestInstall(); return; } const { response } = await dialog.showMessageBox({ type: "info", title: "Khaos", message: texts.t(userData, "updateReady", current.manifest.clientVersion), detail: texts.t(userData, "updateReadyDetail"), buttons: [texts.t(userData, "restartNow"), texts.t(userData, "later")], defaultId: 0, cancelId: 1, }); if (response === 0) await flow.requestInstall(); }; u.on("update-downloaded", (info) => { // Not installed on quit while the check runs (client audit 2026-10-21, porting sec/update-review): a cached // installer reaches this point without verifySignature, and quitting during its hash would have installed it. if (!MAC) u.autoInstallOnAppQuit = false; // Emitted inside downloadUpdate(): checkAndDownload awaits this check before it looks at the phase. verification = verifyDownloaded(info); verification .then((ok) => (ok ? offerInstall() : undefined)) .catch((e) => log(`updates: ${e && e.message}`)); }); // Quitting with a downloaded update installs it (autoInstallOnAppQuit; Windows: with the installer's progress // window and its no-run flag, so the game does not come back up): note it for the next start. app.on("will-quit", () => { if (flow.getState().phase === "downloaded" && u.autoInstallOnAppQuit) writeInstallMarker(marker, current.manifest.version, log); }); return u; } /** One check: signed manifest, then electron-updater's feed, then the download. Re-run when the game asks. */ async function checkAndDownload(why) { // A release already downloaded and verified is installed as it is: no second check, never "not available". if (flow.getState().phase === "downloaded") return undefined; flow.set("checking"); if (why) log(`updates: checking again (${why})`); if (!feed || keys.length === 0) { log("updates: no feed in this build"); return flow.set("none"); } if (!modules) { try { const { NsisUpdater, MacUpdater, AppImageUpdater } = require("electron-updater"); const { ElectronAppAdapter } = require("electron-updater/out/ElectronAppAdapter"); const { ElectronHttpExecutor } = require("electron-updater/out/electronHttpExecutor"); modules = { NsisUpdater, MacUpdater, AppImageUpdater, ElectronAppAdapter, ElectronHttpExecutor }; } catch (e) { log(`updates: electron-updater missing (${e.message})`); return flow.set("failed", `electron-updater missing (${e.message})`); } } let manifest; try { manifest = await fetchManifest(feed, keys); } catch (e) { log(`updates: no manifest (${e.message}); keeping ${build.version}`); return flow.set("failed", `no manifest (${e.message})`); } if (cmp(manifest.version, build.version) <= 0) { log(`updates: up to date (${build.clientVersion})`); return flow.set("none"); } // This platform's package in the signed manifest: installer (Windows NSIS), mac (zip of Khaos.app) or linux (AppImage). const pkg = manifest[PACKAGE_KEY]; if (!pkg || !pkg.sha512) { log(`updates: ${manifest.clientVersion} has no ${PLATFORM_NAME} package; keeping ${build.version}`); return flow.set("none"); } log(`updates: ${manifest.clientVersion} available (installed ${build.clientVersion})`); if ((MAC && !(build.macSigned && pkg.signed)) || (LINUX && !process.env.APPIMAGE)) { offerDownload({ build, manifest, log, userData }); return flow.set("failed", `${manifest.clientVersion} must be downloaded from the website (this build cannot update itself)`); } current = { manifest, pkg }; if (WIN) dropStaleBlockmap(build.version, log); if (!updater) updater = createUpdater(); try { const result = await updater.checkForUpdates(); if (!result || !result.isUpdateAvailable) { log(`updates: the feed has no newer installer (latest.yml ${result && result.updateInfo && result.updateInfo.version})`); return flow.set("none"); } if (result.updateInfo.version !== manifest.version) { log(`updates: latest.yml ${result.updateInfo.version} != signed manifest ${manifest.version}; skipped`); return flow.set("failed", `latest.yml ${result.updateInfo.version} != signed manifest ${manifest.version}`); } flow.set("downloading"); verification = null; await updater.downloadUpdate(); // update-downloaded fired inside downloadUpdate; its installer check finishes here. if (verification) await verification; } catch (e) { log(`updates: ${e && e.message}`); flow.set("failed", (e && e.message) || String(e)); } // A download that ended without update-downloaded or an error must not leave the game's dialog waiting. if (flow.getState().phase === "downloading") flow.set("failed", "the download ended without an installer"); return undefined; } await checkAndDownload(null); }; exports.compareVersions = cmp;