Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

6.5 KB
Raw Blame
// Name lookups for the network gates. Every connection a bot's shell or browser opens asks here first, so a lookup
// must never wait without bound, and must not queue behind file writes: the system lookup (getaddrinfo) runs on the
// four-thread pool that file writes share, where a slow name server holds every thread and the event log backs up
// behind it. So, on a Cloud home, names are asked of the name servers directly, off that pool, with a time limit; an answer is reused
// for a minute; and while the name servers do not answer, the last answer of the past quarter hour is used. Callers
// check the addresses against their policy on every call, reused or not.
import { lookup as systemLookup, Resolver } from "node:dns/promises";
import { networkInterfaces } from "node:os";

export interface NameAddress { address: string; family: number }

export interface NameLookupOptions {
  /** One record type from the name servers; rejects with a `code` as node:dns does. */
  query?(host: string, family: 4 | 6): Promise<string[]>;
  /** Called after a round no name server answered. */
  renew?(): void;
  /** Whether IPv6 addresses are listed before IPv4 ones. */
  ipv6First?(): boolean;
  /** The system's own lookup, which also reads the hosts file. */
  system?(host: string): Promise<NameAddress[]>;
  now?(): number;
  freshMs?: number;
  staleMs?: number;
  /** The longest one call waits for the name servers, and then for the system lookup. */
  waitMs?: number;
  maxNames?: number;
}

export interface NameLookup {
  (host: string): Promise<NameAddress[]>;
  /** Names answered from an answer past its minute because the name servers did not answer. */
  stale: number;
}

/** The name servers said the name has no such record: the hosts file may still know it. */
const NO_RECORD = new Set(["ENOTFOUND", "ENODATA", "ENONAME", "EBADNAME", "EBADRESP", "EFORMERR"]);

const withTimeout = <T>(work: Promise<T>, ms: number, fallback: T): Promise<T> =>
  new Promise((resolve) => {
    const timer = setTimeout(() => resolve(fallback), ms);
    timer.unref?.();
    work.then((value) => { clearTimeout(timer); resolve(value); }, () => { clearTimeout(timer); resolve(fallback); });
  });

/** A resolver keeps the name servers it read when it was made, so one that got no answer is made again: a machine
 * whose name servers changed is then asked through the new ones. */
function defaultQuery(): { query(host: string, family: 4 | 6): Promise<string[]>; renew(): void } {
  let resolver: Resolver | null = null;
  return {
    query: (host, family) => {
      resolver ??= new Resolver({ timeout: 2_000, tries: 2 });
      return family === 4 ? resolver.resolve4(host) : resolver.resolve6(host);
    },
    renew: () => { resolver = null; },
  };
}

/** Whether this machine has an IPv6 address the internet can route to. Without one IPv4 is listed first, as the
 * system lookup orders them, because some callers connect to the first address only. */
export function hasPublicIpv6(interfaces: ReturnType<typeof networkInterfaces> = networkInterfaces()): boolean {
  for (const entries of Object.values(interfaces)) {
    for (const entry of entries ?? []) {
      if (entry.family !== "IPv6" || entry.internal) continue;
      const first = Number.parseInt(entry.address.split(":")[0] || "0", 16);
      // 2000::/3 is the routable range; link-local (fe80::/10) and private (fc00::/7) addresses do not count.
      if ((first & 0xe000) === 0x2000) return true;
    }
  }
  return false;
}

const defaultSystem = (host: string): Promise<NameAddress[]> => systemLookup(host, { all: true, verbatim: true });

export function createNameLookup(options: NameLookupOptions = {}): NameLookup {
  const own = options.query ? null : defaultQuery();
  const query = options.query ?? own!.query;
  const renew = options.renew ?? own?.renew ?? (() => {});
  const ipv6First = options.ipv6First ?? hasPublicIpv6;
  const system = options.system ?? defaultSystem;
  const now = options.now ?? Date.now;
  const freshMs = options.freshMs ?? 60_000, staleMs = options.staleMs ?? 15 * 60_000;
  const waitMs = options.waitMs ?? 8_000, maxNames = options.maxNames ?? 2_048;
  const known = new Map<string, { addresses: NameAddress[]; at: number }>();
  const asking = new Map<string, Promise<NameAddress[]>>();

  const remember = (name: string, addresses: NameAddress[]) => {
    known.delete(name);
    known.set(name, { addresses, at: now() });
    if (known.size > maxNames) known.delete(known.keys().next().value!);
  };

  const ask = async (name: string): Promise<NameAddress[]> => {
    type Answer = { addresses: string[]; missing: boolean };
    const one = (family: 4 | 6): Promise<Answer> =>
      Promise.resolve().then(() => query(name, family)).then(
        (addresses) => ({ addresses, missing: false }),
        (error: NodeJS.ErrnoException) => ({ addresses: [], missing: NO_RECORD.has(error?.code ?? "") }),
      );
    const unanswered: Answer = { addresses: [], missing: false };
    const [six, four] = await Promise.all([withTimeout(one(6), waitMs, unanswered), withTimeout(one(4), waitMs, unanswered)]);
    const sixes = six.addresses.map((address) => ({ address, family: 6 })), fours = four.addresses.map((address) => ({ address, family: 4 }));
    const found: NameAddress[] = ipv6First() ? [...sixes, ...fours] : [...fours, ...sixes];
    if (found.length) { remember(name, found); return found; }
    // Only a name the name servers answered "no such record" for goes to the system lookup: asking it while they are
    // silent is what holds the shared pool.
    if (six.missing && four.missing) {
      const local = await withTimeout(system(name), waitMs, [] as NameAddress[]);
      if (local.length) { remember(name, local); return local; }
      known.delete(name);
      return [];
    }
    if (!six.missing && !four.missing) renew();
    const last = known.get(name);
    if (last && now() - last.at <= staleMs) { lookupName.stale += 1; return last.addresses; }
    return [];
  };

  const lookupName = (async (host: string): Promise<NameAddress[]> => {
    const name = host.toLowerCase().replace(/\.$/, "");
    if (!name) return [];
    const last = known.get(name);
    if (last && now() - last.at <= freshMs) return last.addresses;
    let pending = asking.get(name);
    if (!pending) {
      pending = ask(name).finally(() => asking.delete(name));
      asking.set(name, pending);
    }
    return pending;
  }) as NameLookup;
  lookupName.stale = 0;
  return lookupName;
}

/** The one lookup every gate in this process shares, so a name one bot just reached is not asked again for another. */
export const lookupName: NameLookup = createNameLookup();