okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-021-hostA' into f-021-int74e25e165

main
1.1 KiB20 linesraw
1/**
2 * Preloaded into a host process (`node --import`) to make the network "unplugged": every fetch to an address that is not this
3 * computer is written to the file in STRATA_NET_LOG (one URL per line) and fails the way a machine with no internet does
4 * (TypeError: fetch failed). Loopback calls pass through, so the host's own engine and UI traffic still works.
5 */
6import { appendFileSync } from 'node:fs';
7
8const real = globalThis.fetch;
9const log = process.env.STRATA_NET_LOG;
10const loopback = host => host === '127.0.0.1' || host === 'localhost' || host === '[::1]' || host === '::1';
11
12globalThis.fetch = function offlineFetch(input, init) {
13  let url;
14  try { url = new URL(typeof input === 'string' ? input : input?.url ?? String(input)); } catch { return real(input, init); }
15  if (loopback(url.hostname)) return real(input, init);
16  if (log) appendFileSync(log, `${url.href}\n`);
17  const error = new TypeError('fetch failed');
18  error.cause = Object.assign(new Error(`getaddrinfo ENOTFOUND ${url.hostname}`), { code: 'ENOTFOUND' });
19  return Promise.reject(error);
20};