network-deny.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Loaded only in isolated test children. Record attempts even if callers catch failures.
  2. import { appendFileSync } from 'node:fs';
  3. import { Socket } from 'node:net';
  4. const allowed = process.env.MCODE_TEST_ALLOWED_ORIGIN ? new URL(process.env.MCODE_TEST_ALLOWED_ORIGIN) : undefined;
  5. const originalFetch = globalThis.fetch;
  6. const originalConnect = Socket.prototype.connect;
  7. if (process.env.MCODE_TEST_PROCESS_PROBE === '1') {
  8. const startedAt = Date.now();
  9. const probe = setInterval(() => {
  10. process.stderr.write(`[test-process-probe] ${JSON.stringify({
  11. elapsedMs: Date.now() - startedAt,
  12. resources: process.getActiveResourcesInfo(),
  13. })}\n`);
  14. }, 10000);
  15. // This diagnostic timer must not keep an otherwise completed CLI alive.
  16. probe.unref();
  17. }
  18. function denied() {
  19. appendFileSync(process.env.MCODE_TEST_NETWORK_AUDIT, new Error('network-attempt').stack + '\n');
  20. throw new Error('Unexpected network access during standalone validation');
  21. }
  22. globalThis.fetch = function (input, init) {
  23. const url = new URL(typeof input === 'string' || input instanceof URL ? input : input.url);
  24. if (allowed && url.origin === allowed.origin) return originalFetch(input, init);
  25. // Offline acceptance after restoring managed capabilities: these requests return only local failure responses and never reach servers.
  26. // Keep attempted requests in a separate log; unknown addresses still fail tests.
  27. if (process.env.MCODE_TEST_MANAGED_OFFLINE === '1' && [
  28. 'agent.minimax.cn', 'agent.minimax.io', 'agent.minimaxi.com',
  29. 'www.minimaxi.com', 'platform.minimax.io', 'models.dev',
  30. 'data.hailuo.ai', 'data.hailuoai.com',
  31. ].includes(url.hostname) && url.protocol === 'https:') {
  32. appendFileSync(process.env.MCODE_TEST_NETWORK_AUDIT + '.managed', `${url.origin}${url.pathname}\n`);
  33. return Promise.resolve(new Response(JSON.stringify({ error: 'Managed service offline fixture' }), { status: 503 }));
  34. }
  35. return denied();
  36. };
  37. Socket.prototype.connect = function (...args) {
  38. const options = Array.isArray(args[0]) ? args[0][0] : args[0];
  39. if (allowed && options && typeof options === 'object' && options.host === allowed.hostname && String(options.port) === allowed.port) {
  40. return Reflect.apply(originalConnect, this, args);
  41. }
  42. return denied();
  43. };