// The web module against a fake web on loopback: the pacer (one at a time,
// 3 s gaps, back-off), DuckDuckGo's HTML read, the page reader and its fence.
import { after, before, test } from "node:test";
import assert from "node:assert/strict";
import { startFakeWeb, type FakeWeb } from "../../testing/web/fakeWeb.mjs";
import { WebPacer, WebRequestError, WEB_MIN_GAP_MS } from "./pacer";
import { parseDuckDuckGoHtml, webSearch } from "./search";
import { fetchRefusal, htmlToReadableText, isPrivateAddress, webFetch } from "./fetchPage";
import { webTools } from "./tools";
let web: FakeWeb;
before(async () => {
web = await startFakeWeb({
results: {
"second shop": [
{ title: "The second shop opens", url: "https://news.example/shop?id=1&x=2", snippet: "It opened in the spring." },
{ title: "Bakery & co", url: "https://bakery.example/", snippet: "" },
{ title: "Third", url: "https://third.example/", snippet: "three" },
],
},
});
});
after(() => web.close());
// A pacer on a fake clock: sleeping advances it, and every sleep is recorded.
// jitter 0 unless a test asks: the gaps below are the exact ones.
function clockPacer(opts: ConstructorParameters[1] = { jitter: 0 }) {
let now = 1_000_000;
const sleeps: number[] = [];
const pacer = new WebPacer(
{
now: () => now,
sleep: async (ms) => {
sleeps.push(ms);
now += ms;
},
},
opts,
);
return { pacer, sleeps, advance: (ms: number) => (now += ms) };
}
const page = (p: string, pacer: WebPacer) => webFetch(web.url(p), { pacer, allowPrivate: true });
test("pacer: one request at a time, at least 3 s between them", async () => {
const { pacer, sleeps } = clockPacer();
assert.equal(WEB_MIN_GAP_MS, 3000);
let inFlight = 0;
let most = 0;
const pacerFetch = new WebPacer(
{
now: () => 0,
sleep: async () => {},
fetch: async (url, init) => {
inFlight++;
most = Math.max(most, inFlight);
await new Promise((r) => setTimeout(r, 15));
inFlight--;
return fetch(url, init);
},
},
{},
);
await Promise.all([page("/page/a", pacerFetch), page("/page/b", pacerFetch), page("/text", pacerFetch)]);
assert.equal(most, 1, "never two at once");
// On the fake clock: the second and third each waited the full gap.
await Promise.all([page("/page/a", pacer), page("/page/b", pacer), page("/text", pacer)]);
assert.deepEqual(sleeps, [3000, 3000]);
assert.equal(pacer.sent.length, 3);
assert.ok(pacer.sent[1]!.at - pacer.sent[0]!.at >= 3000);
assert.ok(web.requests.every((r) => /Firefox/.test(r.ua ?? "")), "a plain user agent");
});
test("pacer: a 429 backs off (Retry-After) and retries; a 503 that persists fails after three tries, backing off each time", async () => {
const { pacer, sleeps } = clockPacer();
const p = await page("/busy", pacer);
assert.match(p.text, /second shop opened/);
assert.deepEqual(sleeps, [1000, 2000], "Retry-After: 1, then the rest of the 3 s gap");
const down = clockPacer();
await assert.rejects(page("/down", down.pacer), (e: Error) => e instanceof WebRequestError && /HTTP 503 3 times — backing off/.test(e.message));
assert.deepEqual(down.sleeps, [10000, 20000]);
});
test("search: DuckDuckGo's HTML read — links unwrapped, ads skipped, snippets as text, n results", async () => {
const { pacer } = clockPacer();
const r = await webSearch("second shop", { searchUrl: web.searchUrl, pacer, n: 2 });
assert.deepEqual(r, [
{ title: "The second shop opens", url: "https://news.example/shop?id=1&x=2", snippet: "It opened in the spring." },
{ title: "Bakery & co", url: "https://bakery.example/", snippet: "" },
]);
assert.deepEqual(await webSearch("nothing here", { searchUrl: web.searchUrl, pacer }), []);
await assert.rejects(webSearch(" ", { searchUrl: web.searchUrl, pacer }), /needs a query/);
const posted = web.requests.filter((x) => x.path === "/html/");
assert.equal(posted[0]!.method, "POST");
assert.equal(new URLSearchParams(posted[0]!.body).get("q"), "second shop");
assert.deepEqual(parseDuckDuckGoHtml("no results"), []);
});
test("fetch: a page as readable text — title, no script, style, nav or footer, entities decoded", async () => {
const { pacer } = clockPacer();
const p = await page("/page/a", pacer);
assert.equal(p.title, "The bakery & the oven");
assert.equal(p.contentType, "text/html");
assert.match(p.text, /^The bakery\nThe second shop opened in the spring\.\n+It is a small place with a big oven\.\n- bread\n- pies/);
assert.doesNotMatch(p.text, /tracking|color:red|Home \| About|footer text/);
assert.equal(p.truncated, false);
const t = await page("/text", pacer);
assert.equal(t.text, "plain words\nsecond line");
const long = await webFetch(web.url("/long"), { pacer, allowPrivate: true, maxChars: 500 });
assert.equal(long.truncated, true);
assert.equal(long.text.length, 500);
});
test("fetch: redirects followed (each hop fenced), at most five; a PDF is refused, not read", async () => {
const { pacer } = clockPacer();
const p = await page(`/redirect?to=${encodeURIComponent("/page/x")}`, pacer);
assert.equal(p.finalUrl, web.url("/page/x"));
assert.match(p.text, /The bakery/);
await assert.rejects(page("/loop", pacer), /more than 5 redirects/);
await assert.rejects(page("/pdf", pacer), /not a text page \(application\/pdf\)/);
await assert.rejects(page("/missing", pacer), /answered HTTP 404/);
});
test("the fence: http(s) only, no private or loopback host by name, address or resolution", async () => {
const pub = async () => ["93.184.216.34"];
const inside = async () => ["10.1.2.3"];
assert.match((await fetchRefusal("file:///etc/passwd"))!, /only http and https/);
assert.match((await fetchRefusal("ftp://example.com/x"))!, /only http and https/);
assert.match((await fetchRefusal("not a url"))!, /is not a URL/);
assert.match((await fetchRefusal("http://user:pw@example.com/"))!, /credentials/);
assert.match((await fetchRefusal("http://localhost:3001/api/ops/settings"))!, /private host/);
assert.match((await fetchRefusal("http://printer.local/"))!, /private host/);
assert.match((await fetchRefusal("http://127.0.0.1:3001/"))!, /private address/);
assert.match((await fetchRefusal("http://[::1]/"))!, /private address/);
assert.match((await fetchRefusal("http://169.254.169.254/latest/meta-data"))!, /private address/);
assert.match((await fetchRefusal("https://sneaky.example/", { resolve: inside }))!, /resolves to a private address \(10\.1\.2\.3\)/);
assert.equal(await fetchRefusal("https://example.com/", { resolve: pub }), null);
assert.equal(await fetchRefusal("http://127.0.0.1:9/", { allowPrivate: true }), null);
// The fake web is on loopback: without the test option, refused before any request.
const { pacer } = clockPacer();
const before = web.requests.length;
await assert.rejects(webFetch(web.url("/page/a"), { pacer }), /private address/);
assert.equal(web.requests.length, before);
for (const ip of ["10.0.0.1", "172.16.0.1", "172.31.255.255", "192.168.1.1", "127.0.0.1", "0.0.0.0", "100.64.0.1", "fd00::1", "fe80::1", "::ffff:192.168.0.1"]) {
assert.equal(isPrivateAddress(ip), true, ip);
}
for (const ip of ["93.184.216.34", "8.8.8.8", "172.32.0.1", "2606:4700::1111"]) assert.equal(isPrivateAddress(ip), false, ip);
});
test("htmlToReadableText keeps paragraphs apart", () => {
assert.deepEqual(htmlToReadableText("Ta
b&c
"), { title: "T", text: "a\nb&c" });
});
test("the agent tools: web_search and web_fetch, in the AgentTool shape", async () => {
const { pacer } = clockPacer();
const tools = webTools({ pacer, searchUrl: web.searchUrl, allowPrivate: true });
assert.deepEqual(tools.map((t) => t.name), ["web_search", "web_fetch"]);
const s = await tools[0]!.run({ query: "second shop", n: 1 }, {});
assert.equal(s, "- The second shop opens\n https://news.example/shop?id=1&x=2\n It opened in the spring.");
const f = await tools[1]!.run({ url: web.url("/page/a"), max_chars: 300 }, {});
assert.match(f, /^# The bakery & the oven\nhttp:\/\/127\.0\.0\.1:\d+\/page\/a\n\nThe bakery\n/);
// Without the test option the tool keeps the fence.
await assert.rejects(webTools({ pacer })[1]!.run({ url: web.url("/page/a") }, {}), /private address/);
});