/** * LD FDPI — GUI end-to-end smoke test (WebView2 CDP). * * Covers the new "set & forget" behaviour: * 1. Real Tauri IPC + simplified UI render * 2. BAĞLAN / BAĞLANTIYI KES through the actual buttons * 3. LAN sharing rebinds SpoofDPI to 0.0.0.0 and back * 4. config.json round-trip (camelCase persistence) * 5. `--minimized` silent start: hidden window, auto-connect before React * 6. Task Scheduler autostart path (admin warning in an asInvoker test build) * * Usage: LD_FDPI_NO_ADMIN=1 npm run tauri build -- --no-bundle && npm run test:gui */ import { spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; import net from "node:net"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const CONFIG_DIR = path.join(process.env.LOCALAPPDATA || os.tmpdir(), "LD-FDPI"); const CONFIG_PATH = path.join(CONFIG_DIR, "config.json"); const exeCandidates = [ process.argv[2], path.join(ROOT, "..", ".ld-fdpi-target", "release", "ld-fdpi.exe"), path.join(ROOT, "src-tauri", "target", "release", "ld-fdpi.exe"), ].filter(Boolean); const exe = exeCandidates.find((p) => fs.existsSync(p)); if (!exe) { console.error("ld-fdpi.exe bulunamadı. Önce `npm run tauri build -- --no-bundle` çalıştırın."); process.exit(1); } const BASE_CONFIG = { version: 6, autoStart: false, autoConnect: false, minimizeToTray: true, lanSharing: false, connectionMode: "normal", bypassMode: 1, chunkSize: 8, dohProvider: "cloudflare", proxyPort: 18080, pacPort: 18081, }; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); function readConfigFile() { try { return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8")); } catch { return null; } } const originalConfig = readConfigFile(); // Always restore the user's config, even if a check throws. process.on("exit", () => { try { restoreConfig(); } catch { /* ignore */ } }); function writeConfig(overrides = {}) { fs.mkdirSync(CONFIG_DIR, { recursive: true }); fs.writeFileSync(CONFIG_PATH, JSON.stringify({ ...BASE_CONFIG, ...overrides }, null, 2)); } function restoreConfig() { fs.mkdirSync(CONFIG_DIR, { recursive: true }); if (originalConfig) { fs.writeFileSync(CONFIG_PATH, JSON.stringify(originalConfig, null, 2)); } else { fs.writeFileSync(CONFIG_PATH, JSON.stringify(BASE_CONFIG, null, 2)); } } function freePort(start) { return new Promise((resolve) => { const server = net.createServer(); server.unref(); server.once("error", () => resolve(freePort(start + 1))); server.listen(start, "127.0.0.1", () => { const { port } = server.address(); server.close(() => resolve(port)); }); }); } /** TCP reachability (proves 0.0.0.0 vs 127.0.0.1 binding). */ function canConnect(host, port, timeoutMs = 2500) { return new Promise((resolve) => { const socket = net.connect({ host, port }); let done = false; const finish = (ok) => { if (done) return; done = true; try { socket.destroy(); } catch { /* ignore */ } resolve(ok); }; socket.setTimeout(timeoutMs, () => finish(false)); socket.once("connect", () => finish(true)); socket.once("error", () => finish(false)); }); } class Cdp { constructor(url) { this.ws = new WebSocket(url); this.nextId = 0; this.pending = new Map(); this.ready = new Promise((resolve, reject) => { this.ws.onopen = resolve; this.ws.onerror = reject; }); this.ws.onmessage = (event) => { const message = JSON.parse(event.data); if (message.id && this.pending.has(message.id)) { this.pending.get(message.id)(message); this.pending.delete(message.id); } }; } async send(method, params = {}) { await this.ready; const id = ++this.nextId; const promise = new Promise((resolve) => this.pending.set(id, resolve)); this.ws.send(JSON.stringify({ id, method, params })); return promise; } async eval(expression, awaitPromise = false) { const response = await this.send("Runtime.evaluate", { expression, awaitPromise, returnByValue: true, userGesture: true, }); if (response.result?.exceptionDetails) { throw new Error( response.result.exceptionDetails.exception?.description || JSON.stringify(response.result.exceptionDetails) ); } return response.result?.result?.value; } async invoke(command, args = {}) { const raw = await this.eval( `window.__TAURI_INTERNALS__.invoke(${JSON.stringify(command)}, ${JSON.stringify( args )}).then(r => JSON.stringify({ ok: true, value: r })).catch(e => JSON.stringify({ ok: false, error: String(e) }))`, true ); const parsed = JSON.parse(raw); if (!parsed.ok) throw new Error(parsed.error); return parsed.value; } async click(label) { return this.eval( `(() => { const b = [...document.querySelectorAll('button')].find(x => x.innerText.trim() === ${JSON.stringify( label )}); if (!b) return false; b.click(); return true; })()` ); } close() { try { this.ws.close(); } catch { /* ignore */ } } } async function waitForCdp(port, timeoutMs = 30000) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { try { const list = await fetch(`http://127.0.0.1:${port}/json/list`).then((r) => r.json()); const page = list.find((t) => t.type === "page"); if (page?.webSocketDebuggerUrl) return page; } catch { /* not up yet */ } await sleep(250); } throw new Error("WebView2 CDP endpoint açılmadı (başka bir örnek çalışıyor olabilir)"); } async function launch({ args = [], cdpPort }) { const child = spawn(exe, args, { env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${cdpPort}`, }, stdio: "ignore", }); const page = await waitForCdp(cdpPort); const cdp = new Cdp(page.webSocketDebuggerUrl); await cdp.ready; for (let i = 0; i < 120; i++) { const state = JSON.parse( await cdp.eval( "JSON.stringify({ ready: document.readyState, internals: typeof window.__TAURI_INTERNALS__?.invoke, body: (document.body && document.body.innerText || '').length })" ) ); if (state.ready === "complete" && state.internals === "function" && state.body > 20) break; await sleep(250); } return { child, cdp }; } async function stopSession(session) { if (!session) return; try { if (session.cdp) { await Promise.race([session.cdp.invoke("stop_connection"), sleep(3000)]); } } catch { /* ignore */ } session.cdp?.close(); if (session.child) { session.child.kill(); await sleep(800); } // Last-resort cleanup: restore a dirty proxy even if the app was killed. try { spawnSync(exe, ["--restore-only"], { windowsHide: true, stdio: "ignore" }); } catch { /* ignore */ } } let passed = 0; let failed = 0; function check(name, ok, detail = "") { console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`); if (ok) passed++; else failed++; } // --------------------------------------------------------------------------- // Session 1: normal launch, UI click-through, LAN, config persistence // --------------------------------------------------------------------------- writeConfig(); let session = null; try { session = await launch({ cdpPort: 9333 }); const { cdp, child } = session; const internals = JSON.parse( await cdp.eval( "JSON.stringify({ obj: typeof window.__TAURI_INTERNALS__, invoke: typeof window.__TAURI_INTERNALS__?.invoke })" ) ); check( "Tauri v2 çalışma zamanı enjekte edildi", internals.obj === "object" && internals.invoke === "function", JSON.stringify(internals) ); const init = await cdp.invoke("get_initial_state"); check( "get_initial_state · gerçek motor", init.engineFound === true && Boolean(init.engineVersion), `${init.engineVersion} | admin=${init.isAdmin}` ); let body = ""; for (let i = 0; i < 40; i++) { body = await cdp.eval("document.body.innerText"); if (body.includes("BAĞLAN")) break; await sleep(250); } check( "Sadeleştirilmiş arayüz çizildi", body.includes("BAĞLAN") && body.includes("Bağlantı") && !body.includes("ClientHello"), `${body.length} karakter` ); const status0 = await cdp.invoke("get_status"); check("Normal başlatmada pencere görünür", status0.windowVisible === true, ""); check("Açılışta bağlı değil (autoConnect kapalı)", status0.isConnected === false, ""); const diag = await cdp.invoke("run_diagnostics"); check( "run_diagnostics gerçek sonuçlar", Array.isArray(diag) && diag.length >= 6, Array.isArray(diag) ? `${diag.filter((d) => d.passed).length}/${diag.length}` : String(diag) ); // LAN while disconnected const lanPacPort = await freePort(18181); const lan = await cdp.invoke("toggle_lan_sharing", { enabled: true, proxyPort: 18080, pacPort: lanPacPort, }); const pacBody = await fetch(`http://127.0.0.1:${lanPacPort}/proxy.pac`) .then((r) => r.text()) .catch(() => ""); check( "LAN paylaşımı + PAC sunucusu", lan.enabled === true && pacBody.includes("FindProxyForURL"), lan.pacUrl ); await cdp.invoke("toggle_lan_sharing", { enabled: false, proxyPort: 18080, pacPort: lanPacPort, }); // Connect through the real button check("BAĞLAN düğmesi bulundu", (await cdp.click("BAĞLAN")) === true, ""); let connectedText = ""; for (let i = 0; i < 160; i++) { connectedText = await cdp.eval("document.body.innerText"); if (connectedText.includes("FDPI Bağlı")) break; await sleep(250); } check( "Arayüz 'FDPI Bağlı'", connectedText.includes("FDPI Bağlı"), connectedText.includes("Bağlantı başlatılamadı") ? "arayüzde hata var" : "" ); const status1 = await cdp.invoke("get_status"); check( "Motor + proxy gerçekten etkin", status1.isConnected === true && status1.engineAlive === true && status1.proxyRouted === true, `engine=${status1.engineAlive} proxy=${status1.proxyRouted}` ); const reg = await cdp.invoke("get_initial_state"); check( "Windows proxy'si yazıldı", reg.systemProxy?.proxyEnable === 1 && reg.systemProxy?.pointsToLdFdpiPort === 18080, `ProxyEnable=${reg.systemProxy?.proxyEnable} ProxyServer=${reg.systemProxy?.proxyServer}` ); const persisted = readConfigFile(); check( "config.json kalıcı (camelCase)", persisted?.proxyPort === 18080 && persisted?.connectionMode === "normal" && persisted?.autoConnect === false, `${CONFIG_PATH}` ); // LAN while connected → 0.0.0.0 rebind const lanIp = reg.localIp; const lanPac2 = await freePort(18281); const lanOn = await cdp.invoke("toggle_lan_sharing", { enabled: true, proxyPort: 18080, pacPort: lanPac2, }); const lanReachable = await canConnect(lanIp, 18080); check( "LAN açıkken motor 0.0.0.0'da", lanOn.enabled === true && lanReachable === true, `${lanIp}:18080 reachable=${lanReachable}` ); await cdp.invoke("toggle_lan_sharing", { enabled: false, proxyPort: 18080, pacPort: lanPac2, }); const lanClosed = await canConnect(lanIp, 18080); check( "LAN kapatınca 127.0.0.1'e döndü", lanClosed === false, `${lanIp}:18080 reachable=${lanClosed}` ); // Settings persistence through save_config const saved = await cdp.invoke("save_config", { config: { ...reg.config, bypassMode: 2, chunkSize: 4, dohProvider: "google", minimizeToTray: false, }, }); const afterSave = readConfigFile(); check( "Ayarlar diske yazıldı", afterSave?.bypassMode === 2 && afterSave?.chunkSize === 4 && afterSave?.dohProvider === "google" && afterSave?.minimizeToTray === false, `warning=${saved.warning || "yok"}` ); if (!init.isAdmin) { const auto = await cdp.invoke("save_config", { config: { ...saved.config, autoStart: true }, }); check( "Autostart, yönetici olmadan uyarı üretiyor", // A pre-existing elevated task from an older install can leave the // effective flag true even though apply() failed; the warning invariant // is what matters in this asInvoker test build. Boolean(auto.warning), auto.warning || "" ); await cdp.invoke("save_config", { config: { ...auto.config, autoStart: false }, }); } // Restore the test settings await cdp.invoke("save_config", { config: { ...saved.config, bypassMode: 1, chunkSize: 8, dohProvider: "cloudflare", minimizeToTray: true, }, }); // Disconnect through the real button check("BAĞLANTIYI KES düğmesi bulundu", (await cdp.click("BAĞLANTIYI KES")) === true, ""); let disconnectedText = ""; for (let i = 0; i < 80; i++) { disconnectedText = await cdp.eval("document.body.innerText"); if (disconnectedText.includes("Bağlı Değil")) break; await sleep(250); } check("Arayüz 'Bağlı Değil'", disconnectedText.includes("Bağlı Değil"), ""); const after = await cdp.invoke("get_initial_state"); check( "Proxy orijinal değerine döndü", after.systemProxy?.proxyEnable === 0 && after.systemProxy?.proxyServer === null, `ProxyEnable=${after.systemProxy?.proxyEnable} ProxyServer=${after.systemProxy?.proxyServer}` ); child.kill(); await sleep(800); } catch (error) { check("GUI oturumu 1", false, error.message); } finally { await stopSession(session); } // --------------------------------------------------------------------------- // Session 2: --minimized + auto_connect, before React // --------------------------------------------------------------------------- writeConfig({ autoConnect: true, proxyPort: 18090, pacPort: 18091 }); session = null; try { session = await launch({ args: ["--minimized"], cdpPort: 9334 }); const { cdp } = session; let autoStatus = null; for (let i = 0; i < 120; i++) { autoStatus = await cdp.invoke("get_status"); if (autoStatus.isConnected) break; await sleep(250); } check( "--minimized otomatik bağlandı", autoStatus?.isConnected === true && autoStatus?.proxyRouted === true, `connected=${autoStatus?.isConnected} routed=${autoStatus?.proxyRouted}` ); check( "Sessiz başlangıçta pencere gizli", autoStatus?.windowVisible === false, `windowVisible=${autoStatus?.windowVisible}` ); const init2 = await cdp.invoke("get_initial_state"); check( "Otomatik bağlantı kaydedilmiş ayarları kullandı", init2.isConnected === true && init2.config.proxyPort === 18090, `port=${init2.config.proxyPort}` ); // The hidden webview may lag behind the backend poll; stop through IPC. const stopRes = await cdp.invoke("stop_connection"); await sleep(1000); check( "Otomatik oturum bağlantıyı kesti", stopRes.connected === false && stopRes.restoredOriginalProxy === true, stopRes.message ); const stopped = await cdp.invoke("get_initial_state"); check( "Otomatik oturum proxy'yi geri yükledi", stopped.systemProxy?.proxyEnable === 0, `ProxyEnable=${stopped.systemProxy?.proxyEnable}` ); session.child.kill(); await sleep(800); } catch (error) { check("GUI oturumu 2 (auto-connect)", false, error.message); } finally { await stopSession(session); } // --------------------------------------------------------------------------- // Restore the user's original config // --------------------------------------------------------------------------- restoreConfig(); console.log(`\nSONUÇ: ${passed} başarılı, ${failed} başarısız`); process.exit(failed === 0 ? 0 : 1);