/** * LD FDPI — network security regression test. * * * LAN off => SpoofDPI listens on 127.0.0.1 only (LAN IP refused). * * LAN on => 0.0.0.0 works for private peers, PAC answers normally. * * PAC request cap: >4096 bytes => 413. * * PAC slowloris timeout: 5 s => 408 / close. * * LAN off again => PAC closed, engine back to loopback. * * Usage: LD_FDPI_NO_ADMIN=1 npm run tauri build -- --no-bundle && node scripts/security-e2e.mjs */ 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 exe = [process.argv[2], path.join(ROOT, "..", ".ld-fdpi-target", "release", "ld-fdpi.exe")].find( (candidate) => candidate && fs.existsSync(candidate) ) || ""; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const originalConfig = fs.existsSync(CONFIG_PATH) ? fs.readFileSync(CONFIG_PATH, "utf8") : null; const BASE = { version: 6, autoStart: false, autoConnect: false, minimizeToTray: true, lanSharing: false, connectionMode: "normal", bypassMode: 1, chunkSize: 8, dohProvider: "cloudflare", proxyPort: 18480, pacPort: 18481, }; function writeConfig() { fs.mkdirSync(CONFIG_DIR, { recursive: true }); fs.writeFileSync(CONFIG_PATH, JSON.stringify(BASE, null, 2)); } function restoreConfig() { if (originalConfig !== null) fs.writeFileSync(CONFIG_PATH, originalConfig); else fs.writeFileSync(CONFIG_PATH, JSON.stringify({ ...BASE, autoStart: true, autoConnect: true }, null, 2)); } function canConnect(host, port, timeout = 2000) { 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(timeout, () => finish(false)); socket.once("connect", () => finish(true)); socket.once("error", () => finish(false)); }); } function request(port, payload, waitMs = 9000) { return new Promise((resolve) => { const socket = net.connect({ host: "127.0.0.1", port }); let data = ""; let done = false; const finish = (value) => { if (done) return; done = true; try { socket.destroy(); } catch { /* ignore */ } resolve(value); }; socket.setTimeout(waitMs, () => finish(data || "TIMEOUT")); socket.once("error", (error) => finish(data || `ERROR:${error.code}`)); socket.once("connect", () => socket.write(payload)); socket.on("data", (chunk) => { data += chunk.toString("latin1"); if (data.includes("\r\n\r\n")) { // Wait a moment for the body, then return. setTimeout(() => finish(data), 80); } }); socket.on("end", () => finish(data)); }); } class Cdp { constructor(url) { this.ws = new WebSocket(url); this.id = 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 eval(expression, awaitPromise = false) { await this.ready; const id = ++this.id; const response = new Promise((resolve) => this.pending.set(id, resolve)); this.ws.send( JSON.stringify({ id, method: "Runtime.evaluate", params: { expression, awaitPromise, returnByValue: true, userGesture: true }, }) ); const result = await response; if (result.result?.exceptionDetails) { throw new Error(JSON.stringify(result.result.exceptionDetails)); } return result.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; } close() { try { this.ws.close(); } catch { /* ignore */ } } } async function waitForCdp(port) { for (let i = 0; i < 120; i++) { 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 */ } await sleep(250); } throw new Error("CDP endpoint açılmadı"); } let passed = 0; let failed = 0; const check = (name, ok, detail = "") => { console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`); if (ok) passed++; else failed++; }; if (!exe) { console.error("ld-fdpi.exe bulunamadı."); process.exit(1); } writeConfig(); process.on("exit", () => { try { restoreConfig(); } catch { /* ignore */ } }); const child = spawn(exe, [], { env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: "--remote-debugging-port=9337" }, stdio: "ignore", }); let cdp = null; try { const page = await waitForCdp(9337); cdp = new Cdp(page.webSocketDebuggerUrl); await cdp.ready; for (let i = 0; i < 100; i++) { const ready = await cdp.eval( "typeof window.__TAURI_INTERNALS__?.invoke === 'function' && (document.body?.innerText || '').includes('BAĞLAN')" ); if (ready) break; await sleep(250); } // LAN off: engine must be loopback-only const conn = await cdp.invoke("start_connection", { config: { connectionMode: "normal", bypassMode: 1, chunkSize: 8, dohProvider: "cloudflare", lanSharing: true, // deliberately malicious/stale: must be ignored proxyPort: 18480, pacPort: 18481, }, }); const init = await cdp.invoke("get_initial_state"); const lanIp = init.localIp; // Small wait for the engine to be fully wired. await sleep(300); const loopbackOnly = !(await canConnect(lanIp, 18480)); check( "LAN kapalıyken motor yalnızca 127.0.0.1'de", conn.connected === true && loopbackOnly, `${lanIp}:18480 reachable=${!loopbackOnly}` ); // Enable LAN const pacPort = 18481; const lan = await cdp.invoke("toggle_lan_sharing", { enabled: true, proxyPort: 18480, pacPort, }); const lanReachable = await canConnect(lanIp, 18480); check( "LAN açıkken özel ağdan erişilebilir", lan.enabled === true && lanReachable === true, `${lanIp}:18480` ); const normal = await request(pacPort, "GET /proxy.pac HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"); check( "PAC normal istek 200", normal.startsWith("HTTP/1.1 200") && normal.includes("FindProxyForURL"), normal.split("\r\n")[0] ); const oversized = await request( pacPort, `GET / HTTP/1.1\r\nHost: x\r\n${"A".repeat(5000)}` ); check( "PAC 4096 bayt sınırı (413)", oversized.includes("413"), oversized.split("\r\n")[0] || oversized ); const slow = await new Promise((resolve) => { const socket = net.connect({ host: "127.0.0.1", port: pacPort }, () => socket.write("G")); let data = ""; socket.on("data", (chunk) => { data += chunk.toString("latin1"); }); socket.on("end", () => resolve(data)); socket.on("error", () => resolve(data)); setTimeout(() => { socket.destroy(); resolve(data); }, 7000); }); check( "PAC 5 sn Slowloris zaman aşımı (408 / kapanış)", slow.includes("408") || slow.length === 0, slow.split("\r\n")[0] || "bağlantı kapandı" ); // Disable LAN: PAC must be gone, engine loopback only await cdp.invoke("toggle_lan_sharing", { enabled: false, proxyPort: 18480, pacPort }); await sleep(400); const pacClosed = !(await canConnect("127.0.0.1", pacPort)); const loopbackAgain = !(await canConnect(lanIp, 18480)); check( "LAN kapatınca PAC kapanır + motor loopback'e döner", pacClosed && loopbackAgain, `pacClosed=${pacClosed} loopback=${loopbackAgain}` ); const stop = await cdp.invoke("stop_connection"); check("Bağlantı kesildi ve proxy geri yüklendi", stop.restoredOriginalProxy === true, stop.message); // Eduroam mode smoke test. On this desktop there is no Wi-Fi adapter, so the // mode must still connect (WinHTTP + WinINet) and report an honest warning. const eduroamPort = 18482; const eduroamPac = 18483; const edu = await cdp.invoke("start_connection", { config: { connectionMode: "eduroam", bypassMode: 1, chunkSize: 4, dohProvider: "auto", lanSharing: false, proxyPort: eduroamPort, pacPort: eduroamPac, }, }); check( "Eduroam Modu bağlanır (Wi-Fi yoksa dürüst uyarı)", edu.connected === true && Boolean(edu.warning), edu.warning || edu.message ); const eduStatus = await cdp.invoke("get_eduroam_status"); check( "Eduroam durumu SSID/MTU/802.1X alanlarını döndürür", eduStatus?.targetMtu === 1400 && typeof eduStatus?.wifi?.available === "boolean", `ssid=${eduStatus?.wifi?.ssid || "—"} mtu=${eduStatus?.mtu ?? "—"}` ); const eduDiag = await cdp.invoke("run_eduroam_diagnostics"); check( "Eduroam ağ testi (SSID/MTU/Discord TCP/UDP)", Array.isArray(eduDiag) && eduDiag.length >= 6, Array.isArray(eduDiag) ? `${eduDiag.filter((item) => item.passed).length}/${eduDiag.length}` : "—" ); const eduStop = await cdp.invoke("stop_connection"); check( "Eduroam modu kapanınca proxy/MTU geri yüklenir", eduStop.restoredOriginalProxy === true, eduStop.message ); } catch (error) { check("Güvenlik E2E", false, error.message); } finally { cdp?.close(); child.kill(); await sleep(800); try { spawnSync(exe, ["--restore-only"], { windowsHide: true, stdio: "ignore" }); } catch { /* ignore */ } } restoreConfig(); console.log(`\nSONUÇ: ${passed} başarılı, ${failed} başarısız`); process.exit(failed === 0 ? 0 : 1);