Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Trend Research v0.1.4 · generic

Archive SHA-256 cb60f7918116082765a6fbb8d85ed38dea874db8a99ea82d26fa42e996fddd04 · 41.6 KB · built Nov 27, 2026

src/net.js

// Network helpers: user-supplied host validation (SSRF guard), optional DNS check, and a bounded
// fetch that follows redirects manually so each hop is re-checked against the allowlist.

import { isIP } from "node:net";
import { lookup as dnsLookup } from "node:dns/promises";
import { request as httpsRequest } from "node:https";
import { Readable } from "node:stream";
import { ToolError } from "./errors.js";

export const USER_AGENT = "AgentRove-TrendResearch/0.1 (local feed reader)";
const HOST_RE = /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;
const BLOCKED_SUFFIXES = [".localhost", ".local", ".internal", ".lan", ".home", ".corp", ".intranet", ".arpa"];

/** Validates and normalises user-listed hosts: exact public DNS names only (no wildcards, IPs, ports, localhost). */
export function normaliseHosts(list) {
  const out = [];
  for (const raw of list) {
    const h = String(raw).trim().toLowerCase().replace(/\.$/, "");
    if (h.includes("*")) throw new ToolError("invalid_input", `allowed_hosts: wildcards are not accepted ("${h.slice(0, 80)}")`);
    if (isIP(h.replace(/^\[|\]$/g, "")) !== 0) throw new ToolError("invalid_input", `allowed_hosts: IP addresses are not accepted ("${h.slice(0, 80)}")`);
    if (h === "localhost" || BLOCKED_SUFFIXES.some((s) => h.endsWith(s)) || !HOST_RE.test(h)) {
      throw new ToolError("invalid_input", `allowed_hosts: "${h.slice(0, 80)}" is not a public DNS hostname`);
    }
    if (!out.includes(h)) out.push(h);
  }
  return out;
}

// ---------------------------------------------------------------------------------------------
// Address classification and connect-time pinning (security review 2026-11-26, finding F10b).
// Zero dependencies: node:net, node:dns, node:https and node:stream only.
// ---------------------------------------------------------------------------------------------
function privateV4(ip) {
  const [a, b, c] = ip.split(".").map(Number);
  return (
    a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) ||
    (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224 ||
    (a === 192 && b === 0 && c === 0) || (a === 198 && (b === 18 || b === 19))
  );
}

/** Expands any IPv6 text form (including a dotted IPv4 tail and a zone id) to 8 numbers, or null. */
export function v6Hextets(ip) {
  let s = String(ip).toLowerCase().replace(/%.*$/, "");
  const tail = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(s);
  if (tail) {
    if (isIP(tail[2]) !== 4) return null;
    const [a, b, c, d] = tail[2].split(".").map(Number);
    s = `${tail[1]}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;
  }
  const halves = s.split("::");
  if (halves.length > 2) return null;
  const left = halves[0] ? halves[0].split(":") : [];
  const right = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
  const fill = halves.length === 2 ? 8 - left.length - right.length : 0;
  if (fill < 0 || (halves.length === 2 && fill === 0)) return null;
  const parts = [...left, ...Array(fill).fill("0"), ...right];
  if (parts.length !== 8 || parts.some((p) => !/^[0-9a-f]{1,4}$/.test(p))) return null;
  return parts.map((p) => parseInt(p, 16));
}

const v4Of = (hi, lo) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;

/**
 * True for loopback, private, link-local, CGNAT, multicast and reserved IPv4 ranges, and for IPv6 that is
 * loopback/unspecified, unique-local (fc00::/7), link-local or site-local (fe80::/10, fec0::/10), multicast,
 * discard (100::/64), or that embeds or translates to such an IPv4 address: IPv4-mapped (any notation),
 * IPv4-compatible, NAT64 (64:ff9b::/96) and 6to4 (2002::/16). Unparseable input counts as private.
 */
export function isPrivateIp(ip) {
  if (isIP(ip) === 4) return privateV4(ip);
  const h = v6Hextets(ip);
  if (!h) return true;
  const zeroTo = (n) => h.slice(0, n).every((x) => x === 0);
  if (zeroTo(7) && (h[7] === 0 || h[7] === 1)) return true;
  if (zeroTo(5) && h[5] === 0xffff) return privateV4(v4Of(h[6], h[7]));
  if (zeroTo(6)) return privateV4(v4Of(h[6], h[7]));
  if (h[0] === 0x64 && h[1] === 0xff9b && h.slice(2, 6).every((x) => x === 0)) return privateV4(v4Of(h[6], h[7]));
  if (h[0] === 0x2002) return privateV4(v4Of(h[1], h[2]));
  if (h[0] === 0x100 && h.slice(1, 4).every((x) => x === 0)) return true;
  if ((h[0] & 0xfe00) === 0xfc00) return true;
  if ((h[0] & 0xffc0) === 0xfe80 || (h[0] & 0xffc0) === 0xfec0) return true;
  if ((h[0] & 0xff00) === 0xff00) return true;
  return false;
}

/**
 * A `lookup` for node:https that resolves once, refuses the connection when ANY answer is private and
 * hands the socket exactly the address it checked. Used at connect time, it closes the DNS-rebinding gap
 * between "check the host" and "fetch" (the fetch would otherwise resolve again).
 */
export function safeLookup(resolver = dnsLookup) {
  return (hostname, options, cb) => {
    const all = typeof options === "object" && options !== null && options.all === true;
    Promise.resolve()
      .then(() => resolver(hostname, { all: true, verbatim: true }))
      .then((addrs) => {
        if (!Array.isArray(addrs) || !addrs.length) return cb(Object.assign(new Error(`${hostname} did not resolve`), { code: "ENOTFOUND" }), all ? [] : "", 4);
        if (addrs.some((a) => isPrivateIp(a.address))) return cb(Object.assign(new Error(`${hostname} resolves to a private, loopback or link-local address; connection refused`), { code: "EPRIVATE" }), all ? [] : "", 4);
        if (all) return cb(null, addrs.map((a) => ({ address: a.address, family: a.family })));
        cb(null, addrs[0].address, addrs[0].family);
      })
      .catch((e) => cb(e, all ? [] : "", 4));
  };
}

const NULL_BODY = new Set([101, 103, 204, 205, 304]);

/**
 * fetch-compatible GET/HEAD over node:https whose TCP connection only ever goes to an address that
 * safeLookup validated. It never follows redirects (the caller and the SDK re-check every hop), keeps TLS
 * certificate checks on, and streams the body so callers' size caps apply. deps.request is for tests.
 */
export function pinnedFetch({ resolver = dnsLookup, request } = {}) {
  return async (url, init = {}) => {
    const u = new URL(String(url));
    if (u.protocol !== "https:") throw Object.assign(new Error("pinnedFetch: https only"), { code: "EPROTO" });
    const doRequest = request ?? httpsRequest;
    const headers = {};
    new Headers(init.headers ?? {}).forEach((v, k) => {
      headers[k] = v;
    });
    return new Promise((resolve, reject) => {
      const signal = init.signal;
      let req;
      const onAbort = () => req?.destroy(Object.assign(new Error("The operation was aborted"), { name: "AbortError" }));
      if (signal?.aborted) return reject(Object.assign(new Error("The operation was aborted"), { name: "AbortError" }));
      req = doRequest(
        { method: init.method ?? "GET", protocol: "https:", hostname: u.hostname, port: u.port || 443, path: `${u.pathname}${u.search}`, headers, lookup: safeLookup(resolver), servername: u.hostname },
        (res) => {
          const out = new Headers();
          for (const [k, v] of Object.entries(res.headers ?? {})) {
            if (Array.isArray(v)) v.forEach((x) => out.append(k, String(x)));
            else if (v !== undefined) out.set(k, String(v));
          }
          const status = res.statusCode >= 200 && res.statusCode <= 599 ? res.statusCode : 502;
          const body = NULL_BODY.has(status) || (init.method ?? "GET") === "HEAD" ? null : Readable.toWeb(res);
          if (!body) res.resume?.();
          signal?.removeEventListener?.("abort", onAbort);
          if (signal) signal.addEventListener("abort", () => res.destroy?.(Object.assign(new Error("The operation was aborted"), { name: "AbortError" })), { once: true });
          resolve(new Response(body, { status, headers: out }));
        },
      );
      if (signal) signal.addEventListener("abort", onAbort, { once: true });
      req.on("error", (e) => reject(e));
      req.end();
    });
  };
}

/** Returns the subset of hosts whose DNS answers are all public addresses (fails closed). */
export async function publicHostsOnly(hosts, lookup = dnsLookup) {
  const ok = [];
  const rejected = [];
  for (const h of hosts) {
    try {
      const addrs = await lookup(h, { all: true, verbatim: true });
      if (addrs.length && addrs.every((a) => !isPrivateIp(a.address))) ok.push(h);
      else rejected.push(h);
    } catch {
      rejected.push(h);
    }
  }
  return { ok, rejected };
}

async function readCapped(res, maxBytes) {
  const declared = Number(res.headers.get("content-length") ?? 0);
  if (declared > maxBytes) throw new ToolError("too_large", `Response is ${declared} bytes; the limit is ${maxBytes}.`);
  if (!res.body || typeof res.body.getReader !== "function") {
    const t = await res.text();
    if (Buffer.byteLength(t, "utf8") > maxBytes) throw new ToolError("too_large", `Response exceeds ${maxBytes} bytes.`);
    return t;
  }
  const reader = res.body.getReader();
  const chunks = [];
  let total = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    total += value.byteLength;
    if (total > maxBytes) {
      await reader.cancel().catch(() => {});
      throw new ToolError("too_large", `Response exceeds ${maxBytes} bytes.`);
    }
    chunks.push(value);
  }
  return new TextDecoder("utf-8").decode(Buffer.concat(chunks.map((c) => Buffer.from(c))));
}

/**
 * GETs a URL through the permission-guarded ctx.fetch. Redirects are followed manually (max 3) and
 * every hop goes back through ctx.fetch, so the allowlist applies to each hop.
 */
export async function fetchText(ctx, url, { maxBytes, accept, rejectHtml = true }) {
  let current = url;
  for (let hop = 0; hop <= 3; hop++) {
    const res = await ctx.fetch(current, { method: "GET", redirect: "manual", headers: { accept, "user-agent": USER_AGENT } });
    if (res.status >= 300 && res.status < 400) {
      const loc = res.headers.get("location");
      if (!loc) throw new ToolError("http_error", `HTTP ${res.status} redirect without a Location header`);
      current = new URL(loc, current).toString();
      continue;
    }
    if (!res.ok) throw new ToolError("http_error", `HTTP ${res.status}`);
    const type = (res.headers.get("content-type") ?? "").toLowerCase();
    if (rejectHtml && type.includes("text/html")) throw new ToolError("not_a_feed", "Server returned an HTML page, not a feed. HTML pages are not scraped.");
    return { text: await readCapped(res, maxBytes), finalUrl: current };
  }
  throw new ToolError("http_error", "Too many redirects");
}

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).