"use strict"; // Installed Khaos client: the packaged app's entry point (client/release/package.mjs sets package.json "main" to this // file). docs/LAUNCH.md section 2. // // Development runs (`npm run play`) start the translator first and the client second (translator/src/main.ts). // An installed client is one program, so this file does it the other way round: // 1. reads khaos-build.json (version, release number, environment: Auth host, published corpus, update feed), // 2. sets the player profile: %APPDATA%\ (settings, login), %LOCALAPPDATA%\\KhaosGame (game // data, ~10 GB; a new player can pick another folder or drive first) and %LOCALAPPDATA%\\logs // (errors + incident traces only); macOS: see "profile" below, // 3. forks the bundled translator (translator/src/embedded.mjs) as an Electron-as-Node child process: the shim // (login, server list, join ticket) and the game socket translator on loopback ports, talking to Auth, // 4. starts the auto-updater (updater.cjs), // 5. loads the launcher (main.cjs), which loads the client, with the master/API hosts answered by the shim // (globalThis.__khaosMaster) and the client's asset source answered from the published Khaos corpus. const fs = require("fs"); const path = require("path"); const { fork } = require("child_process"); const { app, dialog } = require("electron"); const { installGuard, installMarkerPath } = require("./updateFlow.cjs"); const APP_ROOT = path.resolve(__dirname, ".."); const build = JSON.parse(fs.readFileSync(path.join(APP_ROOT, "khaos-build.json"), "utf8")); const env = build.env; // Hot + cold release public keys (builds before the cold key carry only releasePublicKey). const releaseKeys = Array.isArray(build.releasePublicKeys) && build.releasePublicKeys.length ? build.releasePublicKeys : [build.releasePublicKey].filter(Boolean); // ---------------------------------------------------------------- profile // macOS: ~/Library/Application Support/ holds the profile and KhaosGame, logs go to ~/Library/Logs/. // Linux (XDG): ~/.config/ holds the profile (settings, login), ~/.local/share/ the game data (KhaosGame, // ~10 GB: not in ~/.config, which backup and dotfile tools copy) and the logs (docs/LINUX-CLIENT.md). const PROFILE = env.profile || "Khaos"; const ROAMING = app.getPath("appData"); const XDG_DATA = process.platform === "linux" ? (path.isAbsolute(process.env.XDG_DATA_HOME || "") ? process.env.XDG_DATA_HOME : path.join(app.getPath("home"), ".local", "share")) : null; const LOCAL = process.env.LOCALAPPDATA || XDG_DATA || ROAMING; const USER_DATA = path.join(ROAMING, PROFILE); const LOG_DIR = process.platform === "darwin" ? path.join(app.getPath("home"), "Library", "Logs", PROFILE) : path.join(LOCAL, PROFILE, "logs"); fs.mkdirSync(LOG_DIR, { recursive: true }); // ---------------------------------------------------------------- update still installing (Windows) // Started while the silent installer of an update replaces this app's files (the player closed the game with an update // downloaded, then relaunched at once): say so and quit, instead of starting on half-replaced files (updateFlow.cjs). if (process.platform === "win32") { const guard = installGuard(installMarkerPath(LOG_DIR), build.version); if (guard.action === "installing") { let message = "Khaos termine l'installation de sa mise à jour. / Khaos is finishing installing its update."; let detail = "Patiente une minute, puis relance Khaos. / Wait a minute, then launch Khaos again."; try { const t = require("./texts.cjs").t; message = t(USER_DATA, "updateInstalling"); detail = t(USER_DATA, "updateInstallingDetail"); } catch { /* texts.cjs is being replaced too: the bilingual text above */ } app.whenReady().then(async () => { await dialog.showMessageBox({ type: "info", title: "Khaos", message, detail, buttons: ["OK"] }); app.exit(0); }); return; // CommonJS module body: nothing else of the client starts } } const updater = require("./updater.cjs"); // before main.cjs wraps the main-process fetch const texts = require("./texts.cjs"); // A game data folder the player chose (first-launch step) or moved (in-game options) is kept: game-data-root.json. // Without one, main.cjs lets the client ask first (KHAOS_GAME_DATA_SETUP, recovered/src/electron/khaos/gameDataSetup.js), // before any download; an explicit KHAOS_GAME_DATA_ROOT is a choice already made. const DEFAULT_GAME_DATA = path.join(LOCAL, PROFILE, "KhaosGame"); const GAME_DATA_SETUP = process.env.KHAOS_GAME_DATA_ROOT ? "" : "1"; function gameDataRoot() { if (process.env.KHAOS_GAME_DATA_ROOT) return path.resolve(process.env.KHAOS_GAME_DATA_ROOT); try { const saved = JSON.parse(fs.readFileSync(path.join(USER_DATA, "game-data-root.json"), "utf8")).root; // A default folder of an older build (another name next to KhaosGame) is not kept: fresh start in KhaosGame // (KHAOS-REBRAND phase 2, no migration; the old folder is left as it is). if (typeof saved === "string" && path.isAbsolute(saved)) { const stale = path.dirname(path.resolve(saved)) === path.join(LOCAL, PROFILE) && path.basename(saved) !== "KhaosGame"; if (!stale) return saved; } } catch { /* first run */ } return DEFAULT_GAME_DATA; } const startLog = path.join(LOG_DIR, "client.log"); function log(line) { try { fs.appendFileSync(startLog, `${new Date().toISOString()} ${line}\n`); } catch { /* ignore */ } } try { if (fs.statSync(startLog).size > 2 * 1024 * 1024) fs.renameSync(startLog, `${startLog}.1`); } catch { /* absent */ } log(`--- Khaos ${build.clientVersion} (${build.version}, ${build.commit.slice(0, 10)}, ${build.environment}) pid=${process.pid}`); // The environment Khaos was started with: a graphics fallback restart (launcher/gpuMode.cjs) starts from it, without the // variables set below. globalThis.__khaosLaunchEnv = { ...process.env }; // The launcher (main.cjs) reads these when it loads. for (const k of ["KHAOS_DIST_DIR", "KHAOS_ELECTRON_DIR", "KHAOS_ALLOW_REMOTE", "KHAOS_MASTER_URL", "KHAOS_RENDERER_DEV_URL", "KHAOS_GAME_DATA_FOLDERS"]) delete process.env[k]; Object.assign(process.env, { KHAOS_USERDATA: USER_DATA, KHAOS_GAME_DATA_ROOT: gameDataRoot(), KHAOS_GAME_DATA_DEFAULT: DEFAULT_GAME_DATA, KHAOS_GAME_DATA_SETUP: GAME_DATA_SETUP, KHAOS_RENDERER_PORT: String(env.rendererPort), KHAOS_ASSET_MIRROR: "", KHAOS_ASSET_BASE: env.assets, // Security audit U2: the corpus root must carry the release key's signature (launcher/assetRoot.cjs). // On for every build except a local rehearsal that says otherwise (package.mjs refuses assetRootSigned false // anywhere else); the hot and the cold release key both verify (owner question 7). KHAOS_ASSET_ROOT_KEY: (env.assetRootSigned !== false || !env.debug) ? releaseKeys.join("\n") : "", KHAOS_REQUEST_LOG: "errors", KHAOS_APP_USER_MODEL_ID: env.appId, KHAOS_WEBSITE: env.website, // launcher/stability.cjs: crash / hang diagnostics next to client.log, carried by F11 reports (translator bugReport.ts) KHAOS_LOG_DIR: LOG_DIR, KHAOS_CLIENT_VERSION: `${build.clientVersion} (${build.release})`, }); // khaos:// deep links are gone (2026-10-09): a production install only removes the registration older installs made (a // rehearsal never touches the machine's handlers). globalThis.__khaosDeepLinks = !env.debug; // The client's own removal (desktopApplication.js) asks app.isPackaged, which main.cjs keeps false at runtime, so the // old registration stayed and any web page could start Khaos through a khaos:// link (client audit 2026-10-21, C8). if (globalThis.__khaosDeepLinks) { app.whenReady().then(() => { try { if (app.isDefaultProtocolClient("khaos")) log(`khaos:// registration removed: ${app.removeAsDefaultProtocolClient("khaos")}`); } catch (e) { log(`khaos:// registration not removed (${e.message})`); } }); } // Remote debugging only in local rehearsal builds (never in a production build: any local program could drive it). if (env.debug && /^\d+$/.test(process.env.KHAOS_DEBUG_PORT || "")) { app.commandLine.appendSwitch("remote-debugging-port", process.env.KHAOS_DEBUG_PORT); log(`remote debugging on ${process.env.KHAOS_DEBUG_PORT} (rehearsal build)`); } // ---------------------------------------------------------------- embedded translator let shimUrl = null; let waiters = []; let quitting = false; let child = null; const starts = []; globalThis.__khaosMaster = { base: () => (shimUrl ? Promise.resolve(shimUrl) : new Promise((resolve, reject) => waiters.push({ resolve, reject }))), }; function fail(message) { log(`translator: ${message}`); for (const w of waiters) w.reject(new Error(message)); waiters = []; if (quitting) return; quitting = true; app.whenReady().then(() => { dialog.showErrorBox(texts.t(USER_DATA, "startFailed"), texts.t(USER_DATA, "startFailedDetail", message, LOG_DIR)); app.quit(); }); } function startTranslator() { const now = Date.now(); while (starts.length && now - starts[0] > 5 * 60 * 1000) starts.shift(); if (starts.length >= 3) return fail(texts.t(USER_DATA, "connectorStopped")); starts.push(now); child = fork(path.join(APP_ROOT, "translator", "src", "embedded.mjs"), [], { execPath: process.execPath, cwd: APP_ROOT, stdio: ["ignore", "ignore", "ignore", "ipc"], windowsHide: true, env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", KHAOS_EMBEDDED: "1", KHAOS_AUTH: env.auth, // Giny over TLS (translator/src/ginyTls.ts; environments.json "tls": { "worldPorts": "5557:5567" }). KHAOS_TLS: env.tls ? "1" : "0", KHAOS_TLS_WORLD_PORTS: (env.tls && env.tls.worldPorts) || "", KHAOS_TLS_SERVERNAME: (env.tls && env.tls.servername) || "", KHAOS_API: env.api || "off", KHAOS_SERVER_ID: String(env.serverId), KHAOS_CLIENT_RELEASE: String(build.release), KHAOS_STATE_DIR: path.join(USER_DATA, "translator"), KHAOS_LOG_DIR: LOG_DIR, KHAOS_SHIM_LOG: "errors", KHAOS_SHIM_PORT: String(env.shimPort || 0), KHAOS_GAME_PORT: String(env.gamePort || 0), // One asset source: the client's own (https://download.khaosdofus.com/khaos/assets), answered by main.cjs. KHAOS_ASSET_URL: "", KHAOS_TRACE: (env.debug && process.env.KHAOS_TRACE) || env.trace || "none", KHAOS_SOURCE_ADDRESS: env.sourceAddress || "", KHAOS_FINGERPRINT: env.fingerprint || "", // Players online on the server card: the website's public status (translator/src/population.ts); "" = hidden. KHAOS_STATUS_URL: env.status || "", // F11 bug reports: the website's intake (translator/src/bugReport.ts, docs/BUG-REPORTS.md); "" = off. KHAOS_BUG_REPORT_URL: env.bugReports || "off", }, }); child.on("message", (m) => { if (m && m.type === "ready") { shimUrl = m.shimUrl; log(`translator ready: ${m.shimUrl}, game port ${m.gamePort}`); for (const w of waiters) w.resolve(shimUrl); waiters = []; } else if (m && m.type === "error") { fail(m.message || "erreur inconnue"); } }); child.on("exit", (code, signal) => { shimUrl = null; if (quitting) return; log(`translator exited (${code ?? signal}); restarting`); startTranslator(); }); } startTranslator(); app.on("before-quit", () => { quitting = true; if (child && child.exitCode === null) { try { child.send({ type: "stop" }); } catch { child.kill(); } } }); app.whenReady().then(() => updater.start({ build, logDir: LOG_DIR, log, userData: USER_DATA })); // ---------------------------------------------------------------- client require("./main.cjs");