"use strict"; // Khaos launcher. // // Runs the Khaos client main process (recovered/dist + recovered/dist-electron, `cd recovered && npm run build`) with: // - an isolated profile (client/.userdata by default; never %APPDATA%), // - its own game-data root (.gamedata/KhaosGame), // - no protocol-handler changes in development (an installed client only removes the old khaos:// registration), // - the renderer served by a local static server (unpackaged Electron loads ELECTRON_RENDERER_URL instead of // dist/index.html) or by the Vite dev server, // - every https request logged; anything that is not ours or loopback is refused unless allowed, // - the client's account API / master hosts (api.khaos.invalid, master.khaos.invalid) answered by the local shim, // - the client's asset source (https://download.khaosdofus.com/khaos/assets) answered from a local Khaos corpus (dev) or // the published one (installed client). // // Environment (all optional): // KHAOS_USERDATA profile dir (default /client/.userdata) // KHAOS_DIST_DIR renderer build to serve (default recovered/dist; the UI preview uses recovered/dist-ui) // KHAOS_ELECTRON_DIR Electron main build to load (default recovered/dist-electron; an agent's test build made // with recovered/build-electron.mjs and KHAOS_ELECTRON_OUT) // KHAOS_GAME_DATA_ROOT asset cache root (default /client/.gamedata/KhaosGame) // KHAOS_RENDERER_PORT static renderer port (default 47374) // KHAOS_RENDERER_DEV_URL renderer from a Vite dev server (live lane, `npm run play` default), e.g. http://127.0.0.1:47460; // replaces the static server and KHAOS_DIST_DIR // KHAOS_MASTER_URL local shim base URL, e.g. http://127.0.0.1:9101 (the API / master hosts are forwarded there) // KHAOS_ALLOW_REMOTE=1 let other https requests reach the internet (or --khaos-allow-remote on the command line) // KHAOS_ASSET_MIRROR a staged Khaos corpus folder (client/release/corpus.mjs stage: asset-manifest.json, shards, // catalog, plans, packs/, ca/) served read-only as the asset source (default: config // paths.corpus of the repo around this checkout, when it holds asset-manifest.json; "" // disables). A miss is BLOCKED and logged. // KHAOS_ASSET_BASE published Khaos corpus (e.g. https://download.khaosdofus.com/khaos/assets): the asset source is // answered from there instead (installed client; no mirror) // KHAOS_ASSET_ROOT_KEY release public key(s): the corpus root must carry their signature (launcher/assetRoot.cjs) // KHAOS_WEBSITE where external links go (default https://play.khaosdofus.com/) // KHAOS_REQUEST_LOG=errors log only refused/failed requests (installed client, launcher/player.cjs) // KHAOS_APP_USER_MODEL_ID taskbar identity (installed client: its installer's appId; default net.khaosdofus.khaos.dev) // KHAOS_GPU_MODE auto | integrated | software: overrides the profile's "Graphics card" option (launcher/gpuMode.cjs) // KHAOS_GPU_FALLBACK native | compat | software | warp: forces a graphics rung (launcher/gpuMode.cjs; support) // The installed client starts here through launcher/player.cjs (docs/LAUNCH.md): it sets these variables and // globalThis.__khaosMaster (the embedded translator's shim URL, known once its child process is up). const fs = require("fs"); const path = require("path"); const http = require("http"); const { app, protocol, net, session, shell } = require("electron"); const ROOT = path.resolve(__dirname, ".."); const APP_DIR = path.join(ROOT, "recovered"); // KHAOS_DIST_DIR: serve another renderer build (e.g. recovered/dist-ui, a UI preview built with // `vite build --outDir dist-ui`) without touching the dist/ the other running instances load. const DIST_DIR = process.env.KHAOS_DIST_DIR ? path.resolve(ROOT, process.env.KHAOS_DIST_DIR) : path.join(APP_DIR, "dist"); // KHAOS_ELECTRON_DIR: load another Electron main build (recovered/build-electron.mjs with KHAOS_ELECTRON_OUT), for an // agent's test instance; unset, every instance loads dist-electron/. const CLIENT_MAIN = process.env.KHAOS_ELECTRON_DIR ? path.join(path.resolve(ROOT, process.env.KHAOS_ELECTRON_DIR), "main.cjs") : path.join(APP_DIR, "dist-electron", "main.cjs"); // KHAOS_RENDERER_DEV_URL: the renderer comes from a Vite dev server (live lane: recovered/live/dev-server.mjs) // instead of a built dist/; no static renderer server is started. const RENDERER_DEV_URL = (process.env.KHAOS_RENDERER_DEV_URL || "").replace(/\/+$/, ""); if (!fs.existsSync(CLIENT_MAIN) || (!RENDERER_DEV_URL && !fs.existsSync(path.join(DIST_DIR, "index.html")))) { console.error( `[khaos] client not built: ${CLIENT_MAIN} or ${DIST_DIR}/index.html missing (run \`npm run build\` in recovered/)`, ); process.exit(1); } const USER_DATA = path.resolve(process.env.KHAOS_USERDATA || path.join(ROOT, ".userdata")); const GAME_DATA_ROOT = path.resolve(process.env.KHAOS_GAME_DATA_ROOT || path.join(ROOT, ".gamedata", "KhaosGame")); const RENDERER_PORT = Number(process.env.KHAOS_RENDERER_PORT || 47374); let MASTER_URL = (process.env.KHAOS_MASTER_URL || "").replace(/\/+$/, ""); // Installed client: the shim URL arrives later (player.cjs); every master request waits for it. const MASTER_PENDING = globalThis.__khaosMaster || null; const hasMaster = () => Boolean(MASTER_URL || MASTER_PENDING); async function masterBase() { return MASTER_PENDING ? (await MASTER_PENDING.base()).replace(/\/+$/, "") : MASTER_URL; } // Development only: an installed client (player.cjs sets globalThis.__khaosMaster) ignores both, so no shortcut or // command line can open its offline policy (client audit 2026-10-21, C6). const ALLOW_REMOTE = !MASTER_PENDING && (process.env.KHAOS_ALLOW_REMOTE === "1" || process.argv.includes("--khaos-allow-remote")); // The client's one asset source (electron/main.js, renderer app/format.js): its URL space is answered by this // launcher, never fetched from the network as such. const ASSET_SOURCE = new URL("https://download.khaosdofus.com/khaos/assets/"); function isAssetSource(url) { return url.host === ASSET_SOURCE.host && url.pathname.startsWith(ASSET_SOURCE.pathname); } // The client's account API and master (renderer app/AuthManagerImpl.js SITE_ORIGIN, app/MasterServers.js; main.js // auth refresh): reserved .invalid names that never resolve, answered here by the local shim. const API_HOST = "api.khaos.invalid"; const MASTER_HOSTS = new Set([API_HOST, "master.khaos.invalid"]); // ---------------------------------------------------------------- profile fs.mkdirSync(USER_DATA, { recursive: true }); app.setPath("appData", path.join(USER_DATA, "appData")); app.setPath("userData", USER_DATA); app.setPath("sessionData", USER_DATA); // Khaos (client-freeze): crash / hang / memory diagnostics that survive a frozen PC, carried by the next F11 report // (launcher/stability.cjs). Installed client: KHAOS_LOG_DIR = %LOCALAPPDATA%\\logs (player.cjs). // The graphics card Chromium draws with (Options > Display > Graphics "Graphics card", launcher/gpuMode.cjs): read // from the profile's settings before "ready", so a change applies at the next start. const gpuMode = require("./gpuMode.cjs"); const GPU_MODE = gpuMode.applyGpuMode(app, USER_DATA); const stability = require("./stability.cjs"); stability.start({ app, logDir: process.env.KHAOS_LOG_DIR || path.join(USER_DATA, "logs"), version: process.env.KHAOS_CLIENT_VERSION || "dev", gpuMode: gpuMode.fallbackRung() ? `${GPU_MODE}, graphics ${gpuMode.fallbackRung()}` : GPU_MODE, }); // The renderer could not start WebGL2 (recovered/src/electron/khaos/desktopIpc.js "app:gpu-fallback"): Windows and // Linux restart on the next graphics rung (launcher/gpuMode.cjs); otherwise the details its error dialog shows. globalThis.__khaosGpuFallback = async (reason) => { const from = gpuMode.fallbackRung(); const answer = await gpuMode.fallback(app, reason); stability.line(answer.retrying ? `WebGL2 failed on graphics ${from} (${String(reason).slice(0, 300)}): restarting on graphics ${answer.rung}` : `WebGL2 failed, no graphics rung left:\n${answer.details}`); return answer; }; // WebGL2 is up ("app:gpu-ready", `renderer`: the GL renderer the game draws with): the rung is kept as working, and // the stability log (F11 reports) says which. "app:gpu-reset": the player asked for the normal mode at the next start. globalThis.__khaosGpuReady = async (renderer) => { const answer = await gpuMode.ready(app); stability.line( `WebGL2 up on graphics ${answer.rung || "default"}${answer.first ? " (first start that worked on it)" : ""}: ${String(renderer).slice(0, 200) || "?"}` + (answer.driverChanged ? `; GPU drivers changed (${answer.previousGpu} -> ${answer.gpu}): the next start tries the normal mode` : ""), ); return answer; }; globalThis.__khaosGpuReset = () => { const done = gpuMode.reset(); if (done) stability.line(`graphics mode reset by the player (was ${gpuMode.fallbackRung() || "default"}): the next start tries the normal mode`); return done; }; // WebGL2 before the first window (recovered/src/electron/khaos/desktopApplication.js boot, launcher/gpuMode.cjs // startCheck; player SOMALO 2026-11-26): a rung without WebGL2 restarts Khaos at once, not after the player's "Play", and // when every rung failed the final message shows here, with "Retry". Answers false when Khaos must not open its windows. globalThis.__khaosGpuStartCheck = async () => { const { BrowserWindow, dialog } = require("electron"); const probe = async () => { // closing the only window must not quit Khaos (no window-all-closed listener yet at this point) const keep = () => {}; app.on("window-all-closed", keep); const win = new BrowserWindow({ show: false, width: 64, height: 64, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } }); let timer; try { await win.loadURL("about:blank"); const check = win.webContents.executeJavaScript( `(() => { const gl = document.createElement("canvas").getContext("webgl2"); if (gl) { gl.getExtension("WEBGL_lose_context")?.loseContext(); return { ok: true }; }` + ` return { ok: false, reason: document.createElement("canvas").getContext("webgl") ? "no WebGL2 context (WebGL 1 only)" : "no WebGL context" }; })()`, ); // a GPU process still starting on a slow PC is not a failure: the renderer's own check stays behind it const late = new Promise((resolve) => { timer = setTimeout(() => resolve({ ok: true, late: true }), 20_000); }); return await Promise.race([check, late]); } finally { clearTimeout(timer); if (!win.isDestroyed()) win.destroy(); setTimeout(() => app.off("window-all-closed", keep), 2_000).unref(); } }; const from = gpuMode.fallbackRung(); const result = await gpuMode.startCheck(app, probe); if (result.probed || !result.proceed) { stability.line(`graphics start check on ${from || "default"} (GL ${result.glVersion || "?"}): ` + (result.proceed ? "WebGL2 ok" : result.retrying ? `no WebGL2, restarting on graphics ${result.rung}` : "no WebGL2, no graphics rung left")); } if (result.proceed || result.retrying) return result.proceed; stability.line(`WebGL2 failed, no graphics rung left:\n${result.details ?? ""}`); const t = (key, ...args) => require("./texts.cjs").t(USER_DATA, key, ...args); const { response } = await dialog.showMessageBox({ type: "error", title: "Khaos", message: t("gpuUnavailable"), detail: t("gpuUnavailableDetail", result.details ?? ""), buttons: [t("gpuQuit"), t("gpuRetry")], defaultId: 0, cancelId: 0, noLink: true, }); if (response === 1) { stability.line("graphics: the player asked to try every mode again"); gpuMode.retryAll(app); } else app.exit(1); return false; }; // The client's Electron main writes why its Game Data Service exited (recovered/src/electron/khaos/gameDataServiceHost.js): // the stability log outlives the session, so the next F11 report still carries the reason. globalThis.__khaosStabilityLine = stability.line; // The client reads the asset cache root from /game-data-root.json (launcher/gameDataRoot.cjs). // KHAOS_GAME_DATA_SETUP=1 (installed client, launcher/player.cjs, unless KHAOS_GAME_DATA_ROOT was given): the client's // folder step decides at every start (recovered/src/electron/khaos/gameDataSetup.js + GameDataLocation: no folder chosen // yet, a first download that never finished, a drive too small for what is left; never a complete install), so the // request is always passed and nothing is created here. Development runs keep the folder they were given. // KHAOS_GAME_DATA_FOLDERS (development test runs only, ";"-separated game data folders): replaces the drive scan. const gameDataSetupRequest = require("./gameDataRoot.cjs").prepareGameDataRoot({ userData: USER_DATA, root: GAME_DATA_ROOT, setup: process.env.KHAOS_GAME_DATA_SETUP === "1", defaultRoot: process.env.KHAOS_GAME_DATA_DEFAULT || null, folders: !MASTER_PENDING && process.env.KHAOS_GAME_DATA_FOLDERS ? process.env.KHAOS_GAME_DATA_FOLDERS.split(";").filter(Boolean).map((folder) => path.resolve(folder)) : null, }); if (gameDataSetupRequest) globalThis.__khaosGameDataSetup = gameDataSetupRequest; // ---------------------------------------------------------------- logging const LOG_FILE = path.join(USER_DATA, "khaos-requests.log"); const LOG_ERRORS_ONLY = process.env.KHAOS_REQUEST_LOG === "errors"; function logRequest(line) { if (LOG_ERRORS_ONLY && !/^(---|BLOCKED|MAIN-BLOCKED|MASTER-ERROR|MIRROR-ERROR|ASSET-ERROR|ASSET-ROOT|EXTERNAL|renderer)/.test(line)) return; try { fs.appendFileSync(LOG_FILE, `${new Date().toISOString()} ${line}\n`); } catch { /* ignore */ } } logRequest( `--- launch pid=${process.pid} allowRemote=${ALLOW_REMOTE} master=${MASTER_URL || "-"} root=${GAME_DATA_ROOT}`, ); // ---------------------------------------------------------------- side effects off // The client no longer uses khaos:// links (2026-10-09); RA() in main.js removes the registration older installs made. Only an // installed production client does (launcher/player.cjs sets globalThis.__khaosDeepLinks); development and rehearsal runs // never touch the machine's protocol handlers. if (!globalThis.__khaosDeepLinks) { app.setAsDefaultProtocolClient = () => true; app.removeAsDefaultProtocolClient = () => true; } // The installed client uses its installer's appId (taskbar grouping with its shortcuts). The method exists on Windows // only (macOS: the bundle id is the identity), and main.js calls it unconditionally. const setAppUserModelId = typeof app.setAppUserModelId === "function" ? app.setAppUserModelId.bind(app) : null; app.setAppUserModelId = () => setAppUserModelId?.(process.env.KHAOS_APP_USER_MODEL_ID || "net.khaosdofus.khaos.dev"); // macOS keeps an application menu (main.js removes the menu on the other platforms only). Electron's default one // would offer Reload and the developer tools, and without an Edit menu Cmd+C / Cmd+V do nothing in the chat and the // login fields, so Khaos sets its own: app (about, hide, quit), Edit (clipboard roles), Window. if (process.platform === "darwin") { app.whenReady().then(() => { const { Menu } = require("electron"); const t = (key) => require("./texts.cjs").t(USER_DATA, key); Menu.setApplicationMenu( Menu.buildFromTemplate([ { role: "appMenu", submenu: [ { role: "about", label: t("menuAbout") }, { type: "separator" }, { role: "hide", label: t("menuHide") }, { role: "hideOthers", label: t("menuHideOthers") }, { role: "unhide", label: t("menuShowAll") }, { type: "separator" }, { role: "quit", label: t("menuQuit") }, ], }, { label: t("menuEdit"), submenu: [ { role: "undo", label: t("menuUndo") }, { role: "redo", label: t("menuRedo") }, { type: "separator" }, { role: "cut", label: t("menuCut") }, { role: "copy", label: t("menuCopy") }, { role: "paste", label: t("menuPaste") }, { role: "selectAll", label: t("menuSelectAll") }, ], }, { role: "windowMenu", label: t("menuWindow"), submenu: [ { role: "minimize", label: t("menuMinimize") }, { role: "zoom", label: t("menuZoom") }, { role: "togglefullscreen", label: t("menuFullScreen") }, ], }, ]), ); }); } // ---------------------------------------------------------------- renderer server const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".webmanifest": "application/manifest+json", ".map": "application/json", ".wasm": "application/wasm", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".avif": "image/avif", ".gif": "image/gif", ".ico": "image/x-icon", ".ktx2": "image/ktx2", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf", ".xml": "application/xml", ".txt": "text/plain; charset=utf-8", ".ogg": "audio/ogg", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".bank": "application/octet-stream", ".bin": "application/octet-stream", }; const rendererServer = http.createServer((req, res) => { let rel; try { rel = decodeURIComponent(new URL(req.url, "http://x").pathname); } catch { res.writeHead(400).end(); return; } if (rel === "/" || rel === "") rel = "/index.html"; const file = path.resolve(DIST_DIR, `.${rel}`); if (file !== DIST_DIR && !file.startsWith(DIST_DIR + path.sep)) { res.writeHead(403).end(); return; } fs.stat(file, (err, st) => { if (err || !st.isFile()) { logRequest(`renderer 404 ${rel}`); res.writeHead(404).end(); return; } res.writeHead(200, { "content-type": MIME[path.extname(file).toLowerCase()] || "application/octet-stream", "content-length": st.size, "cache-control": "no-cache", }); if (req.method === "HEAD") return res.end(); fs.createReadStream(file).pipe(res); }); }); rendererServer.on("error", (err) => { logRequest(`renderer server error: ${err.message}`); console.error(`[khaos] renderer server on 127.0.0.1:${RENDERER_PORT} failed: ${err.message}`); }); if (RENDERER_DEV_URL) { console.log(`[khaos] renderer from the dev server ${RENDERER_DEV_URL} (no static renderer server)`); process.env.ELECTRON_RENDERER_URL = RENDERER_DEV_URL; } else { rendererServer.listen(RENDERER_PORT, "127.0.0.1"); process.env.ELECTRON_RENDERER_URL = `http://127.0.0.1:${RENDERER_PORT}`; } // ---------------------------------------------------------------- https policy function corsHeaders(request) { const origin = request.headers.get("origin"); return { "access-control-allow-origin": origin || "*", "access-control-allow-credentials": "true", "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS", "access-control-allow-headers": request.headers.get("access-control-request-headers") || "authorization, content-type, accept, x-device-id, x-hwid-hash, x-khaos-realm, x-khaos-browser, x-khaos-launcher-token", "access-control-max-age": "600", vary: "Origin", }; } async function forwardToMaster(request, url) { if (request.method === "OPTIONS") { return new Response(null, { status: 204, headers: corsHeaders(request) }); } // api.khaos.invalid/api/... -> /api/...; master.khaos.invalid/servers -> /servers const target = `${await masterBase()}${url.pathname}${url.search}`; const headers = new Headers(request.headers); headers.set("x-khaos-original-host", url.host); const init = { method: request.method, headers, redirect: "manual" }; if (request.method !== "GET" && request.method !== "HEAD" && request.body) { init.body = await request.arrayBuffer(); } const upstream = await net.fetch(target, init); const outHeaders = new Headers(upstream.headers); for (const [k, v] of Object.entries(corsHeaders(request))) outHeaders.set(k, v); return new Response(upstream.body, { status: upstream.status, headers: outHeaders }); } // ---------------------------------------------------------------- local Khaos corpus (development) // Serves the asset source's URL space read-only out of a staged Khaos corpus (client/release/corpus.mjs stage: the same // layout as the published one, so / -> /). The client keeps its own cache under // GAME_DATA_ROOT and "downloads" from this mirror over loopback, so the corpus is only ever opened for reading. const { Readable } = require("stream"); /** Development default: config paths.corpus (tools/lib/khaosconfig.mjs of the repo around this checkout, loaded with * require(esm)); "" for an installed client (no repo) or when the config cannot be read. */ function configuredMirror() { let dir = __dirname; while (!fs.existsSync(path.join(dir, "config", "local.example.json"))) { if (path.dirname(dir) === dir) return ""; dir = path.dirname(dir); } try { return require(path.join(dir, "tools", "lib", "khaosconfig.mjs")).khaosPath("corpus", { mustExist: false }); } catch (err) { console.error(`[khaos] config paths.corpus unavailable (${err && err.message}): no local corpus`); return ""; } } const DEFAULT_MIRROR = process.env.KHAOS_ASSET_MIRROR !== undefined ? "" : configuredMirror(); const ASSET_MIRROR = process.env.KHAOS_ASSET_MIRROR !== undefined ? process.env.KHAOS_ASSET_MIRROR : DEFAULT_MIRROR && fs.existsSync(path.join(DEFAULT_MIRROR, "asset-manifest.json")) ? DEFAULT_MIRROR : ""; const MIRROR_PATH = /^(?:asset-manifest\.json|asset-(?:manifest-shards|pack-catalog|install-plans|deltas)\/[\w./-]+|packs\/sha256\/[0-9a-f]{2}\/[0-9a-f]{64}\.pack|ca\/[0-9a-f]{64})$/; function mirrorFileFor(url) { const rest = url.pathname.slice(ASSET_SOURCE.pathname.length); if (!MIRROR_PATH.test(rest) || rest.split("/").includes("..")) return null; const f = path.join(ASSET_MIRROR, ...rest.split("/")); if (!fs.existsSync(f)) return null; return { file: f, type: rest.endsWith(".json") ? "application/json" : "application/octet-stream" }; } async function serveFromMirror(request, url) { if (request.method !== "GET" && request.method !== "HEAD") return null; let hit; try { hit = mirrorFileFor(url); } catch (err) { logRequest(`MIRROR-ERROR ${request.url} ${err && err.message}`); return null; } if (hit === null) return null; const size = fs.statSync(hit.file).size; const headers = { "content-type": hit.type, "accept-ranges": "bytes", "cache-control": "no-store", ...corsHeaders(request), }; const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.get("range") || ""); let start = 0; let end = size - 1; let status = 200; if (range) { if (range[1] === "") { start = Math.max(0, size - Number(range[2])); } else { start = Number(range[1]); if (range[2] !== "") end = Math.min(end, Number(range[2])); } if (start > end || start >= size) { return new Response(null, { status: 416, headers: { ...headers, "content-range": `bytes */${size}` } }); } status = 206; headers["content-range"] = `bytes ${start}-${end}/${size}`; } headers["content-length"] = String(end - start + 1); logRequest(`MIRROR ${status} ${request.url.replace(/\?.*$/, "")}${range ? ` ${range[0]}` : ""}`); if (request.method === "HEAD" || size === 0) return new Response(null, { status, headers }); const body = Readable.toWeb(fs.createReadStream(hit.file, { start, end, flags: "r" })); return new Response(body, { status, headers }); } // ---------------------------------------------------------------- published Khaos corpus // Installed client: the server entry names no assetDownloadUrl, so the client uses its one asset source; its URL // space is answered from the published Khaos corpus (client/release/corpus.mjs). Range requests pass through (pack reads). const ASSET_BASE = (process.env.KHAOS_ASSET_BASE || "").replace(/\/+$/, ""); // Security audit U2: the release public key when the build requires a signed asset root (launcher/assetRoot.cjs). const ASSET_ROOT_KEY = process.env.KHAOS_ASSET_ROOT_KEY || ""; const assetRoot = require("./assetRoot.cjs"); // The fetch below gives up on a CDN that stops answering (F11 #117 #124, 2026-11-17; launcher/assetFetch.cjs). const assetFetch = require("./assetFetch.cjs"); const { externalUrl } = require("./externalUrl.cjs"); /** * The corpus root, served only when asset-manifest.json.sig verifies. The last verified root (and its signature) is * kept in the profile: when the CDN's root is missing or fails its check, that one is served instead, so the client * keeps playing on the content it already verified (no content update) rather than staying on "Vérification des * ressources" (rehearsal 2026-10-04: a refused root with no fallback blocked Play, the client retried every 4 s). * 502 only when there is no verified root at all (first start). */ const VERIFIED_ROOT = path.join(USER_DATA, "khaos-verified-asset-root.json"); function rootResponse(request, bytes) { const headers = new Headers({ "content-type": "application/json", ...corsHeaders(request) }); return new Response(request.method === "HEAD" ? null : bytes, { status: 200, headers }); } function lastVerifiedRoot(request, why) { try { const bytes = fs.readFileSync(VERIFIED_ROOT); const sig = fs.readFileSync(`${VERIFIED_ROOT}.sig`, "utf8"); if (assetRoot.verifyAssetRoot(bytes, sig, ASSET_ROOT_KEY)) { logRequest(`ASSET-ROOT-REFUSED ${why}; serving the last verified root`); return rootResponse(request, bytes); } } catch { /* none yet */ } logRequest(`ASSET-ROOT-REFUSED ${why}; no verified root to fall back on`); return new Response(null, { status: 502, headers: corsHeaders(request) }); } async function serveSignedAssetRoot(request, target) { const plain = target.replace(/\?.*$/, ""); // a CDN that stops answering ends in the last verified root, not in a request open forever (launcher/assetFetch.cjs) const budget = assetFetch.stallBudget(request.headers); const get = (url) => assetFetch.fetchWithWatchdog(net.fetch, url, { method: "GET", cache: "no-store", bypassCustomProtocolHandlers: true }, budget); try { const [rootRes, sigRes] = await Promise.all([get(target), get(`${plain}.sig${target.slice(plain.length)}`)]); if (rootRes.status !== 200 || sigRes.status !== 200) { return lastVerifiedRoot(request, `${plain} root=${rootRes.status} sig=${sigRes.status}`); } const bytes = Buffer.from(await rootRes.arrayBuffer()); const sig = await sigRes.text(); if (!assetRoot.verifyAssetRoot(bytes, sig, ASSET_ROOT_KEY)) { return lastVerifiedRoot(request, `${plain} bad signature`); } try { fs.writeFileSync(`${VERIFIED_ROOT}.sig`, sig); fs.writeFileSync(VERIFIED_ROOT, bytes); } catch { /* the cache is a convenience */ } return rootResponse(request, bytes); } catch (err) { return lastVerifiedRoot(request, `${plain} ${err && err.message}`); } } // KHAOS_ASSET_TRACE=: one JSON line per published-corpus request (path, range, status, bytes, time to headers and // to the last byte, Cloudflare cache status). Load-latency measurements (docs/client/load-latency.md); off by default. const ASSET_TRACE = process.env.KHAOS_ASSET_TRACE ? fs.createWriteStream(process.env.KHAOS_ASSET_TRACE, { flags: "a" }) : null; function traceAssetBody(body, rec) { if (!ASSET_TRACE) return body; const done = (aborted) => { rec.ms = Math.round(performance.now() - rec.t0); delete rec.t0; if (aborted) rec.aborted = true; ASSET_TRACE.write(`${JSON.stringify(rec)}\n`); }; if (!body) { done(false); return body; } return body.pipeThrough( new TransformStream({ transform(chunk, controller) { rec.bytes += chunk.byteLength; controller.enqueue(chunk); }, flush() { done(false); }, cancel() { done(true); }, }), ); } // KHAOS_ASSET_SIM="rtt=,mbps=" (development runs only, never a packaged client): adds before each // published-corpus request and shares Mbit/s between all response bodies, to measure the asset path under a // player's link (Latin America: ~150-250 ms more per request than here). docs/client/load-latency.md. const ASSET_SIM = (() => { if (app.isPackaged || !process.env.KHAOS_ASSET_SIM) return null; const o = Object.fromEntries(process.env.KHAOS_ASSET_SIM.split(",").map((kv) => kv.split("=").map((x) => x.trim()))); const rtt = Number(o.rtt) || 0; const bytesPerMs = Number(o.mbps) > 0 ? (Number(o.mbps) * 1e6) / 8 / 1000 : 0; let nextFree = 0; // the shared link is busy until this time return { rtt, delay: () => (rtt > 0 ? new Promise((r) => setTimeout(r, rtt)) : null), throttle(body) { if (!body || bytesPerMs <= 0) return body; return body.pipeThrough( new TransformStream({ async transform(chunk, controller) { const now = performance.now(); nextFree = Math.max(nextFree, now) + chunk.byteLength / bytesPerMs; if (nextFree - now > 1) await new Promise((r) => setTimeout(r, nextFree - now)); controller.enqueue(chunk); }, }), ); }, }; })(); async function serveFromAssetBase(request, url) { if (request.method !== "GET" && request.method !== "HEAD") return null; if (ASSET_SIM && ASSET_SIM.rtt > 0) await ASSET_SIM.delay(); const target = `${ASSET_BASE}/${url.pathname.slice(ASSET_SOURCE.pathname.length)}${url.search}`; if (ASSET_ROOT_KEY && assetRoot.isAssetRootPath(url.pathname)) return serveSignedAssetRoot(request, target); const headers = {}; const range = request.headers.get("range"); if (range) headers.range = range; const t0 = performance.now(); // Khaos (asset-verify 2026-10-15): blobs, packs and asset-* metadata skip Chromium's HTTP disk cache (launcher/assetRoot.cjs // bypassesHttpCache). The client's own cache: "no-store" ends at this hop, and a bad cached /ca/ copy was replayed // for a year. const init = { method: request.method, headers, bypassCustomProtocolHandlers: true }; if (assetRoot.bypassesHttpCache(url.pathname.slice(ASSET_SOURCE.pathname.length))) init.cache = "no-store"; let upstream; try { upstream = await assetFetch.fetchWithWatchdog(net.fetch, target, init, assetFetch.stallBudget(request.headers)); } catch (err) { logRequest(`ASSET-ERROR ${target.replace(/\?.*$/, "")} ${err && err.message}`); return assetFetch.failedFetchResponse(err, corsHeaders(request)); } // A missing asset-deltas/ object is normal (the client then downloads the whole artifact). if (upstream.status >= 400 && !(upstream.status === 404 && url.pathname.includes("/asset-deltas/"))) logRequest(`ASSET-ERROR ${upstream.status} ${target.replace(/\?.*$/, "")}`); const outHeaders = new Headers(upstream.headers); for (const [k, v] of Object.entries(corsHeaders(request))) outHeaders.set(k, v); const rec = ASSET_TRACE && { at: new Date().toISOString(), path: url.pathname.slice(ASSET_SOURCE.pathname.length), range: range || undefined, status: upstream.status, cf: upstream.headers.get("cf-cache-status") || undefined, ttfb: Math.round(performance.now() - t0), bytes: 0, t0, }; let body = request.method === "HEAD" ? null : upstream.body; if (ASSET_SIM) body = ASSET_SIM.throttle(body); if (rec) body = traceAssetBody(body, rec); return new Response(body, { status: upstream.status, headers: outHeaders }); } // ---------------------------------------------------------------- external links // Links leave the client for the player's browser: window.open (Khaosshop "Acheter en ligne", wiki) used to open an // Electron window the offline policy then blocked. The client's own ogrines / vote / support / "Create an account" / // "Forgot your password?" buttons point at its account API host (api.khaos.invalid) and Ankama: those go to the // Khaosdofus website instead (KHAOS_WEBSITE; the mapping is launcher/externalUrl.cjs). const WEBSITE = (process.env.KHAOS_WEBSITE || "https://play.khaosdofus.com/").replace(/\/?$/, "/"); const openExternal = shell.openExternal.bind(shell); shell.openExternal = (raw, options) => { const target = externalUrl(raw, WEBSITE); logRequest(`EXTERNAL ${String(raw).replace(/\?.*$/, "")}${target && target !== raw ? ` -> ${target}` : ""}`); return target ? openExternal(target, options) : Promise.resolve(); }; app.on("web-contents-created", (_event, contents) => { // Never a window inside the client: web links go to the browser (externalUrl drops other schemes), anything else // (file:, data:, javascript:, about:blank) is refused (client audit 2026-10-21, C5; the client's own guard, // recovered/src/electron/khaos/security.js, replaces this handler on its pages and refuses the same). contents.setWindowOpenHandler(({ url }) => { if (/^https?:/i.test(url)) void shell.openExternal(url); return { action: "deny" }; }); }); // Khaos (stability, owner report 2026-10-06: "the client opens to a black screen and nothing can be done"): the app page // (index.html of the renderer server) is reloaded when it fails to load, or when none of its code has run 45 s after // it loaded (the action journal, the first module, is still missing: a module request that never answered). At most // 3 reloads in 3 minutes. Once the app code runs, the renderer's own watchdog (khaos/boot/bootWatchdog.js) takes over. const APP_START_TIMEOUT_MS = 45000; function guardAppPageStart(contents) { let origin = ""; try { origin = new URL(process.env.ELECTRON_RENDERER_URL).origin; } catch { return; } const isAppPage = (raw) => { try { const u = new URL(raw); return u.origin === origin && (u.pathname === "/" || u.pathname === "/index.html"); } catch { return false; } }; let windowStart = 0; let reloads = 0; let poll = null; const stopPoll = () => { if (poll) clearInterval(poll); poll = null; }; const reload = (why, url) => { stopPoll(); if (contents.isDestroyed()) return; if (Date.now() - windowStart > 180000) { windowStart = Date.now(); reloads = 0; } if (reloads >= 3) { console.error(`[khaos] app page ${why}; 3 reloads did not help, leaving it (Ctrl+R to retry)`); return; } reloads++; console.warn(`[khaos] app page ${why}; reloading (${reloads}/3)`); logRequest(`APP-PAGE ${why}; reload ${reloads}/3`); setTimeout(() => { if (!contents.isDestroyed()) void contents.loadURL(url).catch(() => {}); }, 1000); }; contents.on("did-fail-load", (_e, code, desc, url, isMainFrame) => { // -3 = aborted (a newer navigation replaced this one) if (isMainFrame && code !== -3 && isAppPage(url)) reload(`failed to load (${code} ${desc})`, url); }); contents.on("did-navigate", (_e, url) => { stopPoll(); if (!isAppPage(url)) return; const started = Date.now(); let checking = false; poll = setInterval(() => { if (contents.isDestroyed()) return stopPoll(); const late = Date.now() - started >= APP_START_TIMEOUT_MS; // executeJavaScript waits for the page to stop loading: a page still loading (a module request that never // answers) is checked by time alone if (contents.isLoading()) { if (late) reload(`still loading after ${APP_START_TIMEOUT_MS / 1000} s`, url); return; } if (checking) return; checking = true; contents .executeJavaScript("!!globalThis.__khaosJournal", true) .then((running) => { if (running) stopPoll(); else if (poll && late) reload(`did not start within ${APP_START_TIMEOUT_MS / 1000} s`, url); }) .catch(() => {}) .finally(() => { checking = false; }); }, 3000); }); contents.on("destroyed", stopPoll); } app.on("web-contents-created", (_event, contents) => guardAppPageStart(contents)); // Khaos (stability): after a GPU process crash Chromium may block WebGL for the page's origin until restart, so the // game view could never be rebuilt (renderer khaos/gpuRecovery.js rejoins to rebuild it). app.disableDomainBlockingFor3DAPIs(); app.whenReady().then(() => { // Khaos (stability): WebSocket handshakes go through neither protocol.handle nor the patched fetch, so the offline // policy never saw them. The client's social socket reached its vendor's master servers every ~31 s with our // launcher JWT (fixed at the source in Social.jsx). Any ws:/wss: to a non-loopback host is refused unless allowed. if (!ALLOW_REMOTE) { session.defaultSession.webRequest.onBeforeRequest({ urls: ["ws://*/*", "wss://*/*"] }, (details, callback) => { let host = ""; try { host = new URL(details.url).hostname.replace(/^\[|\]$/g, "").toLowerCase(); } catch { /* unparsable: refused below */ } const local = host === "localhost" || host === "::1" || /^127\./.test(host); if (!local) logRequest(`BLOCKED-WS ${details.url.replace(/\?.*$/, "")}`); callback({ cancel: !local }); }); } protocol.handle("https", async (request) => { let url; try { url = new URL(request.url); } catch { return new Response(null, { status: 400 }); } const host = url.hostname.toLowerCase(); if (hasMaster() && MASTER_HOSTS.has(host)) { logRequest(`MASTER ${request.method} ${request.url}`); try { return await forwardToMaster(request, url); } catch (err) { logRequest(`MASTER-ERROR ${request.url} ${err && err.message}`); return new Response("Khaos master shim unreachable", { status: 502 }); } } if (isAssetSource(url)) { if (ASSET_BASE) { const published = await serveFromAssetBase(request, url); if (published !== null) return published; } else if (ASSET_MIRROR) { const mirrored = await serveFromMirror(request, url); if (mirrored !== null) return mirrored; } // Never fetched from the network as such: a miss of the local corpus is refused (and logged) below. logRequest(`BLOCKED ${request.method} ${request.url}`); return new Response("not in the local Khaos corpus", { status: 404, headers: corsHeaders(request) }); } if (!ALLOW_REMOTE) { logRequest(`BLOCKED ${request.method} ${request.url}`); return new Response("blocked by the Khaos launcher (offline mode)", { status: 503, headers: { "content-type": "text/plain", ...corsHeaders(request) }, }); } logRequest(`REMOTE ${request.method} ${request.url}`); return net.fetch(request, { bypassCustomProtocolHandlers: true }); }); }); // ---------------------------------------------------------------- main-process fetch // main.cjs refreshes/revokes the account session with Node's global fetch (`${apiBase}/v1/auth/refresh`, // `/v1/auth/logout`, apiBase pinned to https://api.khaos.invalid/api by ju()). That bypasses protocol.handle, so apply // the same policy here. const nodeFetch = globalThis.fetch; globalThis.fetch = async (input, init) => { const href = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; let url; try { url = new URL(href); } catch { return nodeFetch(input, init); } const host = url.hostname.toLowerCase(); if (url.protocol === "https:" && hasMaster() && MASTER_HOSTS.has(host)) { logRequest(`MAIN-MASTER ${(init && init.method) || "GET"} ${href}`); return nodeFetch(`${await masterBase()}${url.pathname}${url.search}`, init); } if (url.protocol === "https:" && !ALLOW_REMOTE) { logRequest(`MAIN-BLOCKED ${(init && init.method) || "GET"} ${href}`); return new Response("blocked by the Khaos launcher (offline mode)", { status: 503 }); } return nodeFetch(input, init); }; // ---------------------------------------------------------------- start the client // main.cjs computes the dofus-assets://core directory once at load time: // isPackaged ? recovered/dist/core : recovered/public/core. // The CSS hard-codes dofus-assets://core/... fonts and textures, so report // "packaged" only while the module loads; at runtime isPackaged is false again // (renderer from ELECTRON_RENDERER_URL, no updater, no Updater.exe hand-off). The installed client (a really // packaged Electron, launcher/player.cjs) gets the same runtime behaviour: isPackaged is an inherited getter, so an // own property is defined both ways instead of restoring the native value. Object.defineProperty(app, "isPackaged", { configurable: true, get: () => true }); try { require(CLIENT_MAIN); } finally { Object.defineProperty(app, "isPackaged", { configurable: true, get: () => false }); }