repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/web/__tests__/web-fetch-contract.test.ts

Raw
import { mkdtemp, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestSession, type TestSession } from "../../../test/harness";
import { fetchUrlStream } from "../fetch";
import { filterLineMatches } from "../line-match";
import {
	discoverSiteMap,
	parseLlmsLinks,
	parseRobotsSitemaps,
	parseSitemapXml,
} from "../map";
import {
	assertSafeHttpUrl,
	isPrivateOrReservedIp,
	resolveRedirectUrl,
} from "../safety";
import { platformStateDir, projectStoreDir, saveJsonResult } from "../store";

const originalFetch = globalThis.fetch;

describe("web_fetch context contract", () => {
	let t: TestSession | undefined;
	afterEach(() => {
		globalThis.fetch = originalFetch;
		t?.dispose();
		t = undefined;
	});

	it("stores full output but returns only capped visible text and metadata", async () => {
		globalThis.fetch = vi.fn(
			async () =>
				new Response("x".repeat(50_000), {
					status: 200,
					headers: { "content-type": "text/plain" },
				}),
		) as typeof fetch;

		const webPath = path.resolve(import.meta.dirname, "../index.ts");
		t = await createTestSession({ extensions: [webPath] });
		const [extension] = t.session.extensionRunner.extensions;
		const tool = extension.tools.get("web_fetch").definition;
		const result = await tool.execute(
			"test",
			{ url: "https://93.184.216.34/plain", maxChars: 1_000 },
			new AbortController().signal,
			undefined,
			{ cwd: t.cwd },
		);

		const text = result.content[0].text;
		expect(text.length).toBeLessThan(1_500);
		expect(text).toContain("responseId:");
		expect(result.details.responseId).toBeTypeOf("string");
		expect(result.details.fullOutputPath).toBeTypeOf("string");
		expect(JSON.stringify(result.details)).not.toContain("x".repeat(200));
		const saved = JSON.parse(
			await readFile(result.details.fullOutputPath, "utf8"),
		);
		expect(saved.output).toContain("x".repeat(10_000));
	});

	it("line matching returns excerpts instead of full page", async () => {
		globalThis.fetch = vi.fn(
			async () =>
				new Response(
					["one", "before", "install with mise", "after", "tail"].join("\n"),
					{ status: 200, headers: { "content-type": "text/plain" } },
				),
		) as typeof fetch;

		const webPath = path.resolve(import.meta.dirname, "../index.ts");
		t = await createTestSession({ extensions: [webPath] });
		const [extension] = t.session.extensionRunner.extensions;
		const result = await extension.tools.get("web_fetch").definition.execute(
			"test",
			{
				url: "https://93.184.216.34/plain",
				linesMatching: ["install"],
				contextLines: 1,
			},
			new AbortController().signal,
			undefined,
			{ cwd: t.cwd },
		);

		const text = result.content[0].text;
		expect(text).toContain("2: before");
		expect(text).toContain("3: install with mise");
		expect(text).toContain("4: after");
		expect(text).not.toContain("1: one");
		expect(text).not.toContain("5: tail");
	});
});

describe("web safety/store/map primitives", () => {
	it("blocks unsafe URLs and DNS answers", async () => {
		await expect(assertSafeHttpUrl("file:///etc/passwd")).rejects.toThrow(
			/Only http: and https:/,
		);
		await expect(assertSafeHttpUrl("http://127.0.0.1")).rejects.toThrow(
			/private address/,
		);
		await expect(
			assertSafeHttpUrl("https://public.test", {
				resolver: async () => ["10.0.0.2"],
			}),
		).rejects.toThrow(/blocked private address/);
		await expect(
			resolveRedirectUrl("https://example.com/a", "http://127.0.0.1/b"),
		).rejects.toThrow(/private address/);
		expect(isPrivateOrReservedIp("8.8.8.8")).toBe(false);
	});

	it("fetch validates redirects and max bytes", async () => {
		globalThis.fetch = vi.fn(
			async () =>
				new Response(null, {
					status: 302,
					headers: { location: "http://127.0.0.1/private" },
				}),
		) as typeof fetch;
		await expect(
			fetchUrlStream("https://example.com", undefined, undefined, {
				resolver: async () => ["93.184.216.34"],
			}),
		).rejects.toThrow(/private address/);
		globalThis.fetch = vi.fn(
			async () =>
				new Response("x".repeat(20), {
					status: 200,
					headers: { "content-type": "text/plain" },
				}),
		) as typeof fetch;
		await expect(
			fetchUrlStream("https://example.com", undefined, undefined, {
				maxBytes: 10,
				resolver: async () => ["93.184.216.34"],
			}),
		).rejects.toThrow(/exceeds maxBytes/);
	});

	it("stores full JSON under XDG state dir", async () => {
		const root = await mkdtemp(path.join(tmpdir(), "pi-web-store-"));
		expect(
			platformStateDir("linux", { XDG_STATE_HOME: "/state" }, "/home/me"),
		).toBe("/state/pi");
		expect(
			projectStoreDir("web", "/work/project", {
				platform: "linux",
				env: { XDG_STATE_HOME: "/state" },
				home: "/home/me",
			}),
		).toMatch(/^\/state\/pi\/web\/[a-f0-9]{64}$/);
		const saved = await saveJsonResult(
			"web",
			root,
			{ body: "x".repeat(50_000) },
			{ platform: "linux", env: { XDG_STATE_HOME: root }, home: root },
		);
		expect(
			JSON.parse(await readFile(saved.fullOutputPath, "utf8")).body,
		).toHaveLength(50_000);
		expect(JSON.stringify(saved)).not.toContain("xxxxx");
	});

	it("filters matching lines with context", () => {
		const result = filterLineMatches(
			["a", "before", "Install with mise", "after", "z"].join("\n"),
			{ needles: ["install"], contextLines: 1 },
		);
		expect(result.text).toContain("2: before");
		expect(result.text).toContain("3: Install with mise");
		expect(result.text).toContain("4: after");
		expect(filterLineMatches("huge\nbody", { needles: ["missing"] }).text).toBe(
			"",
		);
	});

	it("maps robots/sitemap/llms without page bodies", async () => {
		expect(
			parseRobotsSitemaps("Sitemap: https://x.test/sitemap.xml\n"),
		).toEqual(["https://x.test/sitemap.xml"]);
		expect(parseSitemapXml("<url><loc>https://x.test/a</loc></url>")).toEqual([
			"https://x.test/a",
		]);
		expect(
			parseLlmsLinks(
				"[Docs](https://x.test/docs) [Rel](/rel)",
				"https://x.test/base",
			),
		).toEqual(["https://x.test/docs", "https://x.test/rel"]);
		const fetched: string[] = [];
		const result = await discoverSiteMap("https://x.test/docs", {
			fetchText: async (url) => {
				fetched.push(url);
				if (url.endsWith("robots.txt"))
					return "Sitemap: https://x.test/sitemap.xml";
				if (url.endsWith("sitemap.xml"))
					return "<url><loc>https://x.test/a</loc></url>";
				if (url.endsWith("llms.txt")) return "[LLM](https://x.test/llm)";
				throw new Error(`unexpected ${url}`);
			},
		});
		expect(fetched).toEqual([
			"https://x.test/robots.txt",
			"https://x.test/sitemap.xml",
			"https://x.test/llms.txt",
		]);
		expect(result.urls.map((x) => x.url)).toEqual([
			"https://x.test/a",
			"https://x.test/llm",
		]);
	});
});