// Network guard for the MMRT frontend test suite. // // SAFETY: This module is imported first by every test file. It hard-blocks // every outbound network primitive so that no test can ever perform a real // HTTP request, SMTP send, DNS lookup or raw socket connect even by accident. // The original implementations are captured and can be restored via // restoreNetwork() if a test ever legitimately needs them (none currently do). // // Run order: import this module at the very top of a test file, BEFORE any // application module is imported, so that any transitive client that tries to // open a connection at import time fails loudly instead of dialing out. import dns from 'node:dns'; import net from 'node:net'; const original = { fetch: globalThis.fetch, socketConnect: net.Socket.prototype.connect, dnsLookup: dns.lookup, dnsLookupPromises: dns.promises ? dns.promises.lookup : undefined, }; let installed = false; /** * Install the network guard. Idempotent. */ export function blockNetwork() { if (installed) { return; } installed = true; const boom = (what) => () => { throw new Error( `[network-guard] Blocked outbound ${what} during tests. ` + 'Tests must never touch the network. Mock the client instead.' ); }; // Block fetch (covers axios when it falls back to fetch, and any direct use). globalThis.fetch = boom('fetch()'); // Block raw TCP socket connects (covers http/https/axios over Node http). net.Socket.prototype.connect = function () { throw new Error( '[network-guard] Blocked outbound TCP connect during tests. ' + 'Tests must never touch the network. Mock the client instead.' ); }; // Block DNS resolution so nothing can even resolve a host. dns.lookup = boom('dns.lookup'); if (dns.promises && dns.promises.lookup) { dns.promises.lookup = boom('dns.promises.lookup'); } } /** * Restore the original network primitives. Used in test teardown. */ export function restoreNetwork() { if (!installed) { return; } installed = false; globalThis.fetch = original.fetch; net.Socket.prototype.connect = original.socketConnect; dns.lookup = original.dnsLookup; if (dns.promises && original.dnsLookupPromises) { dns.promises.lookup = original.dnsLookupPromises; } }