diff --git a/CHANGELOG.md b/CHANGELOG.md index b67627c..4890400 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [0.1.65] - 2026-11-13 + +### Added + +- **R1 safe actions** — element refs now carry stale and sensitive-action guards (a ref from an outdated snapshot or pointing at a sensitive control is refused instead of clicking the wrong element); new `browser_find` tool; `browser_snapshot` accepts `within` to scope the tree to a subtree. +- **R2 docs-native reading** — new `browser_map` tool (site map from sitemap/llms files, cross-origin `` dropped as `offOrigin`, robots-disallowed files not fetched unless advertised by `Sitemap:`); `browser_fetch` `focus`/`topK` return the most relevant BM25-ranked passages; site-served markdown is preferred when available. +- **R3 token diet** — output budget via `maxTokens`/`offset` with `nextOffset` for continuation, `outputMode: "file"` to offload large results to disk, MCP tool annotations on every tool, and presets. +- **R4 proof of UI change** — new `browser_verify` tool: expect assertions, evidence capture and a receipt. +- **Blocked-page verdict** — `browser_navigate` and extraction tools report a session `blocked` verdict instead of returning a challenge page as content. +- Tool count: 51 → 54 (`browser_find`, `browser_map`, `browser_verify`). + +### Changed (default behaviour) + +- `browser_snapshot` output now adds `generation`, `truncated` and `dropped`. +- `browser_fetch` prefers site-served markdown (`Accept: text/markdown`, `Link rel=alternate`) and reports which one it used in `source`. + ## [0.1.64] - 2026-07-20 ### Fixed diff --git a/README.md b/README.md index 48fa3d1..090a36a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Shadow DOM + iframes), multi-step plans, structured extraction, visual diff, and guardrails** for payments and bookings. It drives real Chromium, so it reads **Next.js / SPA** pages after hydration — not just static HTML. -> 51 MCP tools · stealth + rotating proxies · HTTP fast-path (single, batch & crawl) · full-site content + screenshot snapshots · structured per-card product extraction · form fill + file upload · encrypted credential vault + TOTP (fill-by-reference, origin-bound, never exposed to the LLM) · hover + drag&drop · PDF export · cookies / permissions · network mocking · clipboard · virtualized-list scraping + autoscroll · tabs / dialogs / downloads · console + network logs · MCP screenshot resources · `FUSE_CAPS` tool-group filtering · named auth profiles (cookies + localStorage + IndexedDB, saved at login) · `blockResources` · HAR record/replay · pixel visual-diff · human handoff + live view · typed structured output (`outputSchema` + `structuredContent`). +> 54 MCP tools · stealth + rotating proxies · HTTP fast-path (single, batch & crawl) · full-site content + screenshot snapshots · structured per-card product extraction · form fill + file upload · encrypted credential vault + TOTP (fill-by-reference, origin-bound, never exposed to the LLM) · hover + drag&drop · PDF export · cookies / permissions · network mocking · clipboard · virtualized-list scraping + autoscroll · tabs / dialogs / downloads · console + network logs · MCP screenshot resources · `FUSE_CAPS` / `FUSE_PRESET` (`docs`/`qa`) tool filtering · tool annotations · output budget (`maxTokens`, `outputMode:"file"`) · named auth profiles (cookies + localStorage + IndexedDB, saved at login) · `blockResources` · HAR record/replay · pixel visual-diff · human handoff + live view · typed structured output (`outputSchema` + `structuredContent`). ## Install diff --git a/bun.lock b/bun.lock index ba1afcd..d4c9b82 100644 --- a/bun.lock +++ b/bun.lock @@ -14,6 +14,7 @@ "patchright": "^1.61.1", "pixelmatch": "^7.2.0", "playwright": "^1.61.1", + "unpdf": "^1.9.1", "zod": "^4.4.3", }, "devDependencies": { @@ -401,6 +402,8 @@ "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], + "unpdf": ["unpdf@1.9.1", "", { "peerDependencies": { "@napi-rs/canvas": "^0.1.69 || ^1.0.0" }, "optionalPeers": ["@napi-rs/canvas"] }, "sha512-nO1npM2kNyd4hj1fKzUVU6bvnWjDSxI97eycM/DgzI83dYyW+pNRI9NeMQVEfef8fI3Q06i9lkMeE1HxrQqKoA=="], + "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], diff --git a/docs/README.md b/docs/README.md index 4bcbec7..b6b1b54 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,7 +7,7 @@ New here? Start with the root [README](../README.md), then dive in: | --- | --- | | [Installation](./installation.md) | Requirements, install, Chromium, MCP registration, the three ways to get a browser | | [CLI](./cli.md) | `probe` / `fetch` / `fetch-batch` / `crawl` / `collect-batch` / `shots` / `shots-batch` / `site-shots` / `serp-batch` + one-shot page commands (`run` / `products` / `extract` / `snapshot` / `screenshot` / `inspect`) + every flag | -| [MCP tools](./mcp-tools.md) | All 51 tools with parameters and examples | +| [MCP tools](./mcp-tools.md) | All 54 tools with parameters and examples | | [Configuration](./configuration.md) | `AgentOptions`, `FUSE_*` env vars, identity, retry, output location | | [Sessions](./sessions.md) | Session lifecycle, auto crash recovery, `storageState` auto-save, HAR record/replay, CDP attach | | [Extraction](./extraction.md) | `browser_extract` / `extract_schema` / `collect` + the clean→validate→dedupe→emit pipeline | diff --git a/docs/anti-bot.md b/docs/anti-bot.md index 2606fca..061ef59 100644 --- a/docs/anti-bot.md +++ b/docs/anti-bot.md @@ -97,6 +97,19 @@ accepts an optional `proxyUrl`. a real DOM. - **Fallback:** for anything in the "does not pass" list, use `browser_probe` (full stealth browser). +- **A block is reported, not passed off as a page.** When the response is a + challenge interstitial (Cloudflare, DataDome, AWS WAF), `browser_fetch` / + `browser_fetch_batch` / `browser_crawl` return `blocked: true`, `blockedBy` + and a `hint` instead of an ordinary-looking result. This is detection and + routing only — nothing is solved or evaded: next step is `browserFallback: + true` (or `FUSE_FETCH_ESCALATE_BLOCKED=1` server-side), then a session + (`browser_open` → `browser_navigate` → `browser_extract`), then + `browser_handoff` when the live page shows a human step (CAPTCHA / + Turnstile). Whether a real browser passes a given challenge depends on the + site and on the client's reputation at that moment — see + [blocked-fast-path-live-check-2026-11-11.md](./blocked-fast-path-live-check-2026-11-11.md). + Signals and combination rules: `src/net/block-signals.ts`, + `src/net/block-detect.ts`. ## Captcha solver (opt-in — authorized testing only) diff --git a/docs/blocked-fast-path-live-check-2026-11-11.md b/docs/blocked-fast-path-live-check-2026-11-11.md new file mode 100644 index 0000000..8248b5a --- /dev/null +++ b/docs/blocked-fast-path-live-check-2026-11-11.md @@ -0,0 +1,81 @@ +# Blocked fast-path responses — live check, 2026-11-11 + +Build under test: the **worktree** (branch `claude/competitive-analysis-blocked-fetch-ec1ef9`, base 0.1.64 + the +blocked-response fix), driven through the real MCP tools of `createServer()` over an in-memory client — not the +installed MCP server. Target: `https://ai.miraheze.org/wiki/Agnostic_AI` (Cloudflare managed challenge for plain +HTTP clients). Negative control: `https://example.com/`. Every browser session opened by the script was closed +(`browser_close`; no leftover browser process afterwards). No CAPTCHA was solved and none of the `captcha` / +`solveCaptcha` options were used. + +## Results + +| # | Time (UTC) | Tool + exact params | status | `blocked` | `blockedBy` | `hint` | wordCount / bytes | `escalated` | +|---|---|---|---|---|---|---|---|---| +| a | 14:41:52Z | `browser_fetch {url}` | 403 | **true** | `cloudflare` | "Blocked by an anti-bot interstitial (cloudflare) — this is not the page content. Retry with browserFallback:true, or read it in a session: browser_open → browser_navigate → browser_extract (if the default session is also challenged, use browser_open {headless:false, engine:"playwright", channel:"chrome"}); if the live page shows a human step (CAPTCHA/turnstile), call browser_handoff." | 0 / 224 | false | +| b | 14:41:52Z (render ≈ 6 s) | `browser_fetch {url, browserFallback:true}` | 403 (fast-path status) | **true** | `cloudflare` | "Still blocked after a real-browser render (cloudflare). Read it in a session: browser_open {headless:false, engine:"playwright", channel:"chrome"} → browser_navigate → browser_extract; if the live page shows a human step (CAPTCHA/turnstile), call browser_handoff so a person completes it." | 9 / 278 (title "Un instant…") | true | +| c | 14:45:05Z (first run 14:42:04Z, same outcome) | `browser_open {}` → `browser_navigate {sessionId, url, waitMs:8000}` → `browser_extract {kind:"text"}` (+ `kind:"challenges"`) | n/a (navigate returns no status) | true (same detector on `page.content()`) | `cloudflare` | — (session tools carry no `hint`; the fast-path hint above points here) | 33 / 278 (title "Un instant…"); `challenges.turnstile: true` | n/a | +| d | 14:43:56Z (earlier runs 14:42:08Z with no wait and 14:42:32Z with `waitMs:10000`, same outcome) | `browser_open {headless:false, engine:"playwright", channel:"chrome"}` → `browser_navigate {sessionId, url, waitMs:8000}` → `browser_extract {kind:"text"}` (+ `kind:"challenges"`) | n/a | true (same detector on `page.content()`) | `cloudflare` | — | 33 / 278 (title "Un instant…"); `challenges.turnstile: true`; screenshot shows a Cloudflare "Verify you are human" checkbox | n/a | +| e (control) | 14:41:58Z | `browser_fetch {url:"https://example.com/"}` | 200 | not set | not set | not set | 25 / 242 | false | + +Row c and d `blocked` is computed by running the same `detectBlock` on the session's `page.content()`; the session +tools themselves do not return a `blocked` field. + +Rows a–e were measured on the first implementation, before the first challenger review. Rows a′/e′ below were +measured at 15:00Z on the code as of that time (weak-signal quorum 3, 1 MiB scan cap, and a broad "any thin render +inherits the fast-path verdict" rule), NOT on the final code. Three changes came after 15:00Z, from the later +challenger fixes: the HTML markers were tightened to executable context (`_cf_chl_opt = {` assignment, +`src="…captcha-delivery.com…"`); the inheritance rule was narrowed to blocks only response headers can identify +(`isHeaderOnlyBlock`, today AWS WAF); and the `x-datadome` presence header was excluded from the weak quorum +(`presenceOnly`), with the "verify you are human" phrase no longer counted twice. The run on the final code is in +`docs/blocked-fast-path-real-conditions-2026-11-11.md` (written by `e2e-runner`); this document makes no claim +about it. Rows a′ and e′ (no browser, 2 requests, same script as a–e): + +| # | Time (UTC) | Tool + exact params | status | `blocked` | `blockedBy` | `hint` | wordCount / bytes | `escalated` | +|---|---|---|---|---|---|---|---|---| +| a′ | 15:00:03Z | `browser_fetch {url:"https://ai.miraheze.org/wiki/Agnostic_AI"}` | 403 | **true** | `cloudflare` | identical to row a | 0 / 224 | false | +| e′ (control) | 15:00:03Z | `browser_fetch {url:"https://example.com/"}` | 200 | not set | not set | not set | 25 / 242 | false | + +Rows b, c and d were not re-run after the first implementation (they need a browser and more requests to the site). +The captured real responses are replayed against the current code by the unit suite +(`tests/unit/fetch-blocked.test.ts`, `tests/unit/block-detect.test.ts`) — fixtures, not live measurements. + +## Reading the table + +- **Before the fix** row a was `{status:403, title "Checking your connection...", wordCount:0, extraction:"primary", + escalated:false}` — a blocked response returned as an ordinary result. It is now `blocked:true` with a hint (row a). +- **`browserFallback:true` does not turn this particular block into content** (row b): the headless browser + renders the same Cloudflare challenge (French title "Un instant…"), and the result stays `blocked:true` + with `escalated:true` and a hint that points at a headed session and `browser_handoff`. +- **Human step.** In rows c and d the live page shows a Cloudflare Turnstile checkbox (`challenges.turnstile:true` + and the screenshot). It was **not** solved. This is the case where `browser_handoff` is the hint: a person + completes the step in the headed session (`browser_open {headless:false}`), then the agent resumes. +- **Negative control** (row e): a normal public page reports no `blocked` field at all (and the result has exactly + the pre-fix keys). + +## Discrepancy with the earlier manual measurement (not resolved) + +Earlier the same day, a plain headed session (`browser_open {headless:false, engine:"playwright", channel:"chrome"}` +→ `browser_navigate` → `browser_extract`) read this page in full (48.8 KB, no human step). This check did **not** +reproduce that: the same headed-Chrome parameters hit the Turnstile checkbox on every run (three runs, including +one with `waitMs:10000`). Cloudflare decides per request and per client reputation, and this check issued 9 requests +to the site between 14:31Z and 14:46Z (one fixture-capture GET, the fast-path GETs of rows a and b, one headless +render for b, two headless session loads for c, three headed loads for d); the cause of the difference was **not** established and the claim "a headed Chrome session always passes +this challenge" is therefore **not** supported by this evidence. What is supported: the fast path now says +`blocked`, and the routing it recommends (`browserFallback`, then a session, then `browser_handoff` when a human step +shows) is the one that applies in each observed state. + +## Real blocked responses used as fixtures (one plain GET each, 2026-11-11, `tests/fixtures/blocked/`) + +| Fixture | Origin / vendor | Status | Distinguishing signals | +|---|---|---|---| +| `cloudflare-managed-miraheze` | ai.miraheze.org / Cloudflare managed challenge | 403 | `cf-mitigated: challenge`, `window._cf_chl_opt`, title "Checking your connection...", ``, 80 visible chars | +| `cloudflare-security-glassdoor` | glassdoor.com / Cloudflare "Security" page | 403 | `cf-mitigated: challenge`, `_cf_chl_opt`, 555 visible chars (just under the 600 thin threshold) | +| `cloudflare-just-a-moment-stockx` | stockx.com / Cloudflare "Just a moment..." | 403 | `cf-mitigated: challenge`, `_cf_chl_opt`, `challenges.cloudflare.com` | +| `datadome-g2` | g2.com / DataDome | 403 | **no** `cf-mitigated`; `x-datadome: protected`, `captcha-delivery.com` script, 50 visible chars, 1.8 KB | + +Sanitized: cookies, ray ids, client IPs, tokens and inline CSS removed. A fifth shape, AWS WAF +(`x-amzn-waf-action: challenge`, HTTP 202), is **synthetic**, from the AWS WAF developer guide +(`https://docs.aws.amazon.com/waf/latest/developerguide/waf-captcha-and-challenge-actions.html`). The Cloudflare header +contract is from `https://developers.cloudflare.com/cloudflare-challenges/challenge-types/challenge-pages/detect-response/`. +Two control captures from the same pass were NOT blocked and shaped the false-positive rules: `hermes.com` (HTTP 200, +carries `x-datadome: protected`, real content) and `nowsecure.nl` (200, sparse). diff --git a/docs/blocked-fast-path-real-conditions-2026-11-11.md b/docs/blocked-fast-path-real-conditions-2026-11-11.md new file mode 100644 index 0000000..9e6e591 --- /dev/null +++ b/docs/blocked-fast-path-real-conditions-2026-11-11.md @@ -0,0 +1,270 @@ +# Blocked fast path: real-conditions test (built, packed, installed, over stdio) + +Date: 2026-11-11, run 15:22-15:26 UTC. Runner: `e2e-runner`. Subject: the uncommitted "blocked fast path" fix on top of `254644b` (v0.1.64 base). + +Scope: the BUILT, PACKED and INSTALLED package, driven by a real MCP client through a real server process over stdio. Not the in-memory `createServer()` client, not the source tree. Nothing here changes code; every number below comes from a raw JSON file listed at the end. + +## 1. Environment and code state + +| Item | Value | +|---|---| +| OS | macOS 27.2.1 (Darwin 27.2.0), arm64 | +| Node / Bun / npm | v26.13.0 / 1.4.4 / 12.2.2 | +| MCP SDK used by client and by the installed server | `@modelcontextprotocol/sdk` 1.32.2 (`Client`, `StdioClientTransport`; API checked in the installed `.d.ts`) | +| HEAD | `254644bb600f94e33595c77dabe02231753e4d27` | +| Tracked diff hash (`git diff \| shasum -a 256`, taken before the build) | `42257842f24c91843023c7d7393b7a62acee13a08c74b2a04aac14de2b84b8fa` (includes docs that `fastpath-fix` may still edit) | +| Combined tracked+untracked hash | `198b0858ae53d2feb4b919898ce16d35135090fc8d063efbdb1cd1e74c8a5e60` | +| `src/` content hash (all files sorted, sha256 of per-file sha256s) | `581b88104a44e4a726b5eb5cf9de8fd7cbf48cbd30cc8df91d127a8b02954ae0` before the build and again after the run (src did not move during the test) | +| Untracked source files built | `src/interfaces/block.ts`, `src/net/block-detect.ts`, `src/net/block-signals.ts` (per-file sha256 in `code-state.txt`) | +| Build | `bun run build` (= `tsc -p tsconfig.json`), 0.6 s, `dist/` did not exist beforehand, so no stale file can ship. `dist/` is git-ignored (`.gitignore:2`), not tracked. | +| `dist` vs `src` | 297 `.ts` in `src` and 297 `.js` in `dist`, identical name sets (diff empty) | +| Tarball | `fusengine-browser-mcp-0.1.64.tgz`, 399,852 bytes, sha256 `5a019a98ad8ea81fdcb9adbb700c44576931fdc59877e819fd7b011ad9355d9e`, sha1 `6ab285eb8791fc39d8c2a5fab6d6492429ad994e` | +| Tarball content | 1193 files: 1188 under `dist/` (js, d.ts, maps only) + `LICENSE`, `package.json`, `proxies.example.json`, `README.md`, `scripts/postinstall.mjs`. No tests, fixtures, docs, `.env`. Nothing odd. | +| Version collision | the tarball is also `0.1.64`, same as the published package. The two installs are in separate directories; the published one lacks `dist/net/block-detect.js` and `block-signals.js` (proof it is the unfixed code). | + +### Install, like a user + +``` +npm init -y && npm install # fixed (install-fixed/, 3.0 s, 135 packages, 0 vulnerabilities) +npm install-scripts approve @fusengine/browser-mcp && npm rebuild @fusengine/browser-mcp # see finding below (17.1 s) +npm init -y && npm install @fusengine/browser-mcp@0.1.64 # published control (install-pub/, 2.4 s) +``` + +Finding (not caused by the fix): on npm 12.2.2 the package's `postinstall` (`scripts/postinstall.mjs`, downloads Chromium via `patchright install chromium`) is BLOCKED by default ("install scripts blocked because they are not covered by allowScripts"). A user must run `npm install-scripts approve` (or equivalent) and rebuild. After approval it ran in 17 s and added `chromium-1248`, `chromium_headless_shell-1248`, `ffmpeg-1013` to the shared `~/Library/Caches/ms-playwright` (additive; the machine's installed 0.1.64 MCP server and its config were not touched). Without that approval, browser rungs would depend on a Chromium already on the machine. This is a documentation candidate for `docs/installation.md`; it was not investigated further. + +### How the server was launched + +The client script spawns the documented bin through the installed package: `npx --no-install browser-mcp` with `cwd` = the install dir (stdio transport, stderr piped; the documented MCP command is `npx -y @fusengine/browser-mcp`, whose bin is `browser-mcp`). `node install-fixed/node_modules/.bin/browser-mcp --version` prints `0.1.64`. Server `initialize` returned `serverInfo` `fuse-browser 0.1.64`. Default env for the child = the SDK's `getDefaultEnvironment()`; the E1 process additionally had `FUSE_FETCH_ESCALATE_BLOCKED=1`. Server stderr contained only the startup line. + +## 2. Tool surface (`tools/list`, installed fixed package) + +- Tool count: 51 (published 0.1.64: also 51). +- `browser_fetch`, `browser_fetch_batch`, `browser_crawl` present. +- Fixed `outputSchema`: `browser_fetch` top-level declares `blocked`, `blockedBy`, `hint`; `browser_fetch_batch` result items (the first `anyOf` branch) declare `blocked` (`const: true`), `blockedBy`, `hint`, the error branch (`{url,error}`) is separate; `browser_crawl` page items declare `blocked`, `blockedBy`, `hint`, `depth`. +- Published 0.1.64: `browser_fetch` declares none of the three, `browser_crawl` items none. + +## 3. Results + +Expectation key: PASS = matched the brief's expectation; "info" = recorded, no expectation of content. Times are call start, UTC, 2026-11-11. "Fix" = installed tarball above; "Pub" = published 0.1.64. + +| Case | UTC | Tool and exact params | Host | status | blocked / blockedBy | escalated | wordCount | Result | +|---|---|---|---|---|---|---|---|---| +| F1 | 15:22:03 | Fix `browser_fetch {url:"https://ai.miraheze.org/wiki/Agnostic_AI"}` | ai.miraheze.org | 403 | true / cloudflare | false | 0 | PASS (hint present) | +| F4a | 15:22:03 | Fix `browser_fetch {url:"https://example.com/"}` | example.com | 200 | key absent | false | 25 | PASS | +| B1 (as planned) | 15:22:23 | Fix `browser_fetch_batch {urls:["https://stockx.com/","https://example.com/"]}` | stockx.com, example.com | 200, 200 | stockx: key absent (!), example: absent | false, false | 0, 25 | PRECONDITION NOT MET: stockx was not blocked today (see 3.1). Not a test of the blocked path; example.com is a valid normal control. | +| C1 | 15:22:23 | Fix `browser_crawl {url:"https://www.g2.com/", maxPages:1, maxDepth:0}` | www.g2.com | 403 | true / datadome | false | 8 | PASS: `count:1`, seed flagged, `depth:0` | +| F2 | 15:22:24 | Fix `browser_fetch {url:"https://ai.miraheze.org/wiki/Agnostic_AI", browserFallback:true}` | ai.miraheze.org | 403 | true / cloudflare | true | 9 | info: the browser rung ran (11.2 s) and the page stayed blocked (title "Un instant..."); no page content read | +| B1b | 15:23:29 | Fix `browser_fetch_batch {urls:["https://www.glassdoor.com/","https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol"]}` | glassdoor.com, en.wikipedia.org | 403, 200 | glassdoor: true / cloudflare; wiki: absent | false, false | 73, 8239 | PASS: blocked URL is a normal result (not `error`), wiki has no `blocked` key | +| F3 | 15:23:29 | Fix `browser_fetch {url:"https://www.g2.com/"}` | www.g2.com | 403 | true / datadome | false | 8 | PASS (second vendor) | +| F5a | 15:23:29 | Fix `browser_fetch {url:"https://example.com/", browserFallback:true}` | example.com | 200 | key absent | false | 25 | PASS (no escalation on a normal page) | +| C3 | 15:23:50 | Fix `browser_crawl {url:"https://example.com/", maxPages:1, maxDepth:0}` | example.com | 200 | key absent | false | 25 | PASS: `count:1`, no `blocked` | +| F4b | 15:23:50 | Fix `browser_fetch {url:"https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol"}` | en.wikipedia.org | 200 | key absent | false | 8239 | PASS | +| F5b | 15:24:10 | same as F4b with `browserFallback:true` | en.wikipedia.org | 200 | key absent | false | 8239 | PASS | +| B2b | 15:24:10 | Fix `browser_fetch_batch {urls:["https://www.g2.com/","https://stockx.com/"], browserFallback:true}` | www.g2.com, stockx.com | 403, 200 | g2: true / datadome; stockx: absent | true, true | 0, 281 | info: g2 still blocked after render (DataDome captcha-delivery iframe); stockx (an empty-body 200 shell on the fast path) was rendered and its content WAS read (281 words). Neither is an `error`. | +| N1a | 15:24:33 | Pub `browser_fetch {url:"https://ai.miraheze.org/wiki/Agnostic_AI"}` | ai.miraheze.org | 403 | key ABSENT | false | 0 | PASS as negative control: unfixed behaviour (interstitial title "Checking your connection...", no flag) | +| N1b | 15:24:33 | Pub `browser_fetch {url:"https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol"}` | en.wikipedia.org | 200 | absent | false | 8239 | same shape and word count as F4b: normal pages unchanged by the fix | +| E1a | 15:24:41 | Fix + env `FUSE_FETCH_ESCALATE_BLOCKED=1`: `browser_fetch {url:"https://www.glassdoor.com/"}` (no `browserFallback`) | www.glassdoor.com | 403 | true / cloudflare | true | 34 | PASS: escalated by env alone (9.5 s), still blocked | +| E1b | 15:24:54 | same env: `browser_fetch {url:"https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol"}` | en.wikipedia.org | 200 | absent | false | 8239 | PASS: normal page not escalated | +| S1 | 15:25:00 | Fix default session: `browser_open {}` -> `browser_navigate {url:"https://ai.miraheze.org/wiki/Agnostic_AI"}` -> `browser_extract {kind:"text",format:"text"}` and `{kind:"challenges"}` -> `browser_close` | ai.miraheze.org | n/a | n/a | n/a | n/a | info: title "Un instant...", text "Verification reussie. En attente de la reponse de ai.miraheze.org." + "Enable JavaScript and cookies to continue"; challenges `turnstile:true` (others false). Page never reached the wiki content. Closed (`{"closed":true}`). | +| S2 | 15:25:17 | Fix `browser_open {headless:false, engine:"playwright", channel:"chrome"}` -> `browser_navigate {url:"https://www.glassdoor.com/"}` -> `browser_extract` text + challenges -> `browser_close` | www.glassdoor.com | n/a | n/a | n/a | n/a | info: title "Un instant...", Cloudflare "Verification de securite en cours" page, then "Verification reussie. En attente de la reponse de www.glassdoor.com."; challenges `turnstile:true`. A visible window opened for ~35 s; nothing was clicked or typed. | +| H1 | 15:25:33 | same headed session: `browser_handoff {sessionId, reason:"e2e probe...", selector:"[data-test='employer-search-box'], #sc\\.keyword", timeoutMs:20000}` then `browser_close` | www.glassdoor.com | n/a | n/a | n/a | n/a | `{"status":"timeout","url":"https://www.glassdoor.com/"}` after 20.0 s. Nobody was asked to act. The selector was a best guess at a Glassdoor-only element and was not validated against the real page, so the timeout says nothing about the selector. | +| C2 | not run | `browser_crawl` blocked seed + `browserFallback:true` | www.glassdoor.com | | | | | NOT MEASURED (request budget): estimated cost 3 (robots.txt + seed + render) with glassdoor already at 4/5 | +| B2 (as planned) | not run | batch with `[stockx, example]` + fallback | | | | | | NOT MEASURED; replaced by B2b because stockx was not blocked | + +### 3.1 StockX was not blocked today + +Plain `browser_fetch_batch` on `https://stockx.com/` returned HTTP 200, a real `` (title "StockX: Sneakers, Streetwear, ..."), an empty body (`wordCount:0`) and no `blocked` key. That is correct behaviour for the fix (not an interstitial), but the brief's "known blocked" candidate was not blocked for this request, so the originally planned B1/B2 pairs had no blocked member. Blocked members used instead: glassdoor (B1b) and g2 (B2b). + +### 3.2 Full hint strings observed (4 distinct) + +1. cloudflare, fast path, no render (F1, B1b): + `Blocked by an anti-bot interstitial (cloudflare) — this is not the page content. Retry with browserFallback:true, or read it in a session: browser_open → browser_navigate → browser_extract (if the default session is also challenged, use browser_open {headless:false, engine:"playwright", channel:"chrome"}); if the live page shows a human step (CAPTCHA/turnstile), call browser_handoff.` +2. datadome, fast path (F3, C1): + `Blocked by an anti-bot interstitial (datadome) — this is not the page content. Retry with browserFallback:true, or read it in a session: browser_open → browser_navigate → browser_extract (if the default session is also challenged, use browser_open {headless:false, engine:"playwright", channel:"chrome"}); if the live page shows a human step (CAPTCHA/turnstile), call browser_handoff.` +3. still blocked after render, cloudflare (F2, E1a): + `Still blocked after a real-browser render (cloudflare). Read it in a session: browser_open {headless:false, engine:"playwright", channel:"chrome"} → browser_navigate → browser_extract; if the live page shows a human step (CAPTCHA/turnstile), call browser_handoff so a person completes it.` +4. still blocked after render, datadome (B2b): + `Still blocked after a real-browser render (datadome). Read it in a session: browser_open {headless:false, engine:"playwright", channel:"chrome"} → browser_navigate → browser_extract; if the live page shows a human step (CAPTCHA/turnstile), call browser_handoff so a person completes it.` + +Observations on the data (no code was changed or judged): +- `wordCount` is not a reliable block signal: blocked results carried 0, 8, 9, 34 and 73 words while the unfixed N1a also showed 0. The `blocked` flag is the signal. +- The batch call returned `url:"https://www.glassdoor.com/index.htm"` for glassdoor while the single `browser_fetch` (E1a) reported `https://www.glassdoor.com/`. Probably a redirect/normalisation difference between the two paths; not investigated. +- In both sessions (S1, S2) the page showed "Verification reussie. En attente de la reponse..." with `turnstile:true`, i.e. the challenge widget reported success but the site never delivered its content within the ~10 s navigate window. + +## 4. Raw JSON of key cases (long `text` bodies trimmed; full files in section 7) + +F1 (`F1-fixed.json`): +```json +{"status":403,"url":"https://ai.miraheze.org/wiki/Agnostic_AI","format":"markdown","escalated":false, + "text":"---\ntitle: \"Checking your connection...\"\nurl: ...\nsite: \"Miraheze\"...[224 chars]","wordCount":0,"extraction":"primary", + "blocked":true,"blockedBy":"cloudflare","hint":""} +``` + +F2 (`F2-fixed.json`, 11244 ms): +```json +{"status":403,"url":"https://ai.miraheze.org/wiki/Agnostic_AI","format":"markdown","escalated":true, + "text":"---\ntitle: \"Un instant…\"\n...lang: \"fr-fr\"\ndescription: \"Our systems have detected…[297 chars]","wordCount":9,"extraction":"primary", + "blocked":true,"blockedBy":"cloudflare","hint":""} +``` + +B1b (`B1b-fixed.json`, 630 ms): +```json +{"count":2,"results":[ + {"status":403,"url":"https://www.glassdoor.com/index.htm","format":"markdown","escalated":false,"text":"---\ntitle: \"Security | Glassdoor\"...[720 chars]","wordCount":73,"extraction":"primary","blocked":true,"blockedBy":"cloudflare","hint":""}, + {"status":200,"url":"https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol","format":"markdown","escalated":false,"text":"---\ntitle: \"HTTP\"...[20187 chars]","wordCount":8239,"extraction":"primary"}]} +``` + +B2b (`B2b-fixed.json`, 5696 ms): +```json +{"count":2,"results":[ + {"status":403,"url":"https://www.g2.com/","format":"markdown","escalated":true,"text":"---\ntitle: \"g2.com\"..."; + await withClient(async (c, sessionId, page) => { + await page.frameLocator("#fr").locator("button").waitFor({ state: "attached", timeout: 30_000 }); + const ref = await snapRef(c, sessionId, "InFrame"); + assert.ok(ref.includes(":")); + await page.evaluate("document.getElementById('fr').remove()"); + const act = await call(c, "browser_act", { sessionId, kind: "click", ref }); + assert.equal(act.result.ok, false); + assert.equal(act.result.error, "ref_stale"); + }, dataUrl(framed)); +}); + +const ROWS = + "
LOG:
" + + ""; + +test("gate A: a clone inserted before the original never wins the ref, even after an unrelated act walked the page", { timeout: 120_000 }, async () => { + await withClient(async (c, sessionId, page) => { + const snap = await call(c, "browser_snapshot", { sessionId }); + const els = snap.elements as Array>; + const del = els.find((e) => e.text === "Delete")?.ref; + const other = els.find((e) => e.text === "Other")?.ref; + await page.evaluate("(() => { const o = document.querySelector('li'); const k = o.cloneNode(true); k.dataset.n = 'NEW'; o.parentNode.insertBefore(k, o); })()"); + await call(c, "browser_act", { sessionId, kind: "click", ref: other }); + const a2 = await call(c, "browser_act", { sessionId, kind: "click", ref: del }); + const log = await logOf(page); + assert.ok(!log.includes("[NEW]"), `the clone must never be clicked: ${log}`); + assert.ok(a2.result.error === "ref_stale" || log.includes("[X]"), JSON.stringify(a2.result)); + }, dataUrl(ROWS)); +}); + +test("gate B: a ref from another tab that also has a snapshot is refused after switching back", { timeout: 120_000 }, async () => { + await withClient(async (c, sessionId, page) => { + await call(c, "browser_snapshot", { sessionId }); + await call(c, "browser_tabs", { sessionId, action: "new", url: dataUrl("") }); + const sB = await call(c, "browser_snapshot", { sessionId }); + const refB = (sB.elements as Array>).find((e) => e.text === "B-Target")?.ref; + await call(c, "browser_tabs", { sessionId, action: "select", index: 0 }); + const act = await call(c, "browser_act", { sessionId, kind: "click", ref: refB }); + assert.equal(act.result.ok, false); + assert.equal(act.result.error, "ref_stale"); + assert.equal(await logOf(page), "LOG:"); + }); +}); + +test("pass2 #1: tab base is never reused after a close (A,B,C; close B; open D)", { timeout: 120_000 }, async () => { + await withClient(async (c, sessionId) => { + await call(c, "browser_snapshot", { sessionId }); + await call(c, "browser_tabs", { sessionId, action: "new", url: dataUrl("") }); + await call(c, "browser_tabs", { sessionId, action: "new", url: dataUrl("") }); + await call(c, "browser_snapshot", { sessionId }); + await call(c, "browser_tabs", { sessionId, action: "close", index: 1 }); + await call(c, "browser_tabs", { sessionId, action: "new", url: dataUrl("") }); + const sD = await call(c, "browser_snapshot", { sessionId }); + const refD = (sD.elements as Array>)[0]?.ref; + await call(c, "browser_tabs", { sessionId, action: "select", index: 1 }); + const act = await call(c, "browser_act", { sessionId, kind: "click", ref: refD }); + assert.equal(act.result.ok, false); + assert.equal(act.result.error, "ref_stale"); + const tabs = (await call(c, "browser_tabs", { sessionId, action: "list" })).tabs as Array>; + assert.ok(!tabs.some((t) => /CLICKED/.test(t.title)), JSON.stringify(tabs)); + }); +}); + +test("pass2 #1: ids past the tab's namespace are not stamped (truncated, no overflow into another tab)", { timeout: 120_000 }, async () => { + await withClient(async (c, sessionId, page) => { + await page.evaluate("document.documentElement.setAttribute('data-fuse-doc', 'x:9999998')"); + const snap = await call(c, "browser_snapshot", { sessionId }); + assert.equal(snap.count, 2); + assert.equal(snap.truncated, true); + assert.equal(snap.dropped, 2); + }); +}); + +test("pass2 #2: a clone that REPLACES the original (same text, other data) is refused", { timeout: 120_000 }, async () => { + await withClient(async (c, sessionId, page) => { + const snap = await call(c, "browser_snapshot", { sessionId }); + const del = (snap.elements as Array>).find((e) => e.text === "Delete")?.ref; + await page.evaluate("(() => { const o = document.querySelector('li'); const k = o.cloneNode(true); k.dataset.n = 'NEW'; o.replaceWith(k); })()"); + const a = await call(c, "browser_act", { sessionId, kind: "click", ref: del }); + assert.equal(a.result.ok, false); + assert.equal(a.result.error, "ref_stale"); + assert.ok(!(await logOf(page)).includes("[NEW]")); + }, dataUrl(ROWS)); +}); + +test("pass2 #2: a moved original (same node re-appended) stays actionable", { timeout: 120_000 }, async () => { + await withClient(async (c, sessionId, page) => { + const snap = await call(c, "browser_snapshot", { sessionId }); + const del = (snap.elements as Array>).find((e) => e.text === "Delete")?.ref; + await page.evaluate("document.body.appendChild(document.querySelector('li'))"); + assert.equal((await call(c, "browser_act", { sessionId, kind: "click", ref: del })).result.ok, true); + assert.equal(await logOf(page), "LOG: [X]"); + }, dataUrl(ROWS)); +}); + +test("snapshot reports a generation; annotate keeps refs actionable", { timeout: 120_000 }, async () => { + await withClient(async (c, sessionId, page) => { + const s1 = await call(c, "browser_snapshot", { sessionId }); + const s2 = await call(c, "browser_snapshot", { sessionId }); + assert.equal(typeof s1.generation, "number"); + assert.equal(s2.generation, s1.generation + 1); + const save = (s2.elements as Array>).find((e) => e.text === "Save")?.ref; + const act = await call(c, "browser_act", { sessionId, kind: "click", ref: save, annotate: true }); + assert.equal(act.result.ok, true); + assert.equal(await logOf(page), "LOG: [Save]"); + // refs of elements added by an action (diff.added) are usable too + await page.evaluate("document.getElementById('bar').insertAdjacentHTML('beforeend','')"); + const snap = await call(c, "browser_snapshot", { sessionId }); + const n = (snap.elements as Array>).find((e) => e.text === "New")?.ref; + assert.equal((await call(c, "browser_act", { sessionId, kind: "click", ref: n })).result.ok, true); + }); +}); diff --git a/tests/unit/block-detect.test.ts b/tests/unit/block-detect.test.ts new file mode 100644 index 0000000..ce7d921 --- /dev/null +++ b/tests/unit/block-detect.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, test } from "bun:test"; +import type { BlockInput, BlockSignal } from "../../src/interfaces/block.js"; +import { BLOCK_SIGNALS } from "../../src/net/block-signals.js"; +import { MAX_SCAN_CHARS, blockHint, detectBlock, isHeaderOnlyBlock, isThinHtml } from "../../src/net/block-detect.js"; +import { NOT_BLOCKED, REAL_BLOCKED, SYNTHETIC_BLOCKED, article } from "./helpers/block-pages.js"; + +/** Build the detector input a served route would produce on the wire. */ +function inputOf(route: { status: number; headers?: Record; body: string; contentType?: string }): BlockInput { + return { + status: route.status, + headers: route.headers, + html: route.body, + isHtml: (route.contentType ?? "text/html").includes("html"), + }; +} + +describe("detectBlock — blocked pages (real captures + documented shapes)", () => { + for (const [path, { route, vendor }] of Object.entries({ ...REAL_BLOCKED, ...SYNTHETIC_BLOCKED })) { + test(`${path} → ${vendor}`, () => { + expect(detectBlock(inputOf(route))?.vendor).toBe(vendor); + }); + } + + test("each combination works without its vendor header: the HTML marker alone still decides on a thin 403", () => { + const cf = REAL_BLOCKED["/cf-managed"]?.route; + const { "cf-mitigated": _drop, ...headers } = cf?.headers ?? {}; + expect(detectBlock({ status: 403, headers, html: cf?.body ?? "", isHtml: true })?.vendor).toBe("cloudflare"); + const dd = REAL_BLOCKED["/datadome"]?.route; + expect(detectBlock({ status: 403, headers: {}, html: dd?.body ?? "", isHtml: true })?.vendor).toBe("datadome"); + }); + + test("a strong header decides at ANY status (AWS WAF challenge is a 202)", () => { + const aws = SYNTHETIC_BLOCKED["/aws-waf"]?.route; + expect(aws?.status).toBe(202); + expect(detectBlock(inputOf(aws as never))?.signals).toContain("header:x-amzn-waf-action"); + }); + + test("a strong header on a non-HTML body still decides (header-only path)", () => { + expect(detectBlock({ status: 403, headers: { "cf-mitigated": "challenge" }, html: "{}", isHtml: false })?.vendor).toBe("cloudflare"); + }); +}); + +describe("detectBlock — false-positive matrix", () => { + for (const [path, route] of Object.entries(NOT_BLOCKED)) { + test(`${path} (${route.status}) is not blocked`, () => { + expect(detectBlock(inputOf(route))).toBeNull(); + }); + } + + test("header values that are not the documented ones do not match", () => { + const cases: Record[] = [{ "cf-mitigated": "none" }, { "x-amzn-waf-action": "allow" }, { "cf-mitigated": "" }]; + for (const headers of cases) { + expect(detectBlock({ status: 200, headers, html: article("x"), isHtml: true })).toBeNull(); + } + }); + + test("a single weak signal on a thin 403 is not enough", () => { + const html = "Access denied

No.

"; + expect(detectBlock({ status: 403, html, isHtml: true })).toBeNull(); + }); + + test("two weak signals on a 200 (not an error status) are not enough", () => { + const html = 'Just a moment...Please enable JavaScript'; + expect(detectBlock({ status: 200, html, isHtml: true })).toBeNull(); + }); + + test("two weak signals on a long 403 page (real text) are not enough", () => { + const html = article("Access denied", "Please enable JavaScript.").replace("", ''); + expect(detectBlock({ status: 403, html, isHtml: true })).toBeNull(); + }); + + test("two weak signals on a thin 403 are still not enough (the quorum is three)", () => { + const html = 'Just a moment...No.'; + expect(detectBlock({ status: 403, html, isHtml: true })).toBeNull(); + }); + + test("a body over MAX_SCAN_CHARS skips HTML scanning, but a strong header still decides", () => { + const huge = `Just a moment${""); + expect(detectBlock({ status: 403, html: executable, isHtml: true })?.vendor).toBe("cloudflare"); + }); + + test("D2: captcha-delivery.com in a CSP meta (thin 200 shell) is not a block; as a script src it is", () => { + const csp = NOT_BLOCKED["/spa-csp-captcha-delivery"]?.body ?? ""; + expect(detectBlock({ status: 200, html: csp, isHtml: true })).toBeNull(); + const loaded = csp.replace("", ''); + expect(detectBlock({ status: 200, html: loaded, isHtml: true })?.vendor).toBe("datadome"); + }); +}); + +describe("detectBlock — table-driven: a new vendor is one entry", () => { + const acme: BlockSignal = { id: "html:acme-shield", vendor: "acme", kind: "html", strength: "strong", pattern: /acme-shield-challenge/ }; + const page = '
Verifying…
'; + + test("unknown to the default table", () => { + expect(detectBlock({ status: 403, html: page, isHtml: true })).toBeNull(); + }); + + test("detected once the entry is appended", () => { + expect(detectBlock({ status: 403, html: page, isHtml: true }, [...BLOCK_SIGNALS, acme])?.vendor).toBe("acme"); + }); +}); + +describe("blockHint", () => { + test("names real tool + parameter names, never an invented one", () => { + const hint = blockHint({ vendor: "cloudflare", signals: [] }, false); + for (const needle of ["browserFallback:true", "browser_open", "browser_navigate", "browser_extract", "browser_handoff", "headless:false"]) { + expect(hint).toContain(needle); + } + expect(hint).not.toContain("captcha:"); + }); + + test("after a failed browser render it points at a headed session + handoff, not at browserFallback again", () => { + const hint = blockHint({ vendor: "datadome", signals: [] }, true); + expect(hint).toContain("browser_handoff"); + expect(hint).not.toContain("browserFallback"); + }); +}); diff --git a/tests/unit/challenges-aws-evidence.test.ts b/tests/unit/challenges-aws-evidence.test.ts new file mode 100644 index 0000000..82e924c --- /dev/null +++ b/tests/unit/challenges-aws-evidence.test.ts @@ -0,0 +1,87 @@ +/** + * `detectChallenges` on AWS WAF interstitials rendered in the DEFAULT engine + * (patchright, where `page.evaluate` cannot see page globals). Fixtures are + * synthetic, built from AWS's developer guide (see each file's header). + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Page } from "playwright"; +import { resolveConfig } from "../../src/agent/config.js"; +import { detectChallenges } from "../../src/extraction/challenges.js"; +import { SessionManager } from "../../src/session/manager.js"; + +const sessions = new SessionManager(); +let page: Page; +let sessionId = ""; + +beforeAll(async () => { + const s = await sessions.open(resolveConfig({ headless: true, engine: "patchright" })); + page = s.page; + sessionId = s.id; +}, 120_000); +afterAll(async () => { + await sessions.close(sessionId); +}); + +async function detect(html: string, status: number) { + await page.unroute("**/*"); + await page.route("**/*", (r) => + r.request().resourceType() === "document" ? r.fulfill({ status, contentType: "text/html", body: html }) : r.abort(), + ); + await page.goto("https://www.example.com/", { waitUntil: "domcontentloaded" }); + return detectChallenges(page, String(await page.evaluate("document.body ? document.body.innerText : ''"))); +} + +const fixture = (name: string): string => + readFileSync(join(import.meta.dir, "../fixtures/challenges", `${name}.html`), "utf8"); + +/** The integration pattern AWS documents for NORMAL protected pages (waf-js-challenge-api-get-token.html). */ +const NORMAL_SDK_PAGE = + `` + + `
` + + ``; + +describe("AWS WAF interstitials", () => { + test("CAPTCHA (405) -> awsWaf and captcha", async () => { + const c = await detect(fixture("aws-waf-captcha-synthetic"), 405); + expect(c.awsWaf).toBe(true); + expect(c.captcha).toBe(true); + }); + + test("CAPTCHA page whose text also says 'captcha' keeps captcha:true (HEAD behaviour)", async () => { + const html = fixture("aws-waf-captcha-synthetic").replace("

Solve the puzzle

", "

Please solve this CAPTCHA

"); + expect((await detect(html, 405)).captcha).toBe(true); + }); + + test("Challenge (202) -> awsWaf, no captcha", async () => { + const c = await detect(fixture("aws-waf-challenge-synthetic"), 202); + expect(c.awsWaf).toBe(true); + expect(c.captcha).toBe(false); + }); + + test("normal protected page embedding the integration SDK (jsapi.js, getToken/hasToken) -> awsWaf false", async () => { + const c = await detect(NORMAL_SDK_PAGE, 200); + expect(c.awsWaf).toBe(false); + expect(c.captcha).toBe(false); + }); + + test("page rendering a customer-embedded AwsWafCaptcha puzzle -> captcha, but not an awsWaf block", async () => { + const c = await detect( + `
`, + 200, + ); + expect(c.captcha).toBe(true); + expect(c.awsWaf).toBe(false); + }); + + test("article quoting the AWS WAF API names in a
 block -> no flag", async () => {
+    const prose = "The committee reviewed the annual report and discussed the findings at length. ".repeat(12);
+    const c = await detect(
+      `

${prose}

AwsWafCaptcha.renderCaptcha(el, {}); window.awsWafCookieDomainList = [];
`, + 200, + ); + expect(c.awsWaf).toBe(false); + expect(c.captcha).toBe(false); + }); +}); diff --git a/tests/unit/challenges-aws-waf.test.ts b/tests/unit/challenges-aws-waf.test.ts index 522eab2..d1d41f0 100644 --- a/tests/unit/challenges-aws-waf.test.ts +++ b/tests/unit/challenges-aws-waf.test.ts @@ -31,7 +31,9 @@ describe("detectChallenges — awsWaf (additive)", () => { test("existing fields keep working unchanged (regression guardrail)", async () => { const page = makePage("https://example.com/"); const result = await detectChallenges(page, "Please solve the captcha to continue"); - expect(result.captcha).toBe(true); + expect(result.captcha).toBe(false); // a word is not a widget (evidence-based since 2026-11-11) + const withWidget = await detectChallenges(makePage("https://example.com/", { ...noFlags, recaptcha: true }), ""); + expect(withWidget.captcha).toBe(true); expect(result.awsWaf).toBe(false); }); }); diff --git a/tests/unit/challenges-evidence.test.ts b/tests/unit/challenges-evidence.test.ts new file mode 100644 index 0000000..8782523 --- /dev/null +++ b/tests/unit/challenges-evidence.test.ts @@ -0,0 +1,176 @@ +/** + * `detectChallenges` on real rendered pages (real Chromium, no network): flags + * must fire on challenge evidence, not on a word in content. + * False-positive matrix: prose naming Cloudflare/Turnstile/hCaptcha, a "Sign in" + * nav link, a real Google results page. True-positive matrix: real captured + * blocked pages, a Turnstile widget, an hCaptcha widget, login walls. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Page } from "playwright"; +import { resolveConfig } from "../../src/agent/config.js"; +import { detectChallenges } from "../../src/extraction/challenges.js"; +import { SessionManager } from "../../src/session/manager.js"; +import type { Challenges } from "../../src/interfaces/extraction.js"; + +const FIX = join(import.meta.dir, "../fixtures"); +const sessions = new SessionManager(); +let page: Page; +let sessionId = ""; + +beforeAll(async () => { + const s = await sessions.open(resolveConfig({ headless: true, engine: "patchright" })); + page = s.page; + sessionId = s.id; +}, 120_000); +afterAll(async () => { + await sessions.close(sessionId); +}); + +/** Render `html` as the document of `url` (sub-resources aborted) and run the detector on it. */ +async function detect(html: string, url = "https://www.example.com/page", status = 200): Promise { + await page.unroute("**/*"); + await page.route("**/*", (route) => + route.request().resourceType() === "document" + ? route.fulfill({ status, contentType: "text/html; charset=utf-8", body: html }) + : route.abort(), + ); + await page.goto(url, { waitUntil: "domcontentloaded" }); + const text = await page.evaluate("document.body ? document.body.innerText : ''"); + return detectChallenges(page, String(text)); +} + +const PROSE = "The committee reviewed the annual report and discussed the findings at length. ".repeat(12); +const captured = (name: string): { html: string; status: number } => + JSON.parse(readFileSync(join(FIX, "blocked", `${name}.json`), "utf8")); +const googleResults = readFileSync(join(FIX, "serp/google-results-2026-11-11.html"), "utf8"); + +describe("false positives: a word in content is not a challenge", () => { + test("article that discusses Cloudflare, Turnstile and hCaptcha", async () => { + const c = await detect( + `

${PROSE}

Cloudflare shipped Turnstile, an alternative to hCaptcha, last year.

`, + ); + expect(c.cloudflare).toBe(false); + expect(c.turnstile).toBe(false); + expect(c.hcaptcha).toBe(false); + }); + + test("article quoting the Cloudflare challenge snippet in a
 block", async () => {
+    const c = await detect(`

${PROSE}

window._cf_chl_opt = {cvId: '3'};
`); + expect(c.cloudflare).toBe(false); + }); + + test("prose naming captcha vendors and 'I'm not a robot' sets no captcha flag", async () => { + const c = await detect( + `

${PROSE}

reCAPTCHA, hCaptcha, FunCaptcha and a captcha image: click "I'm not a robot".

`, + ); + expect(c.captcha).toBe(false); + expect(c.hcaptcha).toBe(false); + }); + + test("a
with an unrelated image and a text input is not a captcha form", async () => { + const c = await detect(`logo
`); + expect(c.captcha).toBe(false); + }); + + test("long article quoting 'Error 1020' and 'Ray ID' in prose", async () => { + const c = await detect( + `

${PROSE}

Visitors who see Error 1020: Access denied should note the Ray ID and contact the site owner.

`, + ); + expect(c.cloudflare).toBe(false); + }); + + test("short page mentioning only 'Ray ID' (no Cloudflare error code) or only an error code", async () => { + expect((await detect(`

Ray ID is a tracing concept.

`)).cloudflare).toBe(false); + expect((await detect(`

Error 1020

Invalid part number.

`)).cloudflare).toBe(false); + }); + + test("page with a 'Sign in' / 'Log in' nav link is not a login wall", async () => { + const c = await detect( + `

${PROSE}

`, + ); + expect(c.login).toBe(false); + }); + + test("real Google results page (Sign in link, results naming Cloudflare)", async () => { + const withMention = googleResults.replace("", "

Cloudflare Turnstile hCaptcha announcement

"); + const c = await detect(withMention, "https://www.google.com/search?q=x&hl=en"); + expect(c.cloudflare).toBe(false); + expect(c.turnstile).toBe(false); + expect(c.hcaptcha).toBe(false); + expect(c.login).toBe(false); + }); +}); + +describe("true positives: challenge evidence", () => { + for (const name of ["cloudflare-just-a-moment-stockx", "cloudflare-managed-miraheze", "cloudflare-security-glassdoor"]) { + test(`real captured Cloudflare page ${name} -> cloudflare`, async () => { + const f = captured(name); + expect((await detect(f.html, "https://www.example.com/", f.status)).cloudflare).toBe(true); + }); + } + + for (const name of ["cloudflare-error-1020-synthetic", "cloudflare-error-1015-synthetic"]) { + test(`Cloudflare hard-block error page ${name} (no _cf_chl_opt) -> cloudflare`, async () => { + const html = readFileSync(join(FIX, "challenges", `${name}.html`), "utf8"); + expect((await detect(html, "https://www.example.com/", 403)).cloudflare).toBe(true); + }); + } + + test("real captured DataDome page is not reported as Cloudflare", async () => { + const f = captured("datadome-g2"); + expect((await detect(f.html, "https://www.example.com/", f.status)).cloudflare).toBe(false); + }); + + const CAPTCHA_WIDGETS: Record = { + "reCAPTCHA v2 widget": `
`, + "reCAPTCHA iframe": ``, + "Arkose / FunCaptcha iframe": ``, + "DataDome captcha-delivery iframe": ``, + "generic form with captcha image and text input": `
code
`, + }; + for (const [label, markup] of Object.entries(CAPTCHA_WIDGETS)) { + test(`${label} -> captcha`, async () => { + expect((await detect(`${markup}`)).captcha).toBe(true); + }); + } + + test("real captured DataDome block page -> captcha", async () => { + const f = captured("datadome-g2"); + expect((await detect(f.html, "https://www.example.com/", f.status)).captcha).toBe(true); + }); + + test("a Turnstile widget -> turnstile", async () => { + const c = await detect( + `

${PROSE}

`, + ); + expect(c.turnstile).toBe(true); + }); + + test("an hCaptcha widget -> hcaptcha and captcha", async () => { + const c = await detect(`
`); + expect(c.hcaptcha).toBe(true); + expect(c.captcha).toBe(true); + }); + + test("password field -> login", async () => { + expect((await detect(`
`)).login).toBe(true); + }); + + test("login wall wording without a password field (SSO) -> login", async () => { + const c = await detect(`

Please sign in to continue

`); + expect(c.login).toBe(true); + }); + + test("username-first SSO step (heading and subtitle on separate lines, no password field)", async () => { + const gmail = await detect(`

Sign in

to continue to Gmail
`); + expect(gmail.login).toBe(true); + const user = await detect(`

Sign In

`); + expect(user.login).toBe(true); + }); + + test("the sparse login fixture -> login", async () => { + expect((await detect(readFileSync(join(FIX, "sparse-login.html"), "utf8"))).login).toBe(true); + }); +}); diff --git a/tests/unit/fetch-blocked-escalation.test.ts b/tests/unit/fetch-blocked-escalation.test.ts new file mode 100644 index 0000000..9e52dc6 --- /dev/null +++ b/tests/unit/fetch-blocked-escalation.test.ts @@ -0,0 +1,116 @@ +import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; +import { fetchAndRender } from "../../src/agent/fetch-orchestrate.js"; +import type { BrowserProbe } from "../../src/interfaces/block.js"; +import { NOT_BLOCKED, REAL_BLOCKED, SYNTHETIC_BLOCKED, article } from "./helpers/block-pages.js"; +import { type FixtureServer, loadHtml, serveFixtures } from "./helpers/fixture-server.js"; + +// Escalation semantics through the public entry point (`fetchAndRender`), with the +// browser replaced by an injected probe so no real browser launches. + +let server: FixtureServer; +beforeAll(() => { + server = serveFixtures({ + "/cf-managed": REAL_BLOCKED["/cf-managed"]?.route as never, + "/datadome": REAL_BLOCKED["/datadome"]?.route as never, + "/aws-waf": SYNTHETIC_BLOCKED["/aws-waf"]?.route as never, + "/spa-shell": NOT_BLOCKED["/spa-shell"] as never, + "/article": NOT_BLOCKED["/article"] as never, + }); +}); +afterAll(() => server.stop()); +afterEach(() => { + delete process.env.FUSE_FETCH_ESCALATE_BLOCKED; +}); + +/** Wrap a probe so every URL it is asked to render is recorded in `calls`. */ +function recording(calls: string[], inner: BrowserProbe): BrowserProbe { + return async (url, proxyUrl) => { + calls.push(url); + return inner(url, proxyUrl); + }; +} + +const clean: BrowserProbe = async (url) => ({ url, html: article("Real page"), text: "Real page" }); +const stillBlocked: BrowserProbe = async (url) => ({ + url, + html: REAL_BLOCKED["/cf-managed"]?.route.body ?? "", + text: "Checking your connection", +}); + +describe("escalation — opt-in via browserFallback (or FUSE_FETCH_ESCALATE_BLOCKED=1)", () => { + test("default: a blocked response never launches a browser", async () => { + const calls: string[] = []; + const { rendered } = await fetchAndRender(`${server.origin}/cf-managed`, { probe: recording(calls, clean) }); + expect(calls).toEqual([]); + expect(rendered.blocked).toBe(true); + expect(rendered.escalated).toBe(false); + }); + + test("browserFallback:true + browser gets the real page → escalated, not blocked", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/cf-managed`, { browserFallback: true, probe: clean }); + expect(rendered.escalated).toBe(true); + expect(rendered.blocked).toBeUndefined(); + expect(rendered.hint).toBeUndefined(); + expect(rendered.text).toContain("committee reviewed"); + }); + + test("browserFallback:true + browser is blocked too → blocked:true, escalated:true, handoff hint", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/cf-managed`, { browserFallback: true, probe: stillBlocked }); + expect(rendered.escalated).toBe(true); + expect(rendered.blocked).toBe(true); + expect(rendered.hint).toContain("browser_handoff"); + expect(rendered.hint).toContain("browser_open"); + }); + + test("FUSE_FETCH_ESCALATE_BLOCKED=1 escalates a block without browserFallback", async () => { + process.env.FUSE_FETCH_ESCALATE_BLOCKED = "1"; + const calls: string[] = []; + const { rendered } = await fetchAndRender(`${server.origin}/datadome`, { probe: recording(calls, clean) }); + expect(calls).toHaveLength(1); + expect(rendered.escalated).toBe(true); + expect(rendered.blocked).toBeUndefined(); + }); + + test("FUSE_FETCH_ESCALATE_BLOCKED=1 does NOT turn on SPA-shell escalation or touch normal pages", async () => { + process.env.FUSE_FETCH_ESCALATE_BLOCKED = "1"; + const calls: string[] = []; + const probe = recording(calls, clean); + await fetchAndRender(`${server.origin}/spa-shell`, { probe }); + await fetchAndRender(`${server.origin}/article`, { probe }); + expect(calls).toEqual([]); + }); +}); + +describe("after escalation — which verdict survives the render", () => { + test("header-only block (AWS WAF): a render as thin as an interstitial inherits blocked; a real page does not", async () => { + const thin: BrowserProbe = async (url) => ({ url, html: "Verifying…", text: "Verifying…" }); + const stuck = await fetchAndRender(`${server.origin}/aws-waf`, { browserFallback: true, probe: thin }); + expect(stuck.rendered.escalated).toBe(true); + expect(stuck.rendered.blocked).toBe(true); + expect(stuck.rendered.blockedBy).toBe("aws-waf"); + const passed = await fetchAndRender(`${server.origin}/aws-waf`, { browserFallback: true, probe: clean }); + expect(passed.rendered.escalated).toBe(true); + expect(passed.rendered.blocked).toBeUndefined(); + }); + + test("A(i): Cloudflare-blocked fast path + a genuinely short page rendered fine → NOT blocked, content returned", async () => { + const login: BrowserProbe = async (url) => ({ url, html: loadHtml("sparse-login.html"), text: "Sign in" }); + const { rendered } = await fetchAndRender(`${server.origin}/cf-managed`, { browserFallback: true, probe: login }); + expect(rendered.escalated).toBe(true); + expect(rendered.blocked).toBeUndefined(); + expect(rendered.hint).toBeUndefined(); + expect(rendered.text.length).toBeGreaterThan(0); + }); + + test("A(iii): Cloudflare-blocked + a thin render that still carries the challenge marker → blocked", async () => { + const challenged: BrowserProbe = async (url) => ({ + url, + html: "Checking…", + text: "Checking…", + }); + const { rendered } = await fetchAndRender(`${server.origin}/cf-managed`, { browserFallback: true, probe: challenged }); + expect(rendered.escalated).toBe(true); + expect(rendered.blocked).toBe(true); + expect(rendered.blockedBy).toBe("cloudflare"); + }); +}); diff --git a/tests/unit/fetch-blocked.test.ts b/tests/unit/fetch-blocked.test.ts new file mode 100644 index 0000000..da2ebfc --- /dev/null +++ b/tests/unit/fetch-blocked.test.ts @@ -0,0 +1,127 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { crawl } from "../../src/agent/crawl.js"; +import { fetchBatch } from "../../src/agent/fetch-batch.js"; +import { fetchAndRender } from "../../src/agent/fetch-orchestrate.js"; +import type { BrowserProbe } from "../../src/interfaces/block.js"; +import { NOT_BLOCKED, REAL_BLOCKED, SYNTHETIC_BLOCKED, article } from "./helpers/block-pages.js"; +import { type FixtureRoute, type FixtureServer, serveFixtures } from "./helpers/fixture-server.js"; + +// Public-entry-point tests: the REAL fast path (impit → fetchFast → resolve → +// render) runs against a local server replaying real response headers + bodies. +// Today (0.1.64) a Cloudflare/DataDome interstitial comes back as an ordinary +// result: status 403, wordCount 0 or a few chrome words, escalated:false and +// nothing an agent can branch on. Escalation semantics: fetch-blocked-escalation.test.ts. + +const ALL_BLOCKED = { ...REAL_BLOCKED, ...SYNTHETIC_BLOCKED }; +const routes: Record = { ...NOT_BLOCKED }; +for (const [path, b] of Object.entries(ALL_BLOCKED)) routes[path] = b.route; + +// Crawl fixtures: a blocked seed and a normal hub, both linking to same-origin trap pages. +const TRAP_LINKS = 'one two'; +routes["/blocked-with-links"] = { + status: 403, + headers: { "cf-mitigated": "challenge" }, + body: `Just a moment...

Checking your browser

${TRAP_LINKS}`, +}; +routes["/hub"] = { status: 200, body: article("Hub", TRAP_LINKS) }; +routes["/trap-1"] = { status: 200, body: article("Trap one") }; +routes["/trap-2"] = { status: 200, body: article("Trap two") }; + +let server: FixtureServer; +beforeAll(() => { + server = serveFixtures(routes); +}); +afterAll(() => server.stop()); + +/** Thin shells that `browserFallback` may legitimately escalate (SPA path, not the block path). */ +const SPA_SHELLS = new Set(["/spa-shell", "/spa-csp-captcha-delivery"]); + +const MARKDOWN_KEYS = ["escalated", "extraction", "format", "status", "text", "url", "wordCount"]; +const TEXT_KEYS = ["escalated", "format", "status", "text", "url"]; + +describe("browser_fetch pipeline — a blocked interstitial is reported as blocked", () => { + for (const [path, { route, vendor }] of Object.entries(ALL_BLOCKED)) { + test(`${path}: blocked:true, blockedBy:${vendor}, hint names the next tools`, async () => { + const { rendered } = await fetchAndRender(`${server.origin}${path}`); + expect(rendered.blocked).toBe(true); + expect(rendered.blockedBy).toBe(vendor); + expect(rendered.status).toBe(route.status); + expect(rendered.escalated).toBe(false); + const hint = rendered.hint ?? ""; + for (const needle of ["browserFallback", "browser_open", "browser_navigate", "browser_extract", "browser_handoff"]) { + expect(hint).toContain(needle); + } + }); + } + + test("the owner's case: a 403 with zero extracted words is no longer a normal result", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/cf-managed`); + expect(rendered.status).toBe(403); + expect(rendered.wordCount).toBe(0); + expect(rendered.blocked).toBe(true); + }); +}); + +describe("false-positive matrix — these keep TODAY's exact result shape", () => { + for (const [path, route] of Object.entries(NOT_BLOCKED)) { + test(`${path} (${route.status}): no blocked/blockedBy/hint key at all`, async () => { + const probes: string[] = []; + const probe: BrowserProbe = async (url) => { + probes.push(url); + return { url, html: article("x"), text: "x" }; + }; + const { rendered } = await fetchAndRender(`${server.origin}${path}`, { browserFallback: true, probe }); + const isJson = route.contentType === "application/json"; + expect(Object.keys(rendered).sort()).toEqual(isJson ? TEXT_KEYS : MARKDOWN_KEYS); + expect(rendered.status).toBe(route.status); + // browserFallback may legitimately escalate an SPA shell, never anything else. + if (!SPA_SHELLS.has(path)) expect(probes).toEqual([]); + }); + } + + test("D2 through the public entry point, no browserFallback: a CSP mention of the DataDome host is not a block", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/spa-csp-captcha-delivery`); + expect(rendered.status).toBe(200); + expect(rendered.blocked).toBeUndefined(); + }); + + test("sparse page keeps its clean extraction (login stays primary)", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/login`); + expect(rendered.extraction).toBe("primary"); + expect(rendered.blocked).toBeUndefined(); + }); +}); + +describe("fetch_batch and crawl share the same detection", () => { + test("fetchBatch: per-URL blocked flag, normal URL untouched", async () => { + const items = await fetchBatch([`${server.origin}/datadome`, `${server.origin}/article`]); + const [bad, good] = items; + expect(bad && "blocked" in bad && bad.blocked).toBe(true); + expect(good && !("blocked" in good)).toBe(true); + expect(good && !("error" in good) && Object.keys(good).sort()).toEqual(MARKDOWN_KEYS); + }); + + test("crawl: a blocked seed is flagged", async () => { + const out = await crawl(`${server.origin}/cf-managed`, { respectRobots: false, throttleMs: 0, maxDepth: 1 }); + expect(out.count).toBe(1); + expect(out.pages[0]?.blocked).toBe(true); + expect(out.pages[0]?.hint).toContain("browser_open"); + }); + + test("crawl: links found on a BLOCKED page are never requested; the same links on a normal page are", async () => { + const blocked = await crawl(`${server.origin}/blocked-with-links`, { respectRobots: false, throttleMs: 0, maxDepth: 1 }); + expect(blocked.count).toBe(1); + expect(blocked.pages[0]?.blocked).toBe(true); + expect(server.hits.get("/trap-1")).toBeUndefined(); + expect(server.hits.get("/trap-2")).toBeUndefined(); + // Control: proves the harness would see a visit. + const normal = await crawl(`${server.origin}/hub`, { respectRobots: false, throttleMs: 0, maxDepth: 1 }); + expect(normal.count).toBe(3); + expect(server.hits.get("/trap-1")).toBe(1); + }); + + test("crawl: a normal page keeps today's exact page shape", async () => { + const out = await crawl(`${server.origin}/article`, { respectRobots: false, throttleMs: 0, maxDepth: 0 }); + expect(Object.keys(out.pages[0] ?? {}).sort()).toEqual([...MARKDOWN_KEYS, "depth"].sort()); + }); +}); diff --git a/tests/unit/fetch-budget-wiring.test.ts b/tests/unit/fetch-budget-wiring.test.ts new file mode 100644 index 0000000..8c125fd --- /dev/null +++ b/tests/unit/fetch-budget-wiring.test.ts @@ -0,0 +1,58 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { registerCrawlTool } from "../../src/server/tools/crawl.js"; +import { registerFetchTool } from "../../src/server/tools/fetch.js"; +import { registerFetchBatchTool } from "../../src/server/tools/fetch-batch.js"; +import { article } from "./helpers/block-pages.js"; +import { type DocServer, serveDocs } from "./helpers/docs-server.js"; +import { callTool } from "./helpers/tool-client.js"; + +// The token-budget helper (`maxTokens`/`offset`, owned by token-diet) is wired into +// the three big-output fast-path tools. Defaults stay off: no budget param = unchanged output. + +let server: DocServer; +beforeAll(() => { + const link = (p: string) => `${p}`; + server = serveDocs({ + "/a": { body: article("Page A", [1, 2, 3].map((i) => link(`/p${i}`)).join(" ")) }, + "/p1": { body: article("P1") }, + "/p2": { body: article("P2") }, + "/p3": { body: article("P3") }, + }); +}); +afterAll(() => server.stop()); + +describe("budget wiring on fetch / fetch_batch / crawl", () => { + test("browser_fetch: maxTokens cuts `text` and says where to resume; resuming at nextOffset continues", async () => { + const url = `${server.origin}/a`; + const full = await callTool(registerFetchTool, "browser_fetch", { url }); + const cut = await callTool(registerFetchTool, "browser_fetch", { url, maxTokens: 60 }); + expect(cut.isError).toBe(false); + expect(typeof cut.out.nextOffset).toBe("number"); // the budget signals a cut with `nextOffset` only… + expect(cut.out.truncated).toBeUndefined(); // …`truncated` belongs to the tool (the fetch family has none) + expect(cut.out.text.length).toBeLessThan(full.out.text.length); + const rest = await callTool(registerFetchTool, "browser_fetch", { url, maxTokens: 60, offset: cut.out.nextOffset }); + expect(`${cut.out.text}${rest.out.text}`.startsWith(full.out.text.slice(0, 40))).toBe(true); + expect(full.out.nextOffset).toBeUndefined(); // no budget → no budget keys, byte-identical default + expect(full.out.truncated).toBeUndefined(); + }); + + test("browser_fetch_batch: maxTokens pages the results array by item", async () => { + const urls = [1, 2, 3].map((i) => `${server.origin}/p${i}`); + const full = await callTool(registerFetchBatchTool, "browser_fetch_batch", { urls }); + const cut = await callTool(registerFetchBatchTool, "browser_fetch_batch", { urls, maxTokens: 150 }); + expect(full.out.results).toHaveLength(3); + expect(typeof cut.out.nextOffset).toBe("number"); + expect(cut.out.truncated).toBeUndefined(); + expect(cut.out.results.length).toBeLessThan(3); + }); + + test("browser_crawl: maxTokens pages the pages array by item", async () => { + const args = { url: `${server.origin}/a`, maxDepth: 1, respectRobots: false, throttleMs: 0 }; + const full = await callTool(registerCrawlTool, "browser_crawl", args); + const cut = await callTool(registerCrawlTool, "browser_crawl", { ...args, maxTokens: 150 }); + expect(full.out.pages.length).toBeGreaterThanOrEqual(3); + expect(typeof cut.out.nextOffset).toBe("number"); + expect(cut.out.truncated).toBeUndefined(); + expect(cut.out.pages.length).toBeLessThan(full.out.pages.length); + }); +}); diff --git a/tests/unit/fetch-doc-ladder-link.test.ts b/tests/unit/fetch-doc-ladder-link.test.ts new file mode 100644 index 0000000..3c86472 --- /dev/null +++ b/tests/unit/fetch-doc-ladder-link.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from "bun:test"; +import { fetchAndRender } from "../../src/agent/fetch-orchestrate.js"; +import { markdownAlternate, mdTwinUrl } from "../../src/net/doc-markdown.js"; +import { article } from "./helpers/block-pages.js"; +import { serveDocs } from "./helpers/docs-server.js"; + +// Hardening of the docs-native ladder found by the challenger: a redirecting +// twin must not smuggle in another origin, and `Link` header parsing must +// follow RFC 8288 quoting. Public-entry-point cases run the real fast path. + +const MD = "# Intro\n\nSite-authored markdown body with `code`.\n"; + +describe("twin redirect", () => { + test("a same-origin twin that REDIRECTS to another origin is rejected (final url re-checked)", async () => { + const other = serveDocs({ "/stolen.md": { body: "# from elsewhere", contentType: "text/markdown" } }); + const s = serveDocs({ + "/page": { body: article("Redirecting twin page"), headers: { link: '; rel="alternate"; type="text/markdown"' } }, + "/hop.md": { status: 302, headers: { location: `${other.origin}/stolen.md` }, body: "" }, + }); + try { + const { rendered } = await fetchAndRender(`${s.origin}/page`); + expect(other.hits.get("/stolen.md")).toBe(1); // the HTTP client follows the redirect… + expect(rendered.source).toBeUndefined(); // …but the foreign-origin answer is never used + expect(rendered.text).toContain("Redirecting twin page"); + } finally { + s.stop(); + other.stop(); + } + }); +}); + +describe("Link header parsing (through the real fetch)", () => { + const cases: Array<[string, boolean]> = [ + ['; title="Guide, v2"; rel="alternate"; type="application/rss+xml", ; rel="alternate"; type="text/markdown"', true], + ['; title="Guide, v2"; rel="alternate"; type="text/markdown"', true], + ["; REL=Alternate; TYPE=Text/Markdown", true], + ['; rel="nofollow alternate"; type="text/markdown"', true], + ['; rel="alternate-x"; type="text/markdown"', false], + ['; rel="alternate"; type="text/markdownish"', false], + ]; + for (const [link, expected] of cases) { + test(`${expected ? "uses" : "ignores"}: ${link}`, async () => { + const s = serveDocs({ "/p": { body: article("P"), headers: { link } }, "/t.md": { body: MD, contentType: "text/markdown" } }); + try { + const { rendered } = await fetchAndRender(`${s.origin}/p`); + expect(rendered.source === "site-markdown").toBe(expected); + } finally { + s.stop(); + } + }); + } +}); + +describe("helpers", () => { + test("markdownAlternate resolves a relative target and ignores a missing header", () => { + expect(markdownAlternate('; rel="alternate"; type="text/markdown"', "https://x.test/docs/")).toBe("https://x.test/docs/intro.md"); + expect(markdownAlternate(undefined, "https://x.test/")).toBeNull(); + }); + + test("mdTwinUrl: appends .md, drops query/hash and trailing slash; none for root or an existing .md", () => { + expect(mdTwinUrl("https://x.test/docs/intro?a=1#top")).toBe("https://x.test/docs/intro.md"); + expect(mdTwinUrl("https://x.test/docs/intro/")).toBe("https://x.test/docs/intro.md"); + expect(mdTwinUrl("https://x.test/")).toBeNull(); + expect(mdTwinUrl("https://x.test/docs/intro.md")).toBeNull(); + }); +}); diff --git a/tests/unit/fetch-doc-ladder.test.ts b/tests/unit/fetch-doc-ladder.test.ts new file mode 100644 index 0000000..8c8fbde --- /dev/null +++ b/tests/unit/fetch-doc-ladder.test.ts @@ -0,0 +1,186 @@ +import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; +import { fetchBatch } from "../../src/agent/fetch-batch.js"; +import { fetchAndRender } from "../../src/agent/fetch-orchestrate.js"; +import { renderFetch } from "../../src/agent/fetch-render.js"; +import { resolveFetchBody } from "../../src/agent/fetch-resolve.js"; +import { fetchFast } from "../../src/net/fetch-fast.js"; +import { PrivateNetworkBlockedError } from "../../src/net/private-net-guard.js"; +import { article } from "./helpers/block-pages.js"; +import { type DocServer, serveDocs } from "./helpers/docs-server.js"; + +// Public-entry-point tests for the docs-native read ladder: a site's own +// markdown (Accept negotiation, `Link: rel=alternate; type=text/markdown`, and +// — opt-in via preferMarkdown — the `.md` twin) is used instead of extracting +// the HTML. Every case runs the REAL fast path against a local server. + +const MD = "# Intro\n\nSite-authored markdown body with `code`.\n"; +const MD_LINK = '<{ORIGIN}/linked.md>; rel="alternate"; type="text/markdown"'; + +let server: DocServer; +beforeAll(() => { + server = serveDocs({ + // (a) content negotiation: markdown only when the client prefers it. + "/negotiated": (req) => ((req.headers.get("accept") ?? "").startsWith("text/markdown") ? { body: MD, contentType: "text/markdown; charset=utf-8" } : { body: article("Negotiated") }), + // (b) Link header advertising a twin. + "/linked": () => ({ body: article("Linked html"), headers: { link: MD_LINK.replace("{ORIGIN}", server.origin) } }), + "/linked.md": { body: MD, contentType: "text/markdown" }, + "/linked-relative": { body: article("Linked relative"), headers: { link: '; rel="alternate"; type="text/markdown"' } }, + "/linked-other-origin": { body: article("Other origin"), headers: { link: '; rel="alternate"; type="text/markdown"' } }, + "/linked-dead": { body: article("Dead twin"), headers: { link: '; rel="alternate"; type="text/markdown"' } }, + "/linked-wrong-type": { body: article("Wrong type"), headers: { link: '; rel="alternate"; type="application/rss+xml"' } }, + "/linked-404": { status: 404, body: article("Not found page"), headers: { link: '; rel="alternate"; type="text/markdown"' } }, + // (c) opt-in .md twin of a docs URL. + "/docs/intro": { body: article("Docs intro html") }, + "/docs/intro.md": { body: MD, contentType: "text/markdown" }, + "/docs/spa": { body: article("Docs spa html") }, + "/docs/spa.md": { body: article("catch-all html on .md") }, // SPA catch-all: 200 text/html + "/docs/gone": { body: article("Docs gone html") }, + "/docs/err": { status: 500, body: article("Server error page") }, + "/docs/err.md": { body: MD, contentType: "text/markdown" }, + "/plain": { body: article("Plain page") }, + "/plain.md": { body: MD, contentType: "text/markdown" }, + "/data.json": { body: '{"a":1}', contentType: "application/json" }, + }); +}); +afterAll(() => server.stop()); +afterEach(() => { + server.hits.clear(); +}); + +const url = (p: string) => `${server.origin}${p}`; + +describe("(a) Accept: text/markdown — a markdown answer is used as-is", () => { + test("sends a markdown-first Accept and returns the site's markdown verbatim, flagged site-markdown", async () => { + const { rendered } = await fetchAndRender(url("/negotiated")); + expect(server.accepts.get("/negotiated")?.startsWith("text/markdown")).toBe(true); + expect(rendered.text).toBe(MD); + expect(rendered.format).toBe("text"); + expect(rendered.source).toBe("site-markdown"); + expect(server.hits.get("/negotiated")).toBe(1); + }); +}); + +describe("(b) Link: rel=alternate; type=text/markdown", () => { + test("absolute Link → one extra request, site markdown returned, url stays the page's", async () => { + const { rendered } = await fetchAndRender(url("/linked")); + expect(rendered.text).toBe(MD); + expect(rendered.source).toBe("site-markdown"); + expect(rendered.url).toBe(url("/linked")); + expect(server.hits.get("/linked.md")).toBe(1); + }); + + test("relative Link target is resolved against the page URL", async () => { + const { rendered } = await fetchAndRender(url("/linked-relative")); + expect(rendered.text).toBe(MD); + expect(rendered.source).toBe("site-markdown"); + }); + + test("a Link to another origin is never followed", async () => { + const { rendered } = await fetchAndRender(url("/linked-other-origin")); + expect(rendered.source).toBeUndefined(); + expect(rendered.text).toContain("Other origin"); + }); + + test("a Link of another type is ignored (no extra request)", async () => { + const { rendered } = await fetchAndRender(url("/linked-wrong-type")); + expect(rendered.source).toBeUndefined(); + expect(server.hits.get("/linked.md")).toBeUndefined(); + }); + + test("a dead twin (404) falls back to the page's own extraction; exactly one extra request", async () => { + const { rendered } = await fetchAndRender(url("/linked-dead")); + expect(rendered.text).toContain("Dead twin"); + expect(rendered.source).toBeUndefined(); + expect(server.hits.get("/missing.md")).toBe(1); + }); + + test("never on a non-2xx page", async () => { + const { rendered } = await fetchAndRender(url("/linked-404")); + expect(rendered.status).toBe(404); + expect(server.hits.get("/linked.md")).toBeUndefined(); + }); + + test("fetchBatch applies the same ladder", async () => { + const [item] = (await fetchBatch([url("/linked")])) as Array>; + expect(item?.text).toBe(MD); + expect(item?.source).toBe("site-markdown"); + }); +}); + +describe("(c) preferMarkdown — opt-in .md twin", () => { + test("tries .md once and returns it flagged site-markdown", async () => { + const { rendered } = await fetchAndRender(url("/docs/intro"), { preferMarkdown: true }); + expect(rendered.text).toBe(MD); + expect(rendered.source).toBe("site-markdown"); + expect(rendered.url).toBe(url("/docs/intro")); + expect(server.hits.get("/docs/intro.md")).toBe(1); + }); + + test("a SPA catch-all answering HTML on .md is rejected: html extraction, source html, one extra request", async () => { + const { rendered } = await fetchAndRender(url("/docs/spa"), { preferMarkdown: true }); + expect(rendered.text).toContain("Docs spa html"); + expect(rendered.source).toBe("html"); + expect(server.hits.get("/docs/spa.md")).toBe(1); + }); + + test("no twin (404) → html, source html", async () => { + const { rendered } = await fetchAndRender(url("/docs/gone"), { preferMarkdown: true }); + expect(rendered.source).toBe("html"); + expect(rendered.text).toContain("Docs gone html"); + }); + + test("never on a non-2xx page, and no source claimed", async () => { + const { rendered } = await fetchAndRender(url("/docs/err"), { preferMarkdown: true }); + expect(rendered.status).toBe(500); + expect(rendered.source).toBeUndefined(); + expect(server.hits.get("/docs/err.md")).toBeUndefined(); + }); + + test("non-HTML answers (JSON) are untouched and trigger no extra request", async () => { + const { rendered } = await fetchAndRender(url("/data.json"), { preferMarkdown: true }); + expect(rendered.text).toBe('{"a":1}'); + expect(rendered.source).toBeUndefined(); + expect(server.hits.get("/data.json.md")).toBeUndefined(); + }); + + test("the root path has no twin: no extra request", async () => { + await fetchAndRender(`${server.origin}/`, { preferMarkdown: true }); + expect(server.hits.get("/.md")).toBeUndefined(); + expect(server.hits.get("/index.md")).toBeUndefined(); + }); + + test("without preferMarkdown the .md twin is never requested", async () => { + const { rendered } = await fetchAndRender(url("/plain")); + expect(server.hits.get("/plain.md")).toBeUndefined(); + expect(rendered.source).toBeUndefined(); + }); + + test("fetchBatch forwards preferMarkdown", async () => { + const [item] = (await fetchBatch([url("/docs/intro")], { preferMarkdown: true })) as Array>; + expect(item?.text).toBe(MD); + expect(item?.source).toBe("site-markdown"); + }); +}); + +describe("normal results stay byte-identical", () => { + test("a page without site markdown renders exactly as the pre-ladder pipeline did", async () => { + const r = await fetchFast(url("/plain")); + const legacy = await renderFetch(await resolveFetchBody(url("/plain"), r), {}); + const { rendered } = await fetchAndRender(url("/plain")); + expect(JSON.stringify(rendered)).toBe(JSON.stringify(legacy)); + expect(Object.keys(rendered).sort()).toEqual(["escalated", "extraction", "format", "status", "text", "url", "wordCount"]); + }); +}); + +describe("SSRF guard still applies on the ladder", () => { + const prev = process.env.FUSE_BLOCK_PRIVATE_NETS; + afterEach(() => { + if (prev === undefined) delete process.env.FUSE_BLOCK_PRIVATE_NETS; + else process.env.FUSE_BLOCK_PRIVATE_NETS = prev; + }); + test("a loopback target is refused before any ladder request", async () => { + process.env.FUSE_BLOCK_PRIVATE_NETS = "1"; + await expect(fetchAndRender(url("/docs/intro"), { preferMarkdown: true })).rejects.toBeInstanceOf(PrivateNetworkBlockedError); + expect(server.hits.get("/docs/intro.md")).toBeUndefined(); + }); +}); diff --git a/tests/unit/fetch-focus.test.ts b/tests/unit/fetch-focus.test.ts new file mode 100644 index 0000000..88ee6d9 --- /dev/null +++ b/tests/unit/fetch-focus.test.ts @@ -0,0 +1,91 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { renderFetch } from "../../src/agent/fetch-render.js"; +import { resolveFetchBody } from "../../src/agent/fetch-resolve.js"; +import { fetchFast } from "../../src/net/fetch-fast.js"; +import { registerFetchTool } from "../../src/server/tools/fetch.js"; +import { type DocServer, serveDocs } from "./helpers/docs-server.js"; +import { callTool } from "./helpers/tool-client.js"; + +// `browser_fetch {focus, topK}`: model-free BM25 passages over the extracted +// markdown, through the real tool. Off by default; no `focus` = unchanged output. + +const filler = (w: string, n: number): string => Array.from({ length: n }, (_, i) => `${w}${i % 7}`).join(" "); +const SECTIONS: Array<[string, string]> = [ + ["Authentication", `Clients authenticate with an API key sent in the Authorization header. Keys are scoped per project. ${filler("auth", 40)}`], + ["Refresh token rotation", `Every refresh token can be used once. When you exchange a refresh token the server rotates it and returns a new refresh token, invalidating the previous one. Token rotation limits replay. ${filler("rotate", 30)}`], + ["Rate limits", `Requests are limited to 100 per minute per key. Exceeding the quota returns HTTP 429 with a retry hint. ${filler("quota", 40)}`], + ["Pagination", `List endpoints return a cursor. Pass the cursor to fetch the next page of results. ${filler("cursor", 40)}`], +]; +const PAGE = `API guide

API guide

${SECTIONS.map(([h, p]) => `

${h}

${p}

`).join("")}
`; + +let server: DocServer; +beforeAll(() => { + server = serveDocs({ + "/guide": { body: PAGE }, + "/notes.txt": { body: "Kubernetes ingress controllers route traffic.\n\nPostgres vacuum reclaims dead tuples and prevents bloat.\n\nRedis eviction policies decide which keys to drop.", contentType: "text/plain" }, + }); +}); +afterAll(() => server.stop()); + +const fetchTool = (args: Record) => callTool(registerFetchTool, "browser_fetch", { url: `${server.origin}/guide`, ...args }); + +describe("browser_fetch focus/topK", () => { + test("ranks the matching section first, best score first, at most topK", async () => { + const r = await fetchTool({ focus: "refresh token rotation", topK: 2 }); + expect(r.isError).toBe(false); + const p = r.out.passages as Array<{ heading: string; text: string; score: number }>; + expect(p.length).toBeLessThanOrEqual(2); + expect(p[0]?.heading).toBe("Refresh token rotation"); + expect(p[0]?.text).toContain("rotates it and returns a new refresh token"); + expect(p.every((x) => x.score > 0)).toBe(true); + expect(p.map((x) => x.score)).toEqual([...p.map((x) => x.score)].sort((a, b) => b - a)); + }); + + test("a different question lands on a different section", async () => { + const p = (await fetchTool({ focus: "how many requests per minute, HTTP 429 quota" })).out.passages as Array<{ heading: string }>; + expect(p[0]?.heading).toBe("Rate limits"); + }); + + test("topK defaults to 3", async () => { + const p = (await fetchTool({ focus: "token key requests cursor results" })).out.passages as unknown[]; + expect(p.length).toBeLessThanOrEqual(3); + expect(p.length).toBeGreaterThan(0); + }); + + test("a query that matches nothing gives an empty list (not an error, not the whole page)", async () => { + const r = await fetchTool({ focus: "kubernetes zeppelin submarine" }); + expect(r.isError).toBe(false); + expect(r.out.passages).toEqual([]); + }); + + test("passages come from the whole page even when maxChars truncates `text`", async () => { + const r = await fetchTool({ focus: "cursor next page", maxChars: 120 }); + expect(r.out.text).not.toContain("Pagination"); // the Pagination section is cut off `text`… + expect((r.out.passages as Array<{ heading: string }>)[0]?.heading).toBe("Pagination"); + }); + + test("plain-text bodies are ranked by paragraph", async () => { + const r = await callTool(registerFetchTool, "browser_fetch", { url: `${server.origin}/notes.txt`, focus: "postgres vacuum bloat" }); + const p = r.out.passages as Array<{ heading: string; text: string }>; + expect(p[0]?.text).toContain("Postgres vacuum"); + expect(p[0]?.heading).toBe(""); + }); + + test("an empty or blank focus is the same as none", async () => { + for (const focus of ["", " "]) expect((await fetchTool({ focus })).out.passages).toBeUndefined(); + }); + + test("topK must be a positive integer", async () => { + expect((await fetchTool({ focus: "token", topK: 0 })).isError).toBe(true); + }); +}); + +describe("without focus the output is byte-identical", () => { + test("no `passages` key; the tool result equals the pre-feature pipeline", async () => { + const url = `${server.origin}/guide`; + const legacy = await renderFetch(await resolveFetchBody(url, await fetchFast(url)), {}); + const r = await fetchTool({}); + expect(r.out.passages).toBeUndefined(); + expect(JSON.parse(r.text)).toEqual(JSON.parse(JSON.stringify(legacy))); + }); +}); diff --git a/tests/unit/fetch-pdf-concurrency.test.ts b/tests/unit/fetch-pdf-concurrency.test.ts new file mode 100644 index 0000000..ece3576 --- /dev/null +++ b/tests/unit/fetch-pdf-concurrency.test.ts @@ -0,0 +1,69 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { Worker } from "node:worker_threads"; +import { fetchBatch } from "../../src/agent/fetch-batch.js"; +import { pdfToText } from "../../src/net/pdf-extract.js"; +import { type DocServer, serveDocs } from "./helpers/docs-server.js"; +import { flateBombPdf, manyPagesPdf } from "./helpers/pdf-bomb.js"; + +// Gate-1 defect: the PDF memory guard measures process RSS growth, so extractions +// running at the same time were charged to each other — under Bun a legitimate PDF +// next to a bomb ended in `memory` (3/3 runs), and 8 legitimate PDFs in parallel all +// did at the default cap. PDF extraction is now serialized process-wide so the growth +// belongs to exactly one worker. + +// A 400-page legitimate PDF: its extraction lasts long enough to overlap other work. +const PAGES = 400; +const GOOD = manyPagesPdf(PAGES); +const GOODS = ["/g1.pdf", "/g2.pdf", "/g3.pdf", "/g4.pdf"]; +const BATCH_TIMEOUT_MS = 40_000; // a bomb can take several seconds to be caught on a warm process + +let server: DocServer; +beforeAll(() => { + const routes: Parameters[0] = { "/bomb.pdf": { body: flateBombPdf(150), contentType: "application/pdf" } }; + for (const p of GOODS) routes[p] = { body: GOOD, contentType: "application/pdf" }; + server = serveDocs(routes); +}); +afterAll(() => server.stop()); + +describe("PDF extractions are serialized", () => { + test("never more than one extraction worker is alive at a time (deterministic)", async () => { + let alive = 0; + let maxAlive = 0; + // A real, trivially short-lived worker per extraction; `alive` spans spawn → exit. + const counting = (): Worker => { + const w = new Worker("setTimeout(() => {}, 40);", { eval: true }); + alive++; + maxAlive = Math.max(maxAlive, alive); + w.once("exit", () => alive--); + return w; + }; + const results = await Promise.all(Array.from({ length: 6 }, () => pdfToText(GOOD, false, 5_000, counting))); + expect(results.every((r) => r.error === "unreadable")).toBe(true); // the stub never replies; each is released by `exit` + expect(maxAlive).toBe(1); + }); +}); + +describe("browser_fetch_batch: PDF extractions do not charge each other's memory", () => { + test( + "a bomb in the batch never turns a legitimate PDF into `memory`", + async () => { + const urls = ["/bomb.pdf", ...GOODS].map((p) => `${server.origin}${p}`); + const items = (await fetchBatch(urls, { concurrency: 8 })) as Array>; + // The bomb's own verdict is the memory guard's business (fetch-pdf-memory.test.ts): on a warm + // process its RSS growth can hide in retained pages. What this test pins is the collateral. + for (const good of items.slice(1)) { + expect(good.pdfError).toBeUndefined(); + expect(good.pageCount).toBe(PAGES); + expect(String(good.text)).toContain("Legitimate page 1 body"); + } + }, + BATCH_TIMEOUT_MS, + ); + + test("eight legitimate PDFs at concurrency 8 all extract (none is a false `memory`)", async () => { + const urls = Array.from({ length: 8 }, (_, i) => `${server.origin}${GOODS[i % GOODS.length]}?n=${i}`); + const items = (await fetchBatch(urls, { concurrency: 8 })) as Array>; // default cap + expect(items.map((i) => i.pdfError)).toEqual(Array(8).fill(undefined)); + expect(items.every((i) => i.pageCount === PAGES)).toBe(true); + }); +}); diff --git a/tests/unit/fetch-pdf-memory.test.ts b/tests/unit/fetch-pdf-memory.test.ts new file mode 100644 index 0000000..b5bc351 --- /dev/null +++ b/tests/unit/fetch-pdf-memory.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, test } from "bun:test"; +import { fetchAndRender } from "../../src/agent/fetch-orchestrate.js"; +import { pdfMaxMb, pdfToText } from "../../src/net/pdf-extract.js"; +import { loadDocFixture, serveDocs } from "./helpers/docs-server.js"; +import { flateBombPdf, withEnv } from "./helpers/pdf-bomb.js"; + +// Memory cap of the PDF worker. Measured (scratchpad worker-probe2.mjs): the real +// 15-page arXiv paper peaks at ~100 MB RSS delta (heap < 64 MB, passes with a 64 MB +// heap limit) on Node 26 and Bun 1.4.4; a 150 MB-inflating bomb reaches ~410-930 MB. +// +// Timing (full `bun test tests/unit`, 4 runs): the guard fires in ~80 ms in a fresh +// process but took 2.4-3.7 s when the process already holds retained freed pages +// (RSS grows more slowly there — the delta is measured from the worker's start), so +// the bomb tests lasted up to 4.7 s and tripped bun's 5 s default. The explicit +// per-test timeout is ~3x the worst measured duration; the extraction budget sits +// well above the worst detection latency so the MEMORY guard, not the clock, ends it. +const BOMB_TEST_TIMEOUT_MS = 15_000; +const BOMB_BUDGET_MS = 12_000; +// 64 MB, not 128: on a warm process the bomb's RSS growth can hide in retained pages +// (a 150 MB bomb once finished under a 256 MB cap); a normal PDF peaks under ~50 MB. +const BOMB_CAP_MB = "64"; + +const GOOD = loadDocFixture("two-page.pdf"); + +describe("PDF worker memory cap (FUSE_PDF_MAX_MB)", () => { + test( + "a bomb is stopped by the memory cap before the time budget, and the process survives", + async () => { + const bomb = flateBombPdf(150); + const out = await withEnv("FUSE_PDF_MAX_MB", BOMB_CAP_MB, () => pdfToText(bomb, false, BOMB_BUDGET_MS)); + expect(out.error).toBe("memory"); // not "timeout": the clock did not end it + expect(out.text).toBe(""); + expect(out.pageCount).toBeUndefined(); + const after = await pdfToText(GOOD, false); // parent alive, next extraction unaffected + expect(after.pageCount).toBe(2); + }, + BOMB_TEST_TIMEOUT_MS, + ); + + test( + "through browser_fetch: pdfError:memory, no garbage text", + async () => { + const s = serveDocs({ "/bomb.pdf": { body: flateBombPdf(150), contentType: "application/pdf" } }); + try { + const { rendered } = await withEnv("FUSE_PDF_MAX_MB", BOMB_CAP_MB, () => fetchAndRender(`${s.origin}/bomb.pdf`)); + expect(rendered.pdfError).toBe("memory"); + expect(rendered.text).toBe(""); + } finally { + s.stop(); + } + }, + BOMB_TEST_TIMEOUT_MS, + ); + + test("a normal PDF is unaffected by a tight cap", async () => { + const out = await withEnv("FUSE_PDF_MAX_MB", "128", () => pdfToText(GOOD, false)); + expect(out.error).toBeUndefined(); + expect(out.pageCount).toBe(2); + }); + + test("the cap is a DELTA from the worker's start: a process already holding far more than the cap is not a false 'memory'", async () => { + const held = Buffer.alloc(400 * 1_048_576, 1); // 400 MB committed in this process, 3x the 128 MB cap + const out = await withEnv("FUSE_PDF_MAX_MB", "128", () => pdfToText(GOOD, false)); + expect(held.length).toBeGreaterThan(0); + expect(out.error).toBeUndefined(); + expect(out.pageCount).toBe(2); + }); + + test("pdfMaxMb: default 256, env override, junk falls back to the default", async () => { + const prev = process.env.FUSE_PDF_MAX_MB; + delete process.env.FUSE_PDF_MAX_MB; + expect(pdfMaxMb()).toBe(256); + for (const [v, want] of [["512", 512], ["0", 256], ["-5", 256], ["abc", 256], ["", 256]] as const) { + expect([v, await withEnv("FUSE_PDF_MAX_MB", v, async () => pdfMaxMb())]).toEqual([v, want]); + } + if (prev !== undefined) process.env.FUSE_PDF_MAX_MB = prev; + }); +}); diff --git a/tests/unit/fetch-pdf-worker-failure.test.ts b/tests/unit/fetch-pdf-worker-failure.test.ts new file mode 100644 index 0000000..ac09579 --- /dev/null +++ b/tests/unit/fetch-pdf-worker-failure.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, test } from "bun:test"; +import { Worker } from "node:worker_threads"; +import { pdfToText } from "../../src/net/pdf-extract.js"; +import { loadDocFixture } from "./helpers/docs-server.js"; + +// Worker failure modes the queue must survive: a worker that dies without a +// message or an error, and a worker that cannot even be created. Both must +// resolve `unreadable` at once (never reject, never hold the queue for the 20 s +// budget). The optional 4th argument of `pdfToText` is the worker factory seam. + +const GOOD = loadDocFixture("two-page.pdf"); +const BUDGET_MS = 600_000; // far larger than any test timeout: the clock can never be what releases the queue + +describe("PDF worker that exits without a reply", () => { + test.each([ + ["exit code 0 (empty module)", "export {};"], + ["exit code 1 (process.exit)", "process.exit(1);"], + ])("%s → unreadable immediately, and the next queued PDF still extracts", async (_name, source) => { + const dying = () => new Worker(source, { eval: true }); + const [dead, next] = await Promise.all([pdfToText(GOOD, false, BUDGET_MS, dying), pdfToText(GOOD, false)]); + expect(dead.error).toBe("unreadable"); + expect(dead.text).toBe(""); + // Queued behind the dead one and released by `exit`: with a 10-minute budget on the dead worker, + // this only completes (inside the test's own timeout) if the queue was released by the exit, not the clock. + expect(next.pageCount).toBe(2); + }); +}); + +describe("worker that cannot be created", () => { + test("a throwing factory (Worker constructor / import.meta.resolve) resolves unreadable, never rejects", async () => { + const boom = () => { + throw new Error("cannot spawn"); + }; + const out = await pdfToText(GOOD, false, BUDGET_MS, boom); + expect(out).toEqual({ text: "", error: "unreadable" }); + const next = await pdfToText(GOOD, false); // the queue is not wedged + expect(next.pageCount).toBe(2); + }); +}); diff --git a/tests/unit/fetch-pdf.test.ts b/tests/unit/fetch-pdf.test.ts new file mode 100644 index 0000000..46fb812 --- /dev/null +++ b/tests/unit/fetch-pdf.test.ts @@ -0,0 +1,135 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { type PdfWorkerFactory, pdfToText, spawnPdfWorker } from "../../src/net/pdf-extract.js"; +import { crawl } from "../../src/agent/crawl.js"; +import { fetchBatch } from "../../src/agent/fetch-batch.js"; +import { fetchAndRender } from "../../src/agent/fetch-orchestrate.js"; +import { article } from "./helpers/block-pages.js"; +import { type DocServer, loadDocFixture, serveDocs } from "./helpers/docs-server.js"; +import { flateBombPdf, withEnv } from "./helpers/pdf-bomb.js"; + +// Public-entry-point tests: the REAL fast path (impit → fetchFast → resolve → +// render) runs against a local server. Before this change a PDF response came +// back as raw `%PDF-1.5 ... stream` bytes decoded as text (measured on +// https://arxiv.org/pdf/1706.03762). + +const PDF = loadDocFixture("two-page.pdf"); +const TEN_MB = 10_485_760; +const tooBig = new Uint8Array(TEN_MB + 1024); +tooBig.set(new TextEncoder().encode("%PDF-1.4\n")); + +let server: DocServer; +beforeAll(() => { + server = serveDocs({ + "/doc.pdf": { body: PDF, contentType: "application/pdf" }, + "/download": { body: PDF, contentType: "application/octet-stream" }, // magic bytes only + "/big.pdf": { body: tooBig, contentType: "application/pdf" }, + "/corrupt.pdf": { body: "%PDF-1.4\nthis is not a pdf at all", contentType: "application/pdf" }, + "/page": { body: article("Plain page") }, + "/hub.html": { body: article("Hub", 'the paper') }, + }); +}); +afterAll(() => server.stop()); + +describe("browser_fetch — PDF responses are read as text", () => { + test("application/pdf → readable text with page markers and pageCount", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/doc.pdf`); + expect(rendered.status).toBe(200); + expect(rendered.text).not.toContain("%PDF"); + expect(rendered.text).toContain(""); + expect(rendered.text).toContain("Alpha paragraph about the transformer"); + expect(rendered.text).toContain(""); + expect(rendered.text).toContain("Beta paragraph about attention"); + expect(rendered.text.indexOf("page 1")).toBeLessThan(rendered.text.indexOf("Alpha")); + expect(rendered.text.indexOf("Alpha")).toBeLessThan(rendered.text.indexOf("page 2")); + expect(rendered.pageCount).toBe(2); + expect(rendered.pdfError).toBeUndefined(); + expect(rendered.escalated).toBe(false); + }); + + test("%PDF- magic bytes are enough when the content-type is generic", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/download`); + expect(rendered.text).toContain("Alpha paragraph"); + expect(rendered.pageCount).toBe(2); + }); + + test("maxChars truncates the text, pageCount still reports the whole document", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/doc.pdf`, { maxChars: 40 }); + expect(rendered.text.length).toBeLessThanOrEqual(40); + expect(rendered.pageCount).toBe(2); + }); + + test("a PDF over the 10 MB download cap is refused with pdfError:too_large, no garbage text", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/big.pdf`); + expect(rendered.pdfError).toBe("too_large"); + expect(rendered.text).not.toContain("%PDF"); + expect(rendered.pageCount).toBeUndefined(); + }); + + test("a corrupt PDF reports pdfError:unreadable instead of throwing", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/corrupt.pdf`); + expect(rendered.pdfError).toBe("unreadable"); + expect(rendered.text).not.toContain("%PDF"); + }); + + test("normal pages carry no PDF field (output shape unchanged)", async () => { + const { rendered } = await fetchAndRender(`${server.origin}/page`); + expect(Object.keys(rendered).sort()).toEqual(["escalated", "extraction", "format", "status", "text", "url", "wordCount"]); + }); +}); + +describe("PDF extraction is bounded (decompression bomb)", () => { + test("a small PDF that inflates to ~150 MB is cut off by the extraction budget, not left running", async () => { + const bomb = flateBombPdf(150); + expect(bomb.length).toBeLessThan(1_000_000); + // memory cap lifted so the wall-clock budget is what stops it (memory cap: fetch-pdf-memory.test.ts) + const out = await withEnv("FUSE_PDF_MAX_MB", "4096", () => pdfToText(bomb, false, 400)); + expect(out.error).toBe("timeout"); + expect(out.text).toBe(""); + }); + + test("extraction runs off the main thread (a worker thread, not the server's event loop)", async () => { + let threadId = 0; + const spying: PdfWorkerFactory = (copy, maxMb) => { + const w = spawnPdfWorker(copy, maxMb); + threadId = w.threadId; + return w; + }; + const out = await pdfToText(PDF, false, 20_000, spying); + expect(out.pageCount).toBe(2); + expect(threadId).toBeGreaterThan(0); // the main thread is id 0 + }); + + test("a text/plain body that merely starts with %PDF- stays text", async () => { + const s = serveDocs({ "/note": { body: "%PDF- is the signature of a PDF file.", contentType: "text/plain" } }); + try { + const { rendered } = await fetchAndRender(`${s.origin}/note`); + expect(rendered.text).toBe("%PDF- is the signature of a PDF file."); + expect(rendered.pdfError).toBeUndefined(); + } finally { + s.stop(); + } + }); +}); + +describe("browser_fetch_batch and browser_crawl read PDFs too", () => { + test("fetchBatch: PDF item has text + pageCount next to a normal page", async () => { + const items = await fetchBatch([`${server.origin}/doc.pdf`, `${server.origin}/page`]); + const [pdf, page] = items as Array>; + expect(String(pdf?.text)).toContain(""); + expect(pdf?.pageCount).toBe(2); + expect(page?.pageCount).toBeUndefined(); + }); + + test("crawl: a PDF page is extracted as text; no links are followed out of it", async () => { + const out = await crawl(`${server.origin}/doc.pdf`, { maxDepth: 2, respectRobots: false, throttleMs: 0 }); + expect(out.count).toBe(1); + expect(out.pages[0]?.text).toContain("Alpha paragraph"); + expect(out.pages[0]?.pageCount).toBe(2); + }); + + test("crawl: a PDF linked from an HTML page is fetched and read", async () => { + const out = await crawl(`${server.origin}/hub.html`, { maxDepth: 1, respectRobots: false, throttleMs: 0 }); + const pdf = out.pages.find((p) => p.url.endsWith("/doc.pdf")); + expect(pdf?.text).toContain("Beta paragraph"); + }); +}); diff --git a/tests/unit/find-elements.test.ts b/tests/unit/find-elements.test.ts new file mode 100644 index 0000000..db97ed4 --- /dev/null +++ b/tests/unit/find-elements.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, test } from "bun:test"; +import { findElements } from "../../src/extraction/find-elements.js"; +import type { InteractiveElement } from "../../src/interfaces/extraction.js"; + +const el = (index: number, text: string, extra: Partial = {}): InteractiveElement => ({ + index, + ref: String(index), + tag: "button", + text, + role: null, + id: null, + name: null, + type: null, + href: null, + visible: true, + box: { x: 0, y: 0, width: 1, height: 1 }, + ...extra, +}); + +const page = [el(0, "Save draft"), el(1, "Save"), el(2, "Cancel"), el(3, "", { role: "tab", text: "Settings" }), el(4, "x", { tag: "input", placeholder: "Search the docs" })]; + +describe("findElements", () => { + test("exact name ranks before prefix before contains; DOM order breaks ties", () => { + const r = findElements(page, "save", 10); + expect(r.total).toBe(2); + expect(r.matches.map((m) => m.ref)).toEqual(["1", "0"]); + }); + + test("every token must match, case-insensitive, across name/role/placeholder", () => { + expect(findElements(page, "SEARCH docs", 10).matches.map((m) => m.ref)).toEqual(["4"]); + expect(findElements(page, "tab", 10).matches.map((m) => m.ref)).toEqual(["3"]); + expect(findElements(page, "save cancel", 10).total).toBe(0); + }); + + test("limit cuts the list but total keeps the full count; blank query matches nothing", () => { + const many = Array.from({ length: 30 }, (_, i) => el(i, `row ${i}`)); + const r = findElements(many, "row", 5); + expect(r.matches.length).toBe(5); + expect(r.total).toBe(30); + expect(findElements(many, " ", 5)).toEqual({ matches: [], total: 0 }); + }); +}); diff --git a/tests/unit/helpers/block-pages.ts b/tests/unit/helpers/block-pages.ts new file mode 100644 index 0000000..fdccb4b --- /dev/null +++ b/tests/unit/helpers/block-pages.ts @@ -0,0 +1,159 @@ +/** + * Page matrix shared by the block-detection tests: BLOCKED pages (real captured + * interstitials + synthetic ones) and NOT-blocked pages (normal, sparse, + * look-alike). Served through the fixture server and fed to the pure detector. + */ +import { type FixtureRoute, loadHtml, routeFromCaptured } from "./fixture-server.js"; + +const PROSE = + "The committee reviewed the annual report and discussed the findings at length. " + + "Several members raised questions about the methodology, and the authors answered each one in turn. "; + +/** A realistic article page with enough prose to clear every sparse-page threshold. */ +export function article(title: string, extra = ""): string { + return ( + `${title}` + + `

${title}

` + + `

${PROSE.repeat(8)}

${extra}

${PROSE.repeat(4)}

Copyright
` + ); +} + +/** Real captured interstitials, keyed by route path. `vendor` is the expected `blockedBy`. */ +export const REAL_BLOCKED: Record = { + "/cf-managed": { route: routeFromCaptured("cloudflare-managed-miraheze"), vendor: "cloudflare" }, + "/cf-security": { route: routeFromCaptured("cloudflare-security-glassdoor"), vendor: "cloudflare" }, + "/cf-moment": { route: routeFromCaptured("cloudflare-just-a-moment-stockx"), vendor: "cloudflare" }, + "/datadome": { route: routeFromCaptured("datadome-g2"), vendor: "datadome" }, +}; + +/** + * Synthetic blocked pages. AWS WAF shape: from the AWS WAF developer guide, + * "CAPTCHA and Challenge action behavior" (docs.aws.amazon.com/waf/latest/developerguide/ + * waf-captcha-and-challenge-actions.html): header `x-amzn-waf-action: challenge`, HTTP 202, + * JavaScript interstitial. Generic shape: a vendor-less thin 403 with two weak signals. + */ +export const SYNTHETIC_BLOCKED: Record = { + "/aws-waf": { + vendor: "aws-waf", + route: { + status: 202, + headers: { "x-amzn-waf-action": "challenge" }, + body: "", + }, + }, + "/generic-weak": { + vendor: "unknown", + route: { + status: 403, + body: + 'Pardon Our Interruption' + + "

Pardon Our Interruption

Please enable JavaScript to continue.

", + }, + }, +}; + +/** Pages that must NEVER be flagged: every one keeps today's exact output. */ +export const NOT_BLOCKED: Record = { + "/article": { status: 200, body: article("Quarterly report") }, + "/article-mentions-captcha": { + status: 200, + body: article( + "How bot protection works", + 'A captcha, a "Checking your connection..." screen or "Just a moment..." page, the cf-mitigated: challenge header, ' + + "window._cf_chl_opt and ct.captcha-delivery.com are all things this article merely talks about.", + ), + }, + "/real-404": { + status: 404, + body: + "Page not found

Page not found

" + + "

We could not find the page you were looking for. It may have been moved or deleted.

" + + '

Try the home page or search the archive.

', + }, + "/forbidden-with-text": { + status: 403, + body: article("Access forbidden", "You do not have permission to view this resource. Contact the administrator if you think this is a mistake."), + }, + "/bare-403": { + status: 403, + body: "403 Forbidden

403 Forbidden


nginx
", + }, + "/maintenance-503": { + status: 503, + body: article("Down for maintenance", "We are performing scheduled maintenance and will be back shortly. Thank you for your patience."), + }, + "/maintenance-refresh-503": { + status: 503, + body: + 'Maintenance' + + "

We will be right back

Scheduled maintenance in progress.

", + }, + // Found by the adversarial review: two weak signals that legitimately co-occur on error pages. + "/datadome-site-503-refresh": { + status: 503, + headers: { "x-datadome": "protected" }, + body: + 'Maintenance' + + "

We will be back soon

", + }, + "/denied-403-refresh-to-login": { + status: 403, + body: + 'Access Denied' + + "

You are not allowed here. Redirecting to the sign-in page.

", + }, + // C: `x-datadome` rides on EVERY response of a DataDome-protected site, so it must not help two page-level hints reach the quorum. + "/denied-403-refresh-datadome-site": { + status: 403, + headers: { "x-datadome": "protected" }, + body: + 'Access Denied' + + "

You are not allowed here. Redirecting to the sign-in page.

", + }, + // D1: one phrase ("verify you are human") in both title and text is ONE hint, not two. + "/one-phrase-title-and-text-403": { + status: 403, + body: + 'Verify you are human' + + "

Verify you are human.

", + }, + // D2: a thin 200 SPA shell whose CSP meta merely whitelists the DataDome challenge host. + "/spa-csp-captcha-delivery": { + status: 200, + body: + '' + + '
', + }, + // D3: a long 403 that quotes the Cloudflare option name in prose (no assignment, no script). + "/thick-403-quotes-cf-opt": { + status: 403, + body: article("Forbidden", "Challenge pages define window._cf_chl_opt before loading their script."), + }, + "/security-check-401-noscript": { + status: 401, + body: + "Security Check

Sign in required.

" + + "", + }, + "/rate-limited-429": { + status: 429, + headers: { "retry-after": "30" }, + body: article("Too many requests", "You have sent too many requests in a given amount of time. Please retry later."), + }, + "/spa-shell": { + status: 200, + body: '
', + }, + "/login": { status: 200, body: loadHtml("sparse-login.html") }, + "/listing": { status: 200, body: loadHtml("smf-board.html") }, + "/datadome-header-only": { + status: 200, + headers: { "x-datadome": "protected" }, + body: article("Protected shop front page"), + }, + "/datadome-tag-article": { + status: 200, + body: article("Protected article").replace("", ''), + }, + "/json-403": { status: 403, contentType: "application/json", body: '{"error":"forbidden"}' }, +}; diff --git a/tests/unit/helpers/budget-client.ts b/tests/unit/helpers/budget-client.ts new file mode 100644 index 0000000..932ad56 --- /dev/null +++ b/tests/unit/helpers/budget-client.ts @@ -0,0 +1,54 @@ +/** + * Test helper: real MCP tools wired exactly as a tool owner would wire the + * output budget (shapes spread into the schemas + one `budgetResult` call), + * driven through the real protocol with an in-memory client. + */ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; +import { BUDGET_INPUT_SHAPE, BUDGET_OUTPUT_SHAPE, budgetResult } from "../../../src/server/output-budget.js"; + +/** ~40 paragraphs separated by blank lines. */ +export const TEXT = Array.from({ length: 40 }, (_, i) => `Paragraph ${i} ${"lorem ipsum ".repeat(8).trim()}.`).join("\n\n"); +/** Multi-byte text (2-, 3- and 4-byte characters). */ +export const MULTIBYTE = "é日本語🙂 ".repeat(200); +/** A literal U+FFFD run and a lone surrogate: both must survive paging untouched. */ +export const TRICKY = "��bbbbb ab\uD800cdefghijkl �x"; +/** 30 small structured items. */ +export const ITEMS = Array.from({ length: 30 }, (_, i) => ({ ref: String(i), name: `element-${i}`, role: "button" })); + +export type Out = Record; +export type Called = { content: Array<{ type: string; text: string }>; structuredContent: Out }; + +const elementShape = z.object({ ref: z.string(), name: z.string(), role: z.string() }); + +/** Server with `big_text` (string field), `big_list` (array field) and `multibyte` tools. */ +export async function budgetClient(): Promise { + const server = new McpServer({ name: "t", version: "0" }); + const make = (name: string, payload: Out, field: string, shape: z.ZodRawShape) => + server.registerTool( + name, + { inputSchema: { ...BUDGET_INPUT_SHAPE }, outputSchema: { ...shape, ...BUDGET_OUTPUT_SHAPE } }, + async (args) => budgetResult(name, payload, field, args as Out), + ); + make("big_text", { url: "https://x.test/", text: TEXT }, "text", { url: z.string(), text: z.string() }); + make("big_list", { count: ITEMS.length, elements: ITEMS }, "elements", { count: z.number(), elements: z.array(elementShape) }); + make("multibyte", { text: MULTIBYTE }, "text", { text: z.string() }); + make("tricky", { text: TRICKY }, "text", { text: z.string() }); + // A tool with its own `truncated` (element cap, maxChars...): the budget must leave it alone. + make("own_false", { truncated: false, text: TEXT }, "text", { truncated: z.boolean(), text: z.string() }); + make("own_true", { truncated: true, text: "short" }, "text", { truncated: z.boolean(), text: z.string() }); + make("scalar", { count: 3 }, "count", { count: z.number() }); + make("absent_field", { count: 3 }, "text", { count: z.number() }); + make("with_undefined", { items: [{ a: 1 }, undefined, { a: 3 }] }, "items", { items: z.array(z.unknown()) }); + const [ct, st] = InMemoryTransport.createLinkedPair(); + const c = new Client({ name: "c", version: "0" }); + await Promise.all([server.connect(st), c.connect(ct)]); + return c; +} + +/** Call a tool and type the result. */ +export async function call(c: Client, name: string, args: Out = {}): Promise { + return (await c.callTool({ name, arguments: args })) as Called; +} diff --git a/tests/unit/helpers/docs-server.ts b/tests/unit/helpers/docs-server.ts new file mode 100644 index 0000000..e696a31 --- /dev/null +++ b/tests/unit/helpers/docs-server.ts @@ -0,0 +1,56 @@ +/** + * Local fixture server for the docs-reading tests (PDF + site-markdown ladder). + * Unlike `fixture-server.ts` it serves binary bodies and lets a route compute + * its response from the request (e.g. `Accept` content negotiation), and it + * records the request headers per path so tests can assert what was sent. + */ +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +/** One canned response; `body` may be binary. */ +export interface DocRoute { + status?: number; + headers?: Record; + body: string | Uint8Array; + contentType?: string; +} + +/** A route, or a function choosing the route from the request. */ +export type DocHandler = DocRoute | ((req: Request) => DocRoute); + +/** A running docs fixture server. */ +export interface DocServer { + origin: string; + /** Requests served per path. */ + hits: Map; + /** `Accept` header received on the most recent request per path. */ + accepts: Map; + stop(): void; +} + +/** Read a binary fixture from `tests/fixtures/docs-reading/`. */ +export function loadDocFixture(name: string): Uint8Array { + return new Uint8Array(readFileSync(fileURLToPath(new URL(`../../fixtures/docs-reading/${name}`, import.meta.url)))); +} + +/** Serve `routes` (keyed by pathname) on a random loopback port; unknown paths answer 404. */ +export function serveDocs(routes: Record): DocServer { + const hits = new Map(); + const accepts = new Map(); + const server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(req) { + const path = new URL(req.url).pathname; + hits.set(path, (hits.get(path) ?? 0) + 1); + accepts.set(path, req.headers.get("accept") ?? ""); + const h = routes[path]; + if (!h) return new Response("", { status: 404 }); + const r = typeof h === "function" ? h(req) : h; + const headers = new Headers(r.headers ?? {}); + headers.set("content-type", r.contentType ?? "text/html; charset=utf-8"); + return new Response(r.body as BodyInit, { status: r.status ?? 200, headers }); + }, + }); + return { origin: `http://127.0.0.1:${server.port}`, hits, accepts, stop: () => void server.stop(true) }; +} diff --git a/tests/unit/helpers/fixture-server.ts b/tests/unit/helpers/fixture-server.ts new file mode 100644 index 0000000..5a86ee8 --- /dev/null +++ b/tests/unit/helpers/fixture-server.ts @@ -0,0 +1,73 @@ +/** + * Local fixture HTTP server for public-entry-point tests: serves canned + * status/header/body triples on 127.0.0.1 so the REAL fetch pipeline + * (impit → fetchFast → resolve → render) runs against real response headers. + */ +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +/** One canned HTTP response. */ +export interface FixtureRoute { + status: number; + headers?: Record; + body: string; + /** Defaults to `text/html; charset=utf-8`. */ + contentType?: string; +} + +/** A captured real response (see `tests/fixtures/blocked/*.json`). */ +interface CapturedFixture { + url: string; + status: number; + headers: Record; + html: string; +} + +const FIXTURES = fileURLToPath(new URL("../../fixtures/", import.meta.url)); + +/** Read a captured blocked response fixture by file stem. */ +export function loadBlocked(name: string): CapturedFixture { + return JSON.parse(readFileSync(`${FIXTURES}blocked/${name}.json`, "utf-8")) as CapturedFixture; +} + +/** Turn a captured fixture into a servable route (status + headers + body verbatim). */ +export function routeFromCaptured(name: string): FixtureRoute { + const f = loadBlocked(name); + const { "content-type": contentType, ...headers } = f.headers; + return { status: f.status, headers, body: f.html, contentType }; +} + +/** Read a plain HTML fixture from `tests/fixtures/`. */ +export function loadHtml(file: string): string { + return readFileSync(`${FIXTURES}${file}`, "utf-8"); +} + +/** A running fixture server. */ +export interface FixtureServer { + origin: string; + /** Number of requests served per path. */ + hits: Map; + stop(): void; +} + +/** + * Serve `routes` (keyed by pathname) on a random loopback port. Unknown paths + * (e.g. `/robots.txt`) answer 404 with an empty body. + */ +export function serveFixtures(routes: Record): FixtureServer { + const hits = new Map(); + const server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(req) { + const path = new URL(req.url).pathname; + hits.set(path, (hits.get(path) ?? 0) + 1); + const r = routes[path]; + if (!r) return new Response("", { status: 404 }); + const headers = new Headers(r.headers ?? {}); + headers.set("content-type", r.contentType ?? "text/html; charset=utf-8"); + return new Response(r.body, { status: r.status, headers }); + }, + }); + return { origin: `http://127.0.0.1:${server.port}`, hits, stop: () => void server.stop(true) }; +} diff --git a/tests/unit/helpers/pdf-bomb.ts b/tests/unit/helpers/pdf-bomb.ts new file mode 100644 index 0000000..19ef454 --- /dev/null +++ b/tests/unit/helpers/pdf-bomb.ts @@ -0,0 +1,65 @@ +/** + * Builds a tiny, structurally valid PDF whose single Flate content stream + * inflates to `mb` MB of valid text operators — a "decompression bomb" for the + * PDF extraction limits (time and memory). + */ +import { deflateSync } from "node:zlib"; + +/** A PDF of < 1 MB that pdf.js inflates to about `mb` MB. */ +export function flateBombPdf(mb: number): Uint8Array { + const line = "BT /F1 12 Tf 72 700 Td (x) Tj ET\n"; + const stream = deflateSync(Buffer.from(line.repeat(Math.floor((mb * 1_048_576) / line.length))), { level: 9 }); + const objs: Buffer[] = [ + Buffer.from("<< /Type /Catalog /Pages 2 0 R >>"), + Buffer.from("<< /Type /Pages /Kids [3 0 R] /Count 1 >>"), + Buffer.from("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>"), + Buffer.concat([Buffer.from(`<< /Length ${stream.length} /Filter /FlateDecode >>\nstream\n`), stream, Buffer.from("\nendstream")]), + Buffer.from("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"), + ]; + const parts: Buffer[] = [Buffer.from("%PDF-1.4\n")]; + const offsets: number[] = []; + let pos = parts[0]?.length ?? 0; + objs.forEach((o, i) => { + offsets.push(pos); + const b = Buffer.concat([Buffer.from(`${i + 1} 0 obj\n`), o, Buffer.from("\nendobj\n")]); + parts.push(b); + pos += b.length; + }); + const xref = [`xref\n0 ${objs.length + 1}\n0000000000 65535 f \n`, ...offsets.map((o) => `${String(o).padStart(10, "0")} 00000 n \n`)].join(""); + parts.push(Buffer.from(`${xref}trailer\n<< /Size ${objs.length + 1} /Root 1 0 R >>\nstartxref\n${pos}\n%%EOF\n`)); + return new Uint8Array(Buffer.concat(parts)); +} + +/** A legitimate multi-page text PDF (`pages` pages, one line each): takes noticeable extraction time, little memory. */ +export function manyPagesPdf(pages: number): Uint8Array { + const objs: string[] = ["<< /Type /Catalog /Pages 2 0 R >>", `<< /Type /Pages /Kids [${Array.from({ length: pages }, (_, i) => `${3 + 2 * i} 0 R`).join(" ")}] /Count ${pages} >>`]; + const font = 3 + 2 * pages; + for (let i = 0; i < pages; i++) { + const s = `BT /F1 12 Tf 72 700 Td (Legitimate page ${i + 1} body text.) Tj ET`; + objs.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${4 + 2 * i} 0 R /Resources << /Font << /F1 ${font} 0 R >> >> >>`); + objs.push(`<< /Length ${s.length} >>\nstream\n${s}\nendstream`); + } + objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"); + let out = "%PDF-1.4\n"; + const offs: number[] = []; + objs.forEach((o, i) => { + offs.push(out.length); + out += `${i + 1} 0 obj\n${o}\nendobj\n`; + }); + const x = out.length; + out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n${offs.map((o) => `${String(o).padStart(10, "0")} 00000 n \n`).join("")}`; + out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R >>\nstartxref\n${x}\n%%EOF\n`; + return new TextEncoder().encode(out); +} + +/** Run `fn` with `process.env[name]` set to `value` (restored afterwards). */ +export async function withEnv(name: string, value: string, fn: () => Promise): Promise { + const prev = process.env[name]; + process.env[name] = value; + try { + return await fn(); + } finally { + if (prev === undefined) delete process.env[name]; + else process.env[name] = prev; + } +} diff --git a/tests/unit/helpers/tool-client.ts b/tests/unit/helpers/tool-client.ts new file mode 100644 index 0000000..88c4691 --- /dev/null +++ b/tests/unit/helpers/tool-client.ts @@ -0,0 +1,44 @@ +/** + * Calls a REAL registered MCP tool in-process: a fresh `McpServer` with only the + * given registration(s), driven through an in-memory MCP client — so input + * validation, the handler and the output schema all run, as in production. + */ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; + +/** Loosely typed `structuredContent` of a tool result (assertions narrow it). */ +// biome-ignore lint/suspicious/noExplicitAny: test-only access to arbitrary tool output +export type ToolOut = Record; + +/** A tool call outcome. */ +export interface ToolCall { + isError: boolean; + /** `structuredContent` (empty object when absent). */ + out: ToolOut; + /** Raw JSON text block of the result. */ + text: string; +} + +/** + * Call tool `name` with `args` on a server that registered only `register`. + * + * @param register - Registration function(s), e.g. `registerFetchTool`. + * @param name - Tool name. + * @param args - Tool arguments. + */ +export async function callTool(register: ((s: McpServer) => void) | Array<(s: McpServer) => void>, name: string, args: Record): Promise { + const server = new McpServer({ name: "test", version: "0.0.0" }); + for (const r of Array.isArray(register) ? register : [register]) r(server); + const [ct, st] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "test", version: "0.0.0" }); + await Promise.all([server.connect(st), client.connect(ct)]); + try { + const res = await client.callTool({ name, arguments: args }); + const block = (res.content as Array<{ type: string; text?: string }>)[0]; + return { isError: res.isError === true, out: (res.structuredContent ?? {}) as ToolOut, text: block?.text ?? "" }; + } finally { + await client.close(); + await server.close(); + } +} diff --git a/tests/unit/helpers/verify-site.ts b/tests/unit/helpers/verify-site.ts new file mode 100644 index 0000000..7861371 --- /dev/null +++ b/tests/unit/helpers/verify-site.ts @@ -0,0 +1,66 @@ +/** + * Local site + session helpers for the `browser_verify` tests: real pages on + * 127.0.0.1 (good, changed, 404 subresource, console error, noisy, uncaught + * exception, flaky API, real blocked interstitial); third-party requests are aborted. + */ +import { mkdtempSync, realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { withClient } from "../../integration/helpers/safe-actions-harness.js"; +import { REAL_BLOCKED } from "./block-pages.js"; +import type { FixtureRoute, FixtureServer } from "./fixture-server.js"; + +const GOOD = "Good

Welcome

"; +const html = (body: string): FixtureRoute => ({ status: 200, body }); + +const ROUTES: Record = { + "/good": html(GOOD), + "/changed": html(`${GOOD}

Brand new banner

`), + "/bad-img": html("

Welcome

x"), + "/console-error": html("

Welcome

"), + "/noisy": html("

Noisy

"), + "/throw": html("

Throws

"), + "/flaky-page": html("

Flaky

"), + "/many": html("

Many

"), + "/netfail": html("

Net

x"), + "/redir": { status: 302, headers: { location: "/good" }, body: "" }, + "/ok.json": { status: 200, body: "{}", contentType: "application/json" }, + "/cf-moment": REAL_BLOCKED["/cf-moment"]!.route, +}; + +/** Start the fixture site; `/flaky` answers 500 the first time and 200 afterwards. */ +export function startSite(): FixtureServer { + const hits = new Map(); + const server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(req) { + const path = new URL(req.url).pathname; + const n = (hits.get(path) ?? 0) + 1; + hits.set(path, n); + if (path === "/flaky") return new Response("{}", { status: n === 1 ? 500 : 200 }); + const r = ROUTES[path]; + if (!r) return new Response("", { status: 404 }); + const headers = new Headers(r.headers ?? {}); + headers.set("content-type", r.contentType ?? "text/html; charset=utf-8"); + return new Response(r.body, { status: r.status, headers }); + }, + }); + return { origin: `http://127.0.0.1:${server.port}`, hits, stop: () => void server.stop(true) }; +} + +/** A fresh real directory (macOS tmpdir is behind a symlink). */ +export const tmpDir = (): string => join(realpathSync(mkdtempSync(join(realpathSync(tmpdir()), "verify-")))); + +/** Run `fn` with a session (third-party requests aborted) opened on about:blank. */ +export function inSession(fn: (c: Client, sessionId: string) => Promise, engine = "patchright"): Promise { + return withClient( + async (c, id, page) => { + await page.context().route(/^https?:\/\/(?!127\.0\.0\.1)/, (r) => r.abort()); + await fn(c, id); + }, + "about:blank", + { engine }, + ); +} diff --git a/tests/unit/map-fallback.test.ts b/tests/unit/map-fallback.test.ts new file mode 100644 index 0000000..4c8a3ef --- /dev/null +++ b/tests/unit/map-fallback.test.ts @@ -0,0 +1,99 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { registerMapTool } from "../../src/server/tools/map.js"; +import { type DocHandler, type DocServer, serveDocs } from "./helpers/docs-server.js"; +import { callTool } from "./helpers/tool-client.js"; + +// `browser_map` never returns an empty list silently, and a site published under a +// sub-path (https://user.github.io/project/) is found at /sitemap.xml and +// /llms.txt. Measured on a live run: mkdocs-material gave count:0 with no signal. + +const servers: DocServer[] = []; +const serve = (r: Record): DocServer => { + const s = serveDocs(r); + servers.push(s); + return s; +}; +afterAll(() => { + for (const s of servers) s.stop(); +}); +const XML = "application/xml"; +const sitemap = (req: Request, paths: string[]): { contentType: string; body: string } => ({ + contentType: XML, + body: `${paths.map((p) => `${new URL(req.url).origin}${p}`).join("")}`, +}); +const map = (args: Record) => callTool(registerMapTool, "browser_map", args); +const pathsOf = (urls: Array<{ url: string }>): string[] => urls.map((u) => new URL(u.url).pathname); +const triedPaths = (tried: string[]): string[] => tried.map((u) => new URL(u).pathname); + +describe("sub-path sites", () => { + test("a sitemap that lives only under /sub/ is found from a /sub/ URL (2nd attempt, nothing else needed)", async () => { + const s = serve({ "/sub/sitemap.xml": (req) => sitemap(req, ["/sub/a", "/sub/b"]) }); + const r = await map({ url: `${s.origin}/sub/` }); + expect(r.out.source).toBe("sitemap"); + expect(pathsOf(r.out.urls)).toEqual(["/sub/a", "/sub/b"]); + expect(r.out.warning).toBeUndefined(); + expect(r.out.tried).toBeUndefined(); + expect(s.hits.get("/sitemap.xml")).toBe(1); // the origin root was tried first + expect(s.hits.get("/sub/llms.txt")).toBeUndefined(); + }); + + test("an llms.txt that lives only under /sub/ is found too", async () => { + const s = serve({ "/sub/llms.txt": { contentType: "text/plain", body: "- [Intro](/sub/intro)\n" } }); + const r = await map({ url: `${s.origin}/sub` }); // the URL's whole path is the base: /llms.txt + expect(r.out.source).toBe("llms-txt"); + expect(pathsOf(r.out.urls)).toEqual(["/sub/intro"]); + }); + + test("a root URL tries no sub-path files", async () => { + const s = serve({}); + const r = await map({ url: s.origin }); + expect(triedPaths(r.out.tried)).toEqual(["/robots.txt", "/sitemap.xml", "/llms.txt"]); + expect(s.hits.size).toBe(3); + }); + + test("with a path: exactly two extra requests (/sitemap.xml, /llms.txt), then a warning listing every URL tried", async () => { + const s = serve({}); + const r = await map({ url: `${s.origin}/sub/` }); + expect(r.out.count).toBe(0); + expect(r.out.warning).toBe("no_sitemap_found"); + expect(triedPaths(r.out.tried)).toEqual(["/robots.txt", "/sitemap.xml", "/sub/sitemap.xml", "/llms.txt", "/sub/llms.txt"]); + expect(s.hits.size).toBe(5); + }); +}); + +describe("an empty list always says why", () => { + test("no sitemap, no llms.txt → no_sitemap_found", async () => { + const r = await map({ url: (serve({})).origin }); + expect(r.isError).toBe(false); + expect(r.out).toMatchObject({ count: 0, urls: [], warning: "no_sitemap_found" }); + expect(r.out.tried.length).toBeGreaterThan(0); + }); + + test("entries existed but the filters removed them all → all_filtered", async () => { + const s = serve({ "/sitemap.xml": (req) => sitemap(req, ["/docs/a", "/docs/b"]) }); + const r = await map({ url: s.origin, includePaths: ["/blog"] }); + expect(r.out).toMatchObject({ count: 0, warning: "all_filtered" }); + }); + + test("llms.txt links all filtered out → all_filtered, source llms-txt", async () => { + const s = serve({ "/llms.txt": { contentType: "text/plain", body: "- [A](/a)\n" } }); + const r = await map({ url: s.origin, excludePaths: ["/a"] }); + expect(r.out).toMatchObject({ source: "llms-txt", count: 0, warning: "all_filtered" }); + }); + + test("the 50-file budget ended the walk before any page was found → budget_exhausted", async () => { + const s = serve({ + "/sitemap.xml": (req) => ({ contentType: XML, body: `${Array.from({ length: 80 }, (_, i) => `${new URL(req.url).origin}/c${i}.xml`).join("")}` }), + }); + const r = await map({ url: s.origin }); + expect(r.out).toMatchObject({ count: 0, truncated: true, warning: "budget_exhausted" }); + }); + + test("a non-empty result carries neither warning nor tried", async () => { + const s = serve({ "/sitemap.xml": (req) => sitemap(req, ["/x"]) }); + const r = await map({ url: s.origin }); + expect(r.out.count).toBe(1); + expect(r.out.warning).toBeUndefined(); + expect(r.out.tried).toBeUndefined(); + }); +}); diff --git a/tests/unit/map-hardening.test.ts b/tests/unit/map-hardening.test.ts new file mode 100644 index 0000000..dd23710 --- /dev/null +++ b/tests/unit/map-hardening.test.ts @@ -0,0 +1,122 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { pathFilter } from "../../src/agent/map-filter.js"; +import { llmsLinks, parseSitemap } from "../../src/agent/map-parse.js"; +import { MAX_SITEMAP_FILES, mapSite } from "../../src/agent/map-site.js"; +import { splitPassages } from "../../src/extraction/passages-split.js"; +import { type DocHandler, type DocServer, serveDocs } from "./helpers/docs-server.js"; + +// Hardening found by the challenger: bounded work on hostile input (no clock +// assertions — a quadratic/exponential implementation simply cannot finish these +// inputs inside the test's own timeout), the 50-file budget counts attempts, a +// redirecting sitemap cannot leave the origin, malformed percent escapes fail closed. + +const servers: DocServer[] = []; +const serve = (r: Record): DocServer => { + const s = serveDocs(r); + servers.push(s); + return s; +}; +afterAll(() => { + for (const s of servers) s.stop(); +}); +const XML = "application/xml"; +const urlset = (locs: string[]): string => `${locs.map((l) => `${l}`).join("")}`; + +describe("browser_map request budget and origin", () => { + test("the sitemap-file budget counts failed attempts: an index of 500 dead children costs at most MAX_SITEMAP_FILES requests", async () => { + const children = Array.from({ length: 500 }, (_, i) => `/c${i}.xml`); + const s = serve({ + "/sitemap.xml": (req) => ({ contentType: XML, body: `${children.map((c) => `${new URL(req.url).origin}${c}`).join("")}` }), + }); + const r = await mapSite(s.origin); + const childHits = [...s.hits.keys()].filter((p) => /^\/c\d+\.xml$/.test(p)).length; + expect(childHits).toBeLessThanOrEqual(MAX_SITEMAP_FILES); + expect(r.count).toBe(0); + expect(r.truncated).toBe(true); // the budget cut the walk: the list is incomplete and says so + }); + + test("a same-origin sitemap that REDIRECTS to another origin is not used", async () => { + const other = serve({ "/evil.xml": { contentType: XML, body: urlset(["http://leak.test/secret"]) } }); + const s = serve({ + "/robots.txt": (req) => ({ contentType: "text/plain", body: `Sitemap: ${new URL(req.url).origin}/redir.xml\n` }), + "/redir.xml": { status: 302, headers: { location: `http://localhost:${new URL(other.origin).port}/evil.xml` }, body: "" }, + }); + const r = await mapSite(s.origin); + expect(r.urls.map((u) => u.url)).not.toContain("http://leak.test/secret"); + expect(r.count).toBe(0); + }); + + test("robots rules fail closed on a malformed percent escape (it cannot slip past `Disallow`)", async () => { + const s = serve({ + "/robots.txt": { contentType: "text/plain", body: "User-agent: *\nDisallow: /private\n" }, + "/sitemap.xml": (req) => { + const o = new URL(req.url).origin; + return { contentType: XML, body: urlset([`${o}/private/%zz`, `${o}/private/%FF`, `${o}/private/ok`, `${o}/public/a`]) }; + }, + }); + const r = await mapSite(s.origin); + expect(r.urls.map((u) => new URL(u.url).pathname)).toEqual(["/public/a"]); + }); + + test("llms.txt links all filtered out → source stays llms-txt with count 0", async () => { + const s = serve({ "/llms.txt": { contentType: "text/plain", body: "- [A](/a)\n- [B](/b)\n" } }); + const r = await mapSite(s.origin, { includePaths: ["/nothing"] }); + expect(r).toMatchObject({ source: "llms-txt", count: 0, urls: [], warning: "all_filtered" }); + }); +}); + +describe("bounded work on hostile input", () => { + test("parseSitemap: 2 MB of unclosed tags", () => { + expect(parseSitemap(`${"".repeat(500_000)}`).entries).toEqual([]); + }); + + test("parseSitemap: an unclosed and a huge block of repeated { + expect(parseSitemap(`${"".repeat(300_000)}`).entries).toEqual([]); + }); + + test("llmsLinks: a 1 MB run after `](`", () => { + expect(llmsLinks(`](${"a".repeat(1_000_000)}`, "https://x.test/llms.txt").length).toBeLessThanOrEqual(1); // one (huge) relative target + expect(llmsLinks("](a".repeat(300_000), "https://x.test/llms.txt").length).toBeGreaterThan(0); // many `](` starts, none scans into the next + }); + + test("pathFilter: a 7-star glob on a 60-character path", () => { + const keep = pathFilter(["*a*a*a*a*a*a*a*b"]); + expect(keep(`https://x.test/${"a".repeat(60)}`)).toBe(false); + expect(keep(`https://x.test/${"a".repeat(60)}b`)).toBe(true); + }); + + test("splitPassages: a heading line with 200 000 trailing spaces, and a 300 000-character run of `[` in a heading", () => { + expect(splitPassages(`# a${" ".repeat(200_000)}x\nbody`)[0]?.text).toBe("body"); + expect(splitPassages(`# ${"[".repeat(300_000)}\nbody`)[0]?.text).toBe("body"); + }); +}); + +describe("parsers still parse (regression on the rewrite)", () => { + test("sitemap, entities, CDATA, attributes, case, self-closing noise", () => { + const p = parseSitemap(`https://x.test/a?b=1&c=2 2026-01-01 ftp://x.test/no`); + expect(p.kind).toBe("urlset"); + expect(p.entries).toEqual([{ loc: "https://x.test/a?b=1&c=2", lastmod: "2026-01-01" }, { loc: "https://x.test/c" }]); + expect(parseSitemap("https://x.test/s.xml")).toEqual({ kind: "index", entries: [{ loc: "https://x.test/s.xml" }] }); + expect(parseSitemap("spa").kind).toBe("unknown"); + }); + + test("llmsLinks: titles, angle-bracket targets, optional title text, relative, fragment, non-http", () => { + const t = "[A](/a) [B]( \"title\") [C](#frag) [D](mailto:a@b.c) [E](/a#x) [F]( /f )"; + expect(llmsLinks(t, "https://x.test/llms.txt")).toEqual(["https://x.test/a", "https://x.test/b", "https://x.test/f"]); + }); + + test("pathFilter: star in the middle, at both ends, escaped regex chars", () => { + const keep = pathFilter(["/docs/*/intro", "*.html"]); + expect(keep("https://x.test/docs/en/intro")).toBe(true); + expect(keep("https://x.test/a.html")).toBe(true); + expect(keep("https://x.test/aXhtml")).toBe(false); + expect(keep("https://x.test/docs/intro")).toBe(false); + }); + + test("headings: closing hashes, up to 3 leading spaces, 4 spaces is code, fenced # ignored", () => { + const md = " ## Title ##\ntext one\n\n # not a heading\n```\n# in fence\n```\n###### Six\nsix text"; + expect(splitPassages(md).map((c) => c.heading)).toEqual(["Title", "Six"]); + expect(splitPassages(md)[0]?.text).toContain("# not a heading"); + expect(splitPassages(md)[0]?.text).toContain("# in fence"); + }); +}); diff --git a/tests/unit/map-offorigin.test.ts b/tests/unit/map-offorigin.test.ts new file mode 100644 index 0000000..e08be56 --- /dev/null +++ b/tests/unit/map-offorigin.test.ts @@ -0,0 +1,63 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { registerMapTool } from "../../src/server/tools/map.js"; +import { type DocHandler, type DocServer, serveDocs } from "./helpers/docs-server.js"; +import { callTool } from "./helpers/tool-client.js"; + +// sitemaps.org (https://www.sitemaps.org/protocol.html, "Sitemap file location"): all URLs +// in a Sitemap must use the same protocol and reside on the same host as the Sitemap; +// invalid ones "are dropped from further consideration". `browser_map` drops them and +// reports how many (`offOrigin`, absent when 0) — they also never went through a robots check. + +const servers: DocServer[] = []; +const serve = (r: Record): DocServer => { + const s = serveDocs(r); + servers.push(s); + return s; +}; +afterAll(() => { + for (const s of servers) s.stop(); +}); +const map = (args: Record) => callTool(registerMapTool, "browser_map", args); +const urlset = (locs: string[]): string => `${locs.map((l) => `${l}`).join("")}`; + +describe("browser_map drops entries that are not on the sitemap's origin", () => { + test("another host, another protocol and another port are dropped and counted; same-origin ones stay", async () => { + const s = serve({ + "/robots.txt": { contentType: "text/plain", body: "User-agent: *\nDisallow: /private\n" }, + "/sitemap.xml": (req) => { + const o = new URL(req.url).origin; + const port = new URL(req.url).port; + return { + contentType: "application/xml", + body: urlset([`${o}/a`, `http://localhost:${port}/other-host`, `https://127.0.0.1:${port}/other-protocol`, `http://127.0.0.1:${Number(port) + 1}/other-port`, `http://evil.test/private/x`, `${o}/b`, `http://evil.test/private/x`]), + }; + }, + }); + const r = await map({ url: s.origin }); + expect(r.out.urls.map((u: { url: string }) => new URL(u.url).pathname)).toEqual(["/a", "/b"]); + expect(r.out.count).toBe(2); + expect(r.out.offOrigin).toBe(4); // distinct off-origin URLs (the duplicate evil.test one counts once) + }); + + test("offOrigin is absent when every entry is on the origin", async () => { + const s = serve({ "/sitemap.xml": (req) => ({ contentType: "application/xml", body: urlset([`${new URL(req.url).origin}/a`]) }) }); + const r = await map({ url: s.origin }); + expect(r.out.count).toBe(1); + expect("offOrigin" in r.out).toBe(false); + }); + + test("a sitemap made only of off-origin entries is an empty, explained result (not a silent one)", async () => { + const s = serve({ "/sitemap.xml": { contentType: "application/xml", body: urlset(["http://evil.test/a", "http://evil.test/b"]) } }); + const r = await map({ url: s.origin }); + expect(r.out).toMatchObject({ count: 0, offOrigin: 2, warning: "all_filtered" }); + expect(r.out.tried.length).toBeGreaterThan(0); + }); + + test("llms.txt links to other hosts are dropped and counted the same way", async () => { + const s = serve({ "/llms.txt": (req) => ({ contentType: "text/plain", body: `- [Doc](/doc)\n- [Repo](https://github.com/x/y)\n- [Abs](${new URL(req.url).origin}/abs)\n` }) }); + const r = await map({ url: s.origin }); + expect(r.out.source).toBe("llms-txt"); + expect(r.out.urls.map((u: { url: string }) => new URL(u.url).pathname)).toEqual(["/doc", "/abs"]); + expect(r.out.offOrigin).toBe(1); + }); +}); diff --git a/tests/unit/map-robots-files.test.ts b/tests/unit/map-robots-files.test.ts new file mode 100644 index 0000000..4235b9f --- /dev/null +++ b/tests/unit/map-robots-files.test.ts @@ -0,0 +1,78 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { registerMapTool } from "../../src/server/tools/map.js"; +import { type DocHandler, type DocServer, serveDocs } from "./helpers/docs-server.js"; +import { callTool } from "./helpers/tool-client.js"; + +// With robots respected, `browser_map` must not fetch a sitemap / llms.txt URL that +// robots.txt disallows — EXCEPT the sitemaps the site itself advertises in `Sitemap:` +// lines (and the child sitemaps those list). The skip is reported, never silent. + +const servers: DocServer[] = []; +const serve = (r: Record): DocServer => { + const s = serveDocs(r); + servers.push(s); + return s; +}; +afterAll(() => { + for (const s of servers) s.stop(); +}); +const XML = "application/xml"; +const urlset = (o: string, paths: string[]): string => `${paths.map((p) => `${o}${p}`).join("")}`; +const map = (args: Record) => callTool(registerMapTool, "browser_map", args); +const origin = (req: Request): string => new URL(req.url).origin; + +/** A site whose robots disallows everything and which also serves every candidate file. */ +const closed = (robots: string): Record => ({ + "/robots.txt": (req) => ({ contentType: "text/plain", body: robots.replaceAll("{O}", origin(req)) }), + "/sitemap.xml": (req) => ({ contentType: XML, body: urlset(origin(req), ["/a"]) }), + "/docs/sitemap.xml": (req) => ({ contentType: XML, body: urlset(origin(req), ["/docs/b"]) }), + "/llms.txt": { contentType: "text/plain", body: "- [A](/a)\n" }, + "/docs/llms.txt": { contentType: "text/plain", body: "- [B](/docs/b)\n" }, +}); + +describe("browser_map does not fetch what robots.txt disallows", () => { + test("Disallow: / → none of the 4 candidate files is requested; the result says so", async () => { + const s = serve(closed("User-agent: *\nDisallow: /\n")); + const r = await map({ url: `${s.origin}/docs/` }); + expect([...s.hits.keys()]).toEqual(["/robots.txt"]); + expect(r.out).toMatchObject({ count: 0, skippedByRobots: 4, warning: "blocked_by_robots" }); + expect(r.out.tried).toEqual([`${s.origin}/robots.txt`]); // `tried` lists requests actually made + }); + + test("a sitemap advertised in robots Sitemap: lines is fetched even under Disallow: /private", async () => { + const s = serve({ + "/robots.txt": (req) => ({ contentType: "text/plain", body: `User-agent: *\nDisallow: /private\nSitemap: ${origin(req)}/private/sitemap.xml\n` }), + "/private/sitemap.xml": (req) => ({ contentType: XML, body: `${origin(req)}/private/child.xml` }), + "/private/child.xml": (req) => ({ contentType: XML, body: urlset(origin(req), ["/pub/a", "/private/secret"]) }), + }); + const r = await map({ url: s.origin }); + // the advertised index and the child it lists are fetched; the listed URL under /private is still filtered + expect(r.out.urls.map((u: { url: string }) => new URL(u.url).pathname)).toEqual(["/pub/a"]); + expect(s.hits.get("/private/sitemap.xml")).toBe(1); + expect(s.hits.get("/private/child.xml")).toBe(1); + expect(r.out.skippedByRobots).toBeUndefined(); + }); + + test("an UNadvertised fallback file under a disallowed path is skipped while the allowed ones are still tried", async () => { + const s = serve(closed("User-agent: *\nDisallow: /docs/\n")); + const r = await map({ url: `${s.origin}/docs/` }); + expect(r.out.source).toBe("sitemap"); + expect(r.out.urls.map((u: { url: string }) => new URL(u.url).pathname)).toEqual(["/a"]); + expect(s.hits.get("/docs/sitemap.xml")).toBeUndefined(); + }); + + test("respectRobots:false fetches them anyway (opt-out unchanged)", async () => { + const s = serve(closed("User-agent: *\nDisallow: /\n")); + const r = await map({ url: s.origin, respectRobots: false }); + expect(s.hits.get("/sitemap.xml")).toBe(1); + expect(r.out.count).toBe(1); + expect(r.out.skippedByRobots).toBeUndefined(); + }); + + test("no robots.txt at all → nothing is skipped", async () => { + const s = serve({ "/sitemap.xml": (req) => ({ contentType: XML, body: urlset(origin(req), ["/a"]) }) }); + const r = await map({ url: s.origin }); + expect(r.out.count).toBe(1); + expect(r.out.skippedByRobots).toBeUndefined(); + }); +}); diff --git a/tests/unit/map-site.test.ts b/tests/unit/map-site.test.ts new file mode 100644 index 0000000..c18f76a --- /dev/null +++ b/tests/unit/map-site.test.ts @@ -0,0 +1,148 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { gzipSync } from "node:zlib"; +import { registerMapTool } from "../../src/server/tools/map.js"; +import { type DocServer, type DocHandler, serveDocs } from "./helpers/docs-server.js"; +import { callTool } from "./helpers/tool-client.js"; + +// `browser_map` through the real registered tool (in-memory MCP client) against +// local sites: sitemap index + gzip child, robots Sitemap lines, llms.txt, filters. + +const XML = "application/xml"; +const originOf = (req: Request): string => new URL(req.url).origin; +const urlset = (items: string[]): string => `${items.join("")}`; +const page = (loc: string, lastmod?: string): string => `${loc}${lastmod ? `${lastmod}` : ""}`; + +/** Routes for the main site: robots with Sitemap lines → index → plain + gzip children. */ +const main = (): Record => ({ + "/robots.txt": (req) => ({ + contentType: "text/plain", + body: `User-agent: *\nDisallow: /private/\nSitemap: ${originOf(req)}/sitemap_index.xml\nSitemap: https://elsewhere.invalid/other.xml\n`, + }), + "/sitemap_index.xml": (req) => ({ + contentType: XML, + body: `${originOf(req)}/sm-docs.xml${originOf(req)}/sm-blog.xml.gzhttp://localhost:${new URL(req.url).port}/cross.xml`, + }), + "/sm-docs.xml": (req) => ({ + contentType: XML, + body: urlset([page(`${originOf(req)}/docs/a`, "2026-01-02"), page(`${originOf(req)}/docs/b`), page(`${originOf(req)}/private/secret`), page(`${originOf(req)}/docs/c?x=1&y=2`), ``]), + }), + "/sm-blog.xml.gz": (req) => ({ contentType: "application/gzip", body: new Uint8Array(gzipSync(urlset([page(`${originOf(req)}/blog/1`), page(`${originOf(req)}/blog/2`)]))) }), + "/cross.xml": { contentType: XML, body: urlset([page("https://x.test/never")]) }, +}); + +let site: DocServer; +const servers: DocServer[] = []; +const serve = (r: Record): DocServer => { + const s = serveDocs(r); + servers.push(s); + return s; +}; +beforeAll(() => { + site = serve(main()); +}); +afterAll(() => { + for (const s of servers) s.stop(); +}); + +const map = (args: Record) => callTool(registerMapTool, "browser_map", args); +const paths = (urls: Array<{ url: string }>): string[] => urls.map((u) => new URL(u.url).pathname + new URL(u.url).search); + +describe("browser_map — sitemap index via robots.txt Sitemap lines", () => { + test("lists every page of the index (plain + gzip child), decodes entities/CDATA, keeps lastmod, drops robots-disallowed", async () => { + const r = await map({ url: `${site.origin}/anything/here` }); + expect(r.isError).toBe(false); + expect(r.out.source).toBe("sitemap"); + expect(paths(r.out.urls)).toEqual(["/docs/a", "/docs/b", "/docs/c?x=1&y=2", "/docs/cdata", "/blog/1", "/blog/2"]); + expect(r.out.urls[0]).toEqual({ url: `${site.origin}/docs/a`, lastmod: "2026-01-02" }); + expect(r.out.urls[1]).toEqual({ url: `${site.origin}/docs/b` }); // no lastmod key at all + expect(r.out.count).toBe(6); + expect(r.out.truncated).toBeUndefined(); + }); + + test("a child sitemap on another origin and a foreign robots Sitemap line are never fetched", async () => { + await map({ url: site.origin }); + expect(site.hits.get("/cross.xml")).toBeUndefined(); + }); + + test("respectRobots:false keeps the robots-disallowed URL", async () => { + const r = await map({ url: site.origin, respectRobots: false }); + expect(paths(r.out.urls)).toContain("/private/secret"); + expect(r.out.count).toBe(7); + }); +}); + +describe("browser_map — filters and limit", () => { + test("includePaths: a bare path matches itself and everything below it; * is a wildcard", async () => { + expect(paths((await map({ url: site.origin, includePaths: ["/docs"] })).out.urls)).toEqual(["/docs/a", "/docs/b", "/docs/c?x=1&y=2", "/docs/cdata"]); + expect(paths((await map({ url: site.origin, includePaths: ["/blog/*"] })).out.urls)).toEqual(["/blog/1", "/blog/2"]); + expect(paths((await map({ url: site.origin, includePaths: ["/docs/*", "/blog/1"] })).out.urls)).toHaveLength(5); + }); + + test("excludePaths removes matches; combined with includePaths", async () => { + const r = await map({ url: site.origin, includePaths: ["/docs"], excludePaths: ["/docs/b", "*/cdata"] }); + expect(paths(r.out.urls)).toEqual(["/docs/a", "/docs/c?x=1&y=2"]); + }); + + test("limit cuts the list and says so (truncated:true); under the limit there is no flag", async () => { + const cut = await map({ url: site.origin, limit: 2 }); + expect(cut.out.count).toBe(2); + expect(cut.out.urls).toHaveLength(2); + expect(cut.out.truncated).toBe(true); + const exact = await map({ url: site.origin, limit: 6 }); + expect(exact.out.count).toBe(6); + expect(exact.out.truncated).toBeUndefined(); + }); +}); + +describe("browser_map — fallbacks", () => { + test("no robots Sitemap line → /sitemap.xml is tried", async () => { + const s = serve({ "/sitemap.xml": (req) => ({ contentType: XML, body: urlset([page(`${originOf(req)}/p1`), page(`${originOf(req)}/p2`)]) }) }); + const r = await map({ url: s.origin }); + expect(r.out.source).toBe("sitemap"); + expect(paths(r.out.urls)).toEqual(["/p1", "/p2"]); + }); + + test("no sitemap at all (an HTML catch-all on /sitemap.xml is not one) → llms.txt links, relative and absolute", async () => { + const s = serve({ + "/sitemap.xml": { body: "SPA shell" }, + "/llms.txt": (req) => ({ contentType: "text/plain", body: `# Site\n\n> summary\n\n## Docs\n- [Intro](/docs/intro): start here\n- [API](${originOf(req)}/docs/api)\n- [Dup](/docs/intro)\n- [Mail](mailto:a@b.c)\n` }), + }); + const r = await map({ url: s.origin }); + expect(r.out.source).toBe("llms-txt"); + expect(paths(r.out.urls)).toEqual(["/docs/intro", "/docs/api"]); + expect(r.out.urls[0]).toEqual({ url: `${s.origin}/docs/intro` }); + }); + + test("nothing found → empty list, not an error", async () => { + const s = serve({}); + const r = await map({ url: s.origin }); + expect(r.isError).toBe(false); + expect(r.out.count).toBe(0); + expect(r.out.urls).toEqual([]); + }); +}); + +describe("browser_map — guards", () => { + const prev = process.env.FUSE_BLOCK_PRIVATE_NETS; + afterAll(() => { + if (prev === undefined) delete process.env.FUSE_BLOCK_PRIVATE_NETS; + else process.env.FUSE_BLOCK_PRIVATE_NETS = prev; + }); + + test("the SSRF guard applies: a loopback target is refused with its code, nothing is fetched", async () => { + const s = serve(main()); + process.env.FUSE_BLOCK_PRIVATE_NETS = "1"; + const r = await map({ url: s.origin }); + delete process.env.FUSE_BLOCK_PRIVATE_NETS; + expect(r.isError).toBe(true); + expect(r.out.code).toBe("blocked_private_network"); + expect(s.hits.size).toBe(0); + }); + + test("a non-http(s) or malformed url is a clean error", async () => { + for (const url of ["ftp://x.test/", "not a url"]) { + const r = await map({ url }); + expect(r.isError).toBe(true); + } + }); +}); diff --git a/tests/unit/output-budget-file.test.ts b/tests/unit/output-budget-file.test.ts new file mode 100644 index 0000000..154a76f --- /dev/null +++ b/tests/unit/output-budget-file.test.ts @@ -0,0 +1,87 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { budgetClient, call, ITEMS, TEXT } from "./helpers/budget-client.js"; + +let dir = ""; +const saved = { out: process.env.FUSE_OUTPUT_DIR, confine: process.env.FUSE_CONFINE_WRITES }; +beforeEach(() => { + dir = realpathSync(mkdtempSync(join(tmpdir(), "fuse-budget-"))); + process.env.FUSE_OUTPUT_DIR = dir; + delete process.env.FUSE_CONFINE_WRITES; +}); +afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + for (const [k, v] of [ + ["FUSE_OUTPUT_DIR", saved.out], + ["FUSE_CONFINE_WRITES", saved.confine], + ] as const) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } +}); + +describe("budgetResult: outputMode file", () => { + test("writes the full text under FUSE_OUTPUT_DIR and returns path, bytes, preview", async () => { + const out = (await call(await budgetClient(), "big_text", { outputMode: "file" })).structuredContent; + expect(out.outputMode).toBe("file"); + const path = out.path as string; + expect(path.startsWith(join(dir, "offload"))).toBe(true); + expect(readFileSync(path, "utf8")).toBe(TEXT); + expect(out.bytes).toBe(statSync(path).size); + expect(typeof out.preview).toBe("string"); + expect(TEXT.startsWith(out.preview as string)).toBe(true); + expect((out.preview as string).length).toBeLessThan(TEXT.length); + expect(out.url).toBe("https://x.test/"); + expect(out.text).toBe(out.preview); + }); + + test("same content writes the same file (content-addressed, no clock)", async () => { + const c = await budgetClient(); + const a = (await call(c, "big_text", { outputMode: "file" })).structuredContent.path; + const b = (await call(c, "big_text", { outputMode: "file" })).structuredContent.path; + expect(a).toBe(b); + }); + + test("an array field is written as JSON and replaced by an empty array", async () => { + const out = (await call(await budgetClient(), "big_list", { outputMode: "file" })).structuredContent; + expect(JSON.parse(readFileSync(out.path as string, "utf8"))).toEqual(ITEMS); + expect(out.elements).toEqual([]); + expect(out.count).toBe(ITEMS.length); + }); + + test("FUSE_CONFINE_WRITES outside the output dir: nothing written, result stays inline with outputError", async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "fuse-conf-"))); + process.env.FUSE_CONFINE_WRITES = root; + try { + const out = (await call(await budgetClient(), "big_text", { outputMode: "file" })).structuredContent; + expect(out.outputError).toBe("path_outside_confinement"); + expect(out.text).toBe(TEXT); + expect(out.path).toBeUndefined(); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("a field that is neither text nor a list: nothing written, outputError says why, payload kept", async () => { + const c = await budgetClient(); + for (const tool of ["scalar", "absent_field"]) { + const out = (await call(c, tool, { outputMode: "file" })).structuredContent; + expect(out.outputError, tool).toBe("field_not_offloadable"); + expect(out.count, tool).toBe(3); + expect(out.path, tool).toBeUndefined(); + } + }); + + test("the same payload without outputMode:'file' is untouched (no outputError)", async () => { + const out = (await call(await budgetClient(), "scalar", { maxTokens: 10 })).structuredContent; + expect(out).toEqual({ count: 3 }); + }); + + test("FUSE_CONFINE_WRITES covering the output dir: the offload is written", async () => { + process.env.FUSE_CONFINE_WRITES = dir; + const out = (await call(await budgetClient(), "big_text", { outputMode: "file" })).structuredContent; + expect(readFileSync(out.path as string, "utf8")).toBe(TEXT); + }); +}); diff --git a/tests/unit/output-budget.test.ts b/tests/unit/output-budget.test.ts new file mode 100644 index 0000000..7f708d6 --- /dev/null +++ b/tests/unit/output-budget.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, test } from "bun:test"; +import { jsonResult } from "../../src/server/result.js"; +import { estimateTokens } from "../../src/server/token-estimate.js"; +import { budgetClient, call, ITEMS, MULTIBYTE, TEXT, TRICKY } from "./helpers/budget-client.js"; + +describe("budgetResult: defaults off", () => { + test("no budget params: result is byte-identical to jsonResult", async () => { + const c = await budgetClient(); + const r = await call(c, "big_text"); + expect(r.content).toEqual(jsonResult({ url: "https://x.test/", text: TEXT }).content); + expect(r.structuredContent).toEqual({ url: "https://x.test/", text: TEXT }); + const l = await call(c, "big_list"); + expect(l.content).toEqual(jsonResult({ count: ITEMS.length, elements: ITEMS }).content); + }); + + test("outputMode:'inline' alone is also a no-op", async () => { + const r = await call(await budgetClient(), "big_text", { outputMode: "inline" }); + expect(r.structuredContent).toEqual({ url: "https://x.test/", text: TEXT }); + }); +}); + +describe("budgetResult: maxTokens on a string field", () => { + test("stays within budget and pages losslessly via nextOffset", async () => { + const c = await budgetClient(); + let offset = 0; + let rebuilt = ""; + let pages = 0; + for (;;) { + const out = (await call(c, "big_text", { maxTokens: 120, offset })).structuredContent; + const text = out.text as string; + expect(estimateTokens(Buffer.byteLength(text, "utf8"))).toBeLessThanOrEqual(120); + rebuilt += text; + pages++; + if (out.nextOffset === undefined) break; + expect(out.nextOffset).toBe(offset + text.length); + expect(text.length).toBeGreaterThan(0); + offset = out.nextOffset as number; + } + expect(pages).toBeGreaterThan(1); + expect(rebuilt).toBe(TEXT); + }); + + test("clean cut: a truncated page ends right before a paragraph break, not mid-word", async () => { + const out = (await call(await budgetClient(), "big_text", { maxTokens: 120 })).structuredContent; + const text = out.text as string; + expect(out.nextOffset).toBe(text.length); + expect(out.truncated).toBeUndefined(); // the budget never writes `truncated`: pagination = nextOffset present + expect(TEXT.slice(text.length, text.length + 2)).toBe("\n\n"); + }); + + test("fits: no truncated flag, approxTokens reported", async () => { + const out = (await call(await budgetClient(), "big_text", { maxTokens: 100000 })).structuredContent; + expect(out.truncated).toBeUndefined(); + expect(out.text).toBe(TEXT); + expect(typeof out.approxTokens).toBe("number"); + }); + + test("multi-byte text is never split mid-character and stays within the byte budget", async () => { + const c = await budgetClient(); + let offset = 0; + let rebuilt = ""; + for (;;) { + const out = (await call(c, "multibyte", { maxTokens: 25, offset })).structuredContent; + const t = out.text as string; + expect(t).not.toContain("�"); + expect(Buffer.byteLength(t, "utf8")).toBeLessThanOrEqual(100); + rebuilt += t; + if (out.nextOffset === undefined) break; + offset = out.nextOffset as number; + } + expect(rebuilt).toBe(MULTIBYTE); + }); + + test("a literal U+FFFD and a lone surrogate in the source are kept exactly and the byte cap holds", async () => { + const c = await budgetClient(); + let offset = 0; + let rebuilt = ""; + for (;;) { + const out = (await call(c, "tricky", { maxTokens: 1, offset })).structuredContent; + const t = out.text as string; + expect(Buffer.byteLength(t, "utf8")).toBeLessThanOrEqual(4); + rebuilt += t; + if (out.nextOffset === undefined) break; + expect(out.nextOffset as number).toBeGreaterThan(offset); + offset = out.nextOffset as number; + } + expect(rebuilt).toBe(TRICKY); + }); + + test("an offset past the end returns an empty, non-truncated page", async () => { + const out = (await call(await budgetClient(), "big_text", { maxTokens: 50, offset: TEXT.length + 10 })).structuredContent; + expect(out.text).toBe(""); + expect(out.truncated).toBeUndefined(); + }); +}); + +describe("budgetResult: maxTokens on an array field", () => { + test("pages whole items and always makes progress", async () => { + const c = await budgetClient(); + let offset = 0; + const seen: unknown[] = []; + for (;;) { + const out = (await call(c, "big_list", { maxTokens: 40, offset })).structuredContent; + const els = out.elements as unknown[]; + expect(els.length).toBeGreaterThan(0); + seen.push(...els); + if (out.nextOffset === undefined) break; + expect(out.nextOffset).toBe(offset + els.length); + offset = out.nextOffset as number; + } + expect(seen).toEqual(ITEMS); + }); + + test("a list holding an undefined item pages without throwing", async () => { + const out = (await call(await budgetClient(), "with_undefined", { maxTokens: 1 })).structuredContent; + expect(out.nextOffset).toBe(1); + }); + + test("a budget smaller than one item still returns that item", async () => { + const out = (await call(await budgetClient(), "big_list", { maxTokens: 1 })).structuredContent; + expect((out.elements as unknown[]).length).toBe(1); + expect(out.nextOffset).toBe(1); + }); +}); + +describe("budgetResult: a tool's own `truncated` keeps its meaning", () => { + test("own truncated:false stays false when maxTokens cuts (pagination = nextOffset present)", async () => { + const out = (await call(await budgetClient(), "own_false", { maxTokens: 50 })).structuredContent; + expect(out.truncated).toBe(false); + expect(typeof out.nextOffset).toBe("number"); + expect((out.text as string).length).toBeLessThan(TEXT.length); + }); + + test("own truncated:true stays true when maxTokens does not cut (no nextOffset)", async () => { + const out = (await call(await budgetClient(), "own_true", { maxTokens: 100000 })).structuredContent; + expect(out.truncated).toBe(true); + expect(out.nextOffset).toBeUndefined(); + expect(out.text).toBe("short"); + }); + + test("without budget params a payload with its own truncated is byte-identical", async () => { + const c = await budgetClient(); + for (const [tool, payload] of [["own_false", { truncated: false, text: TEXT }], ["own_true", { truncated: true, text: "short" }]] as const) { + expect((await call(c, tool)).content).toEqual(jsonResult(payload).content); + } + }); +}); diff --git a/tests/unit/passages-fence.test.ts b/tests/unit/passages-fence.test.ts new file mode 100644 index 0000000..29926b4 --- /dev/null +++ b/tests/unit/passages-fence.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, test } from "bun:test"; +import { splitPassages } from "../../src/extraction/passages-split.js"; + +// CommonMark fenced code blocks: a closing fence uses the SAME character as the opening +// one, is at least as long, and carries no info string. A `# line` inside a fence is code, +// never a heading. + +const headings = (md: string): string[] => splitPassages(md).map((c) => c.heading); +const bodyOf = (md: string, heading: string): string => splitPassages(md).find((c) => c.heading === heading)?.text ?? ""; + +describe("fenced code blocks and headings", () => { + test("a ~~~ line inside a ``` block does not close it", () => { + const md = "```\n~~~\n# not a heading\n```\n# Real\nreal body"; + expect(headings(md)).toEqual(["", "Real"]); + expect(bodyOf(md, "")).toContain("# not a heading"); + }); + + test("a ``` line inside a ~~~ block does not close it", () => { + const md = "~~~\n```\n# not a heading\n~~~\n# Real\nreal body"; + expect(headings(md)).toEqual(["", "Real"]); + }); + + test("a shorter fence does not close a longer one; an equal or longer one does", () => { + const md = "````\n```\n# still code\n````\n# Out\nout body"; + expect(headings(md)).toEqual(["", "Out"]); + expect(bodyOf(md, "")).toContain("# still code"); + expect(headings("```\n# code\n`````\n# After\nbody")).toEqual(["", "After"]); // longer closes + }); + + test("a fence line with an info string does not close a block", () => { + const md = "```\n```js\n# code\n```\n# Real\nbody"; + expect(headings(md)).toEqual(["", "Real"]); + }); + + test("a backtick line whose info string contains a backtick is inline code, not a fence (CommonMark 0.31.2)", () => { + const md = "```js``` is inline code\n\n# Install\ninstall body\n\n# Usage\nusage body"; + expect(headings(md)).toEqual(["", "Install", "Usage"]); + expect(headings("``` `x`\n# Real\nbody")).toEqual(["", "Real"]); + }); + + test("a tilde fence may carry backticks in its info string", () => { + expect(headings("~~~ `x`\n# code\n~~~\n# Real\nbody")).toEqual(["", "Real"]); + expect(bodyOf("~~~ `x`\n# code\n~~~\n# Real\nbody", "")).toContain("# code"); + }); + + test("an unterminated fence swallows the rest (no heading inside it)", () => { + expect(headings("intro\n```\n# code\n# more code")).toEqual([""]); + }); + + test("ordinary headings around a well-formed fence are unchanged", () => { + expect(headings("# A\na\n```\n# c\n```\n## B\nb")).toEqual(["A", "B"]); + }); +}); diff --git a/tests/unit/probe-proxy-report.test.ts b/tests/unit/probe-proxy-report.test.ts new file mode 100644 index 0000000..741c236 --- /dev/null +++ b/tests/unit/probe-proxy-report.test.ts @@ -0,0 +1,87 @@ +/** + * Which challenge results make a probe report its pool proxy as blocked + * (`reportBlockedProxy`, the code behind `probe-run.ts`'s call). Challenges come + * from the real `detectChallenges` on rendered AWS WAF fixtures, the reporter is a spy. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Page } from "playwright"; +import { resolveConfig } from "../../src/agent/config.js"; +import { reportBlockedProxy } from "../../src/agent/probe-run.js"; +import { detectChallenges } from "../../src/extraction/challenges.js"; +import { SessionManager } from "../../src/session/manager.js"; + +const FIX = join(import.meta.dir, "../fixtures/challenges"); +const sessions = new SessionManager(); +let page: Page; +let sessionId = ""; + +beforeAll(async () => { + const s = await sessions.open(resolveConfig({ headless: true, engine: "patchright" })); + page = s.page; + sessionId = s.id; +}, 120_000); +afterAll(async () => { + await sessions.close(sessionId); +}); + +/** Render `body` as the document (sub-resources aborted) and run the real detector on it. */ +async function challengesOfHtml(body: string, status: number) { + await page.unroute("**/*"); + await page.route("**/*", (r) => + r.request().resourceType() === "document" ? r.fulfill({ status, contentType: "text/html", body }) : r.abort(), + ); + await page.goto("https://www.example.com/", { waitUntil: "domcontentloaded" }); + return detectChallenges(page, String(await page.evaluate("document.body ? document.body.innerText : ''"))); +} + +const challengesOf = (file: string, status: number) => challengesOfHtml(readFileSync(join(FIX, file), "utf8"), status); + +const pool = { proxySource: "pool", proxyUrl: "http://10.0.0.1:8080" } as const; + +/** Run the real decision with a spy reporter; returns the URLs it was called with. */ +function reported(config: Parameters[0], challenges: Parameters[1]): string[] { + const calls: string[] = []; + reportBlockedProxy(config, challenges, (u) => calls.push(u)); + return calls; +} + +describe("pool proxy is reported on a WAF block page", () => { + test("AWS WAF CAPTCHA interstitial -> reported", async () => { + expect(reported(pool, await challengesOf("aws-waf-captcha-synthetic.html", 405))).toEqual([pool.proxyUrl]); + }); + + test("AWS WAF Challenge interstitial (awsWaf only, no captcha) -> reported", async () => { + const c = await challengesOf("aws-waf-challenge-synthetic.html", 202); + expect(c.captcha).toBe(false); + expect(reported(pool, c)).toEqual([pool.proxyUrl]); + }); + + test("Cloudflare hard-block page -> reported", async () => { + expect(reported(pool, await challengesOf("cloudflare-error-1020-synthetic.html", 403))).toEqual([pool.proxyUrl]); + }); +}); + +describe("no report when it must not fire", () => { + test("not a pool proxy", async () => { + const c = await challengesOf("aws-waf-captcha-synthetic.html", 405); + expect(reported({ proxySource: "env", proxyUrl: pool.proxyUrl } as never, c)).toEqual([]); + expect(reported({ proxySource: "pool", proxyUrl: null } as never, c)).toEqual([]); + }); + + test("normal page using the AWS WAF integration SDK (getToken) is not a block", async () => { + const body = + `` + + ``; + expect(reported(pool, await challengesOfHtml(body, 200))).toEqual([]); + }); + + test("clean page", async () => { + expect(reported(pool, await challengesOfHtml("

hello

", 200))).toEqual([]); + }); + + test("challenges not detected ({})", () => { + expect(reported(pool, {})).toEqual([]); + }); +}); diff --git a/tests/unit/safe-actions-registry.test.ts b/tests/unit/safe-actions-registry.test.ts new file mode 100644 index 0000000..85d7fd6 --- /dev/null +++ b/tests/unit/safe-actions-registry.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, test } from "bun:test"; +import type { Page } from "playwright"; +import { registryFor } from "../../src/actions/ref-registry.js"; +import { guardRef } from "../../src/actions/ref-guard.js"; +import { SENSITIVE_RULES, sensitiveCategory } from "../../src/actions/sensitive-vocab.js"; +import type { InteractiveElement } from "../../src/interfaces/extraction.js"; + +const el = (ref: string, text: string, frame = 0): InteractiveElement => ({ + index: 0, + ref, + frame: frame || undefined, + tag: "button", + text, + role: null, + id: null, + name: null, + type: null, + href: null, + visible: true, + box: { x: 0, y: 0, width: 1, height: 1 }, +}); + +describe("RefRegistry", () => { + test("a page without an agent-facing snapshot has no valid refs (new tab, recovered page)", async () => { + const page = {} as Page; + expect(registryFor(page).active).toBe(false); + const r = await guardRef(page, "3"); + expect(r?.error).toBe("ref_stale"); + expect(r?.reason).toBe("no_snapshot"); + }); + + test("begin() bumps the generation and replaces entries; merge() adds without refreshing", () => { + const reg = registryFor({} as Page); + expect(reg.begin({ elements: [el("0", "Cancel")], docs: { 0: "d1" } })).toBe(1); + reg.merge({ elements: [el("5", "New"), el("0", "Renamed")], docs: { 0: "d1" } }); + expect(reg.get("5")?.text).toBe("New"); + expect(reg.get("0")?.text).toBe("Renamed"); + expect(reg.begin({ elements: [el("5", "New")], docs: { 0: "d1" } })).toBe(2); + expect(reg.get("0")).toBeUndefined(); + }); + + test("a changed document token drops that frame's refs", () => { + const reg = registryFor({} as Page); + reg.begin({ elements: [el("0", "A"), el("1:0", "InFrame", 1)], docs: { 0: "d1", 1: "f1" } }); + reg.merge({ elements: [], docs: { 1: "f2" } }); + expect(reg.get("1:0")).toBeUndefined(); + expect(reg.get("0")?.text).toBe("A"); + expect(reg.docOf(1)).toBe("f2"); + }); + + test("guardRef refuses a ref that is not in the last snapshot (frame gone -> ref_stale)", async () => { + const page = { frames: () => [] } as unknown as Page; + registryFor(page).begin({ elements: [el("0", "A")], docs: { 0: "d1" } }); + const unknown = await guardRef(page, "9"); + expect(unknown?.error).toBe("ref_stale"); + expect(unknown?.reason).toBe("not_in_snapshot"); + const gone = await guardRef(page, "0"); + expect(gone?.error).toBe("ref_stale"); + expect(gone?.reason).toBe("element_gone"); + expect(String(gone?.hint)).toContain("browser_snapshot"); + }); +}); + +describe("sensitive vocabulary", () => { + test("data table, destructive and payment, EN and FR", () => { + expect(SENSITIVE_RULES.length).toBeGreaterThan(1); + expect(sensitiveCategory("Delete account")).toBe("destructive"); + expect(sensitiveCategory("Cancel subscription")).toBe("destructive"); + expect(sensitiveCategory("Supprimer le compte")).toBe("destructive"); + expect(sensitiveCategory("Pay now")).toBe("payment"); + expect(sensitiveCategory("Place your order")).toBe("payment"); + }); + + test("unsubscribe (EN/FR) and remove-with-object are destructive", () => { + for (const t of ["Unsubscribe", "Se désabonner", "Remove account", "Remove all", "Erase history", "Effacer le compte"]) { + expect(sensitiveCategory(t)).toBe("destructive"); + } + }); + + test("French elision and filter-like objects", () => { + expect(sensitiveCategory("Effacer l'historique")).toBe("destructive"); + expect(sensitiveCategory("Effacer l’historique")).toBe("destructive"); + expect(sensitiveCategory("Supprimer le compte")).toBe("destructive"); + for (const t of ["Supprimer le filtre", "Supprimer la recherche", "Delete filter", "Delete this tag"]) { + expect(sensitiveCategory(t)).toBeNull(); + } + }); + + test("newsletter Subscribe and bare Remove/Effacer are not sensitive", () => { + for (const t of ["Subscribe", "Remove filter", "Remove tag", "Effacer", "Effacer le filtre"]) { + expect(sensitiveCategory(t)).toBeNull(); + } + }); + + test("harmless controls do not match", () => { + for (const t of ["Cancel", "Save", "Search", "Sign in", "Confirm email", "Undelete"]) { + expect(sensitiveCategory(t)).toBeNull(); + } + }); +}); diff --git a/tests/unit/screenshot-tool.test.ts b/tests/unit/screenshot-tool.test.ts index 1ac84fa..548da20 100644 --- a/tests/unit/screenshot-tool.test.ts +++ b/tests/unit/screenshot-tool.test.ts @@ -11,7 +11,9 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import type { Page } from "playwright"; import { z } from "zod"; +import { registryFor } from "../../src/actions/ref-registry.js"; import { screenshotOutputShape } from "../../src/server/tools/screenshot-result.js"; import { registerScreenshotTool } from "../../src/server/tools/screenshot.js"; import type { SessionManager } from "../../src/session/manager.js"; @@ -33,11 +35,12 @@ function mockServer(): { server: McpServer; getHandler: () => Handler } { /** Locator/Frame/Page fakes covering ref-locator, snapshot, and annotate paths. */ function fakePage() { - const locator = { count: async () => 1, screenshot: async () => Buffer.from("PNG-ELEMENT") }; + const live = { tag: "button", role: null, id: null, name: null, type: null, href: null, text: "Go", title: null, doc: "d1", owned: true, editable: false }; + const locator = { count: async () => 1, screenshot: async () => Buffer.from("PNG-ELEMENT"), evaluate: async () => live }; const frame = { - locator: () => ({ first: () => locator }), + locator: () => ({ first: () => locator, count: async () => 1 }), isDetached: () => false, - evaluate: async () => [], + evaluate: async () => ({ count: 1, live }), }; const page = { frames: () => [frame], @@ -63,7 +66,12 @@ function fakeSessions(page: ReturnType): SessionManager { describe("browser_screenshot outputSchema", () => { test("element ref branch: structuredContent parses against the schema", async () => { const { server, getHandler } = mockServer(); - registerScreenshotTool(server, fakeSessions(fakePage())); + const page = fakePage(); + registryFor(page as unknown as Page).begin({ + elements: [{ index: 0, ref: "3", tag: "button", text: "Go", role: null, id: null, name: null, type: null, href: null, visible: true, box: { x: 0, y: 0, width: 1, height: 1 } }], + docs: { 0: "d1" }, + }); + registerScreenshotTool(server, fakeSessions(page)); const res = await getHandler()({ sessionId: "s", ref: 3 }); expect(res.structuredContent).toBeDefined(); expect(() => outputSchema.parse(res.structuredContent)).not.toThrow(); diff --git a/tests/unit/serp-extract.test.ts b/tests/unit/serp-extract.test.ts new file mode 100644 index 0000000..1f99665 --- /dev/null +++ b/tests/unit/serp-extract.test.ts @@ -0,0 +1,119 @@ +/** + * `extractSerp` / `collectSerp` against a real Chromium page. Google is never + * contacted: `page.route` serves a REAL Google results page captured + * 2026-11-11 (sanitized, `tests/fixtures/serp/`) and small synthetic pages, so + * `a.href` resolves against a real `https://www.google.com/...` origin. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Page } from "playwright"; +import { resolveConfig } from "../../src/agent/config.js"; +import { collectSerp } from "../../src/agent/serp-paged.js"; +import { extractSerp } from "../../src/extraction/serp.js"; +import { findDomainRanks } from "../../src/extraction/serp-rank.js"; +import { SessionManager } from "../../src/session/manager.js"; + +const FIXTURE = readFileSync(join(import.meta.dir, "../fixtures/serp/google-results-2026-11-11.html"), "utf8"); +const config = resolveConfig({ headless: true, engine: "patchright" }); +const sessions = new SessionManager(); +let page: Page; +let sessionId = ""; + +/** Serve `body` for the next navigation to `url` (no network) and load it. */ +async function load(url: string, body: string): Promise { + await page.unroute("**/*"); + await page.route("**/*", (route) => route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body })); + await page.goto(url, { waitUntil: "domcontentloaded" }); +} + +const RESULTS_URL = "https://www.google.com/search?q=playwright+mcp+changelog&hl=en"; + +beforeAll(async () => { + const s = await sessions.open(config); + page = s.page; + sessionId = s.id; +}, 120_000); +afterAll(async () => { + await sessions.close(sessionId); +}); + +describe("real Google results page (goto redirect layout, captured 2026-11-11)", () => { + test("every organic result is kept, flagged as a redirect, with its title and display URL", async () => { + await load(RESULTS_URL, FIXTURE); + const serp = await extractSerp(page); + expect(serp.organic.length).toBe(9); + expect(serp.organic.map((r) => r.position)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); + expect(serp.organic[0]?.title).toBe("Releases · microsoft/playwright-mcp"); + expect(serp.organic[0]?.displayUrl).toBe("https://github.com › microsoft › playwright-mcp › releases"); + for (const r of serp.organic) { + expect(r.url.startsWith("https://www.google.com/goto?url=")).toBe(true); + expect(r.redirect).toBe(true); + } + // the "AI Mode reply" heading is not a result (no link) + expect(serp.organic.some((r) => r.title.startsWith("AI Mode"))).toBe(false); + expect(serp.related.length).toBeGreaterThan(0); + }); + + test("domain rank works on a redirect result through its display host", async () => { + await load(RESULTS_URL, FIXTURE); + const serp = await extractSerp(page); + const rank = findDomainRanks(serp, "github.com"); + expect(rank.found).toBe(true); + expect(rank.organic).toEqual([1, 9]); + expect(rank.best).toBe(1); + expect(findDomainRanks(serp, "google.com").found).toBe(false); + }); +}); + +describe("classic layout (direct hrefs) keeps the real destination", () => { + const CLASSIC = + ''; + + test("url is the destination, no redirect flag, Google-internal links are dropped", async () => { + await load(RESULTS_URL, CLASSIC); + const serp = await extractSerp(page); + expect(serp.organic).toEqual([ + { + position: 1, + title: "Doc A", + url: "https://example.com/docs/a?x=1", + displayUrl: "https://example.com › docs › a", + snippet: "snippet a", + }, + ]); + }); +}); + +describe("an empty result list is never silent", () => { + const retry = config.retry; + + test("results page with zero extractable results -> warning no_results_extracted", async () => { + await load(RESULTS_URL, '
layout nobody handles
'); + const serp = await collectSerp(page, 1, retry); + expect(serp.organic).toEqual([]); + expect(serp.warning).toBe("no_results_extracted"); + }); + + test("consent interstitial -> warning consent_wall", async () => { + await load("https://consent.google.com/m?continue=https://www.google.com/search%3Fq%3Dx", "
"); + const serp = await collectSerp(page, 1, retry); + expect(serp.warning).toBe("consent_wall"); + }); + + test("Google /sorry/ block page -> warning blocked", async () => { + await load("https://www.google.com/sorry/index?continue=https://www.google.com/search%3Fq%3Dx", "

Our systems have detected unusual traffic

"); + const serp = await collectSerp(page, 1, retry); + expect(serp.warning).toBe("blocked"); + }); + + test("a page WITH results carries no warning field", async () => { + await load(RESULTS_URL, FIXTURE); + const serp = await collectSerp(page, 1, retry); + expect(serp.organic.length).toBe(9); + expect("warning" in serp).toBe(false); + }); +}); diff --git a/tests/unit/session-block-widgets.test.ts b/tests/unit/session-block-widgets.test.ts new file mode 100644 index 0000000..a123846 --- /dev/null +++ b/tests/unit/session-block-widgets.test.ts @@ -0,0 +1,70 @@ +/** + * Session block verdict on captcha WIDGET shapes, through the real `browser_navigate` / + * `browser_extract` tools: a visitor-facing widget (even an empty container whose iframe + * renders late) is evidence; invisible reCAPTCHA (button-bound, v3 badge, zero-size or + * `size=invisible` iframe) is not. Local fixture server; third-party hosts are aborted. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { call, withClient } from "../integration/helpers/safe-actions-harness.js"; +import { type FixtureServer, serveFixtures } from "./helpers/fixture-server.js"; + +let site: FixtureServer; +beforeAll(() => { + site = serveFixtures({ + // empty h-captcha CONTAINER whose 303x78 iframe is injected after load (real widgets render late) + "/hcaptcha-delayed": { + status: 200, + body: + `
`, + }, + // Google-documented invisible reCAPTCHA binding: `, + }, + // reCAPTCHA v3 badge iframe on a thin thank-you page (src shape supposed, not measured on a live site) + "/thanks-v3-badge": { + status: 200, + body: `

Thank you

Your order is confirmed.

`, + }, + // invisible / zero-size challenge iframes are not a human step either + "/thanks-hidden-iframe": { + status: 200, + body: `

Thank you

`, + }, + }); +}); +afterAll(() => site.stop()); + +describe("a visitor-facing widget on a short page is evidence", () => { + test("empty h-captcha container: blocked at navigate (iframe not rendered yet) and after it renders", async () => { + await withClient(async (c, sessionId, page) => { + await page.context().route(/^https?:\/\/(?!127\.0\.0\.1)/, (r) => r.abort()); + const nav = await call(c, "browser_navigate", { sessionId, url: `${site.origin}/hcaptcha-delayed` }); + expect(nav.blocked).toBe(true); + expect(nav.blockedBy).toBe("unknown"); + await page.waitForSelector(".h-captcha iframe"); + const ext = await call(c, "browser_extract", { sessionId, kind: "text" }); + expect(ext.blocked).toBe(true); + expect(ext.blockedBy).toBe("unknown"); + }, "about:blank"); + }, 60_000); +}); + +describe("invisible reCAPTCHA is never a block", () => { + for (const path of ["/confirm-invisible", "/thanks-v3-badge", "/thanks-hidden-iframe"]) { + test(path, async () => { + await withClient(async (c, sessionId, page) => { + await page.context().route(/^https?:\/\/(?!127\.0\.0\.1)/, (r) => r.abort()); + const nav = await call(c, "browser_navigate", { sessionId, url: `${site.origin}${path}` }); + expect(Object.keys(nav).sort()).toEqual(["title", "url"]); + const ext = await call(c, "browser_extract", { sessionId, kind: "text" }); + expect(Object.keys(ext).sort()).toEqual(["text", "url"]); + const all = await call(c, "browser_extract", { sessionId }); + expect(Object.keys(all).sort()).toEqual(["challenges", "hotelOffers", "prices", "text", "url"]); + }, "about:blank"); + }, 60_000); + } +}); diff --git a/tests/unit/session-block.test.ts b/tests/unit/session-block.test.ts new file mode 100644 index 0000000..7f5028f --- /dev/null +++ b/tests/unit/session-block.test.ts @@ -0,0 +1,177 @@ +/** + * Session routes (`browser_navigate`, `browser_extract`) say when the live page is + * an anti-bot interstitial, like the fast path does. Tested through the REAL tools + * (in-memory MCP client, real headless Chromium) against a local fixture server that + * serves the real captured blocked pages with their real status/headers. + * Third-party hosts (e.g. challenges.cloudflare.com) are aborted. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { call, withClient } from "../integration/helpers/safe-actions-harness.js"; +import { detectSessionBlock } from "../../src/extraction/challenge-verdict.js"; +import { REAL_BLOCKED, article } from "./helpers/block-pages.js"; +import { type FixtureServer, serveFixtures } from "./helpers/fixture-server.js"; + +const CH = join(import.meta.dir, "../fixtures/challenges"); +const read = (f: string): string => readFileSync(join(CH, f), "utf8"); +const PROSE = "The committee reviewed the annual report and discussed the findings at length. ".repeat(12); + +let site: FixtureServer; +beforeAll(() => { + site = serveFixtures({ + "/cf-moment": REAL_BLOCKED["/cf-moment"]!.route, + "/cf-managed": REAL_BLOCKED["/cf-managed"]!.route, + "/cf-security": REAL_BLOCKED["/cf-security"]!.route, + "/datadome": REAL_BLOCKED["/datadome"]!.route, + "/aws-captcha": { status: 405, headers: { "x-amzn-waf-action": "captcha" }, body: read("aws-waf-captcha-synthetic.html") }, + "/aws-challenge": { status: 202, headers: { "x-amzn-waf-action": "challenge" }, body: read("aws-waf-challenge-synthetic.html") }, + "/cf-1020": { status: 403, body: read("cloudflare-error-1020-synthetic.html") }, + // a RENDERED Turnstile widget: its container holds the 300x65 iframe (an empty 0x0 div is not a rendered widget) + "/turnstile-thin": { + status: 200, + body: `
`, + }, + "/turnstile-form": { + status: 200, + body: `

${PROSE}

`, + }, + "/login-recaptcha": { + status: 200, + body: `
`, + }, + "/contact-recaptcha-v3": { + status: 200, + body: `

Contact

`, + }, + "/spa-turnstile-script": { + status: 200, + body: `
Loading...
`, + }, + "/long-nav-main-widget": { + status: 200, + body: `
`, + }, + "/article": { status: 200, body: article("Quarterly report") }, + "/prose": { + status: 200, + body: article("Bot walls", "Cloudflare shipped Turnstile; hCaptcha and reCAPTCHA exist; Error 1020 shows a Ray ID; AWS WAF returns 405."), + }, + }); +}); +afterAll(() => site.stop()); + +/** Run `fn` with a session whose third-party requests are aborted. */ +async function inSession(fn: (c: Client, sessionId: string) => Promise): Promise { + await withClient(async (c, id, page) => { + await page.context().route(/^https?:\/\/(?!127\.0\.0\.1)/, (r) => r.abort()); + await fn(c, id); + }, "about:blank"); +} + +const BLOCKED: [string, string][] = [ + ["/cf-moment", "cloudflare"], + ["/cf-managed", "cloudflare"], + ["/cf-security", "cloudflare"], + ["/datadome", "datadome"], + ["/aws-captcha", "aws-waf"], + ["/aws-challenge", "aws-waf"], + ["/cf-1020", "cloudflare"], + ["/turnstile-thin", "unknown"], +]; + +describe("blocked pages are reported by browser_navigate and browser_extract", () => { + for (const [path, vendor] of BLOCKED) { + test(`${path} -> blockedBy ${vendor}`, async () => { + await inSession(async (c, sessionId) => { + const nav = await call(c, "browser_navigate", { sessionId, url: `${site.origin}${path}` }); + expect(nav.blocked).toBe(true); + expect(nav.blockedBy).toBe(vendor); + expect(typeof nav.hint).toBe("string"); + const ext = await call(c, "browser_extract", { sessionId, kind: "text" }); + expect(ext.blocked).toBe(true); + expect(ext.blockedBy).toBe(vendor); + expect(ext.hint).toBe(nav.hint); + }); + }, 60_000); + } + + test("hint names real next steps and never a solver", async () => { + await inSession(async (c, sessionId) => { + const nav = await call(c, "browser_navigate", { sessionId, url: `${site.origin}/turnstile-thin` }); + const hint = String(nav.hint); + expect(hint).toContain("browser_handoff"); + expect(hint).toContain("browser_open"); + expect(hint.toLowerCase()).not.toContain("solve"); + expect(hint).not.toContain("captcha:"); + }); + }, 60_000); +}); + +describe("an inspection failure is logged and leaves the output verdict-free", () => { + test("closed page -> null verdict plus exactly one warn line on stderr", async () => { + await withClient(async (_c, _id, page) => { + const extra = await page.context().newPage(); + await extra.close(); + const lines: string[] = []; + const orig = process.stderr.write.bind(process.stderr); + process.stderr.write = ((chunk: string | Uint8Array) => { + lines.push(String(chunk)); + return true; + }) as typeof process.stderr.write; + try { + expect(await detectSessionBlock(extra)).toBeNull(); + } finally { + process.stderr.write = orig; + } + const warns = lines.filter((l) => l.includes("session block check failed")); + expect(warns.length).toBe(1); + expect(JSON.parse(warns[0] ?? "{}").level).toBe("warn"); + }, "about:blank"); + }, 60_000); +}); + +describe("browser_extract maxTokens (token-diet wiring) keeps the block verdict", () => { + test("blocked page + maxTokens: text truncated, blocked/blockedBy/hint still present", async () => { + await inSession(async (c, sessionId) => { + await call(c, "browser_navigate", { sessionId, url: `${site.origin}/cf-1020` }); + const ext = await call(c, "browser_extract", { sessionId, kind: "text", maxTokens: 5 }); + expect(ext.blocked).toBe(true); + expect(ext.blockedBy).toBe("cloudflare"); + expect(ext.nextOffset).toBeDefined(); + }); + }, 60_000); + + test("normal page + maxTokens on a long text: truncated, no block keys", async () => { + await inSession(async (c, sessionId) => { + await call(c, "browser_navigate", { sessionId, url: `${site.origin}/article` }); + const ext = await call(c, "browser_extract", { sessionId, kind: "text", maxTokens: 20 }); + expect(ext.nextOffset).toBeDefined(); + expect(ext.blocked).toBeUndefined(); + }); + }, 60_000); +}); + +describe("normal pages stay byte-identical (no blocked/blockedBy/hint keys)", () => { + for (const path of [ + "/article", + "/prose", + "/turnstile-form", + "/login-recaptcha", + "/contact-recaptcha-v3", + "/spa-turnstile-script", + "/long-nav-main-widget", + ]) { + test(`${path}`, async () => { + await inSession(async (c, sessionId) => { + const nav = await call(c, "browser_navigate", { sessionId, url: `${site.origin}${path}` }); + expect(Object.keys(nav).sort()).toEqual(["title", "url"]); + const ext = await call(c, "browser_extract", { sessionId, kind: "text" }); + expect(Object.keys(ext).sort()).toEqual(["text", "url"]); + const all = await call(c, "browser_extract", { sessionId }); + expect(Object.keys(all).sort()).toEqual(["challenges", "hotelOffers", "prices", "text", "url"]); + }); + }, 60_000); + } +}); diff --git a/tests/unit/tool-annotations.test.ts b/tests/unit/tool-annotations.test.ts new file mode 100644 index 0000000..134cf0a --- /dev/null +++ b/tests/unit/tool-annotations.test.ts @@ -0,0 +1,124 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { TOOL_ANNOTATIONS } from "../../src/server/tool-annotations.js"; +import { createServer } from "../../src/server/server.js"; +import { listAdvertisedTools } from "../../src/server/tool-sizes.js"; + +const savedCaps = process.env.FUSE_CAPS; +const savedPreset = process.env.FUSE_PRESET; +beforeEach(() => { + delete process.env.FUSE_CAPS; + delete process.env.FUSE_PRESET; +}); +afterEach(() => { + if (savedCaps === undefined) delete process.env.FUSE_CAPS; + else process.env.FUSE_CAPS = savedCaps; + if (savedPreset === undefined) delete process.env.FUSE_PRESET; + else process.env.FUSE_PRESET = savedPreset; +}); + +/** `tools/list` of the default server, through the real MCP protocol (in-memory). */ +const advertised = () => listAdvertisedTools(createServer()); + +/** Tools that only observe: must be advertised `readOnlyHint: true`. */ +const READ_ONLY = [ + "browser_fetch", + "browser_fetch_batch", + "browser_crawl", + "browser_collect_batch", + "browser_snapshot", + "browser_extract", + "browser_extract_schema", + "browser_products", + "browser_inspect", + "browser_console", + "browser_network", + "browser_status", + "browser_vault", +]; + +/** + * Tools with a write side effect on SOME input (a caller `path`, `harPath`/`outputDir` + * agent options, saved screenshots/baselines/PDFs, cookie set/clear...): a client that + * auto-approves read-only tools must still be asked, so they are never `readOnlyHint:true`. + */ +const WRITE_CAPABLE = [ + "browser_screenshot", + "browser_probe", + "browser_probe_html", + "browser_serp_batch", + "browser_shots_batch", + "browser_site_shots", + "browser_pdf", + "browser_visual_diff", + "browser_cookies", + "browser_metrics", +]; + +/** Tools that change page/session state: must NOT be advertised read-only. */ +const ACTIONS = [ + "browser_click", + "browser_fill", + "browser_act", + "browser_run", + "browser_navigate", + "browser_press", + "browser_type", + "browser_select", + "browser_login", + "browser_cookies", + "browser_close", + "browser_open", +]; + +/** Tools that may trigger irreversible effects (submit, delete, clear). */ +const DESTRUCTIVE = ["browser_click", "browser_act", "browser_press", "browser_run", "browser_cookies"]; + +describe("tool annotations (central table applied at registration)", () => { + test("every registered tool is advertised with its table entry and an explicit readOnlyHint", async () => { + const tools = await advertised(); + expect(tools).toHaveLength(Object.keys(TOOL_ANNOTATIONS).length); + for (const tool of tools) { + const entry = TOOL_ANNOTATIONS[tool.name]; + expect(entry, `${tool.name} has no TOOL_ANNOTATIONS entry`).toBeDefined(); + expect(tool.annotations, `${tool.name} advertises no annotations`).toEqual(entry); + expect(typeof tool.annotations?.readOnlyHint, `${tool.name}.readOnlyHint`).toBe("boolean"); + } + }); + + test("the table has no entry for a tool that is not registered", async () => { + const names = new Set((await advertised()).map((t) => t.name)); + expect(Object.keys(TOOL_ANNOTATIONS).filter((n) => !names.has(n))).toEqual([]); + }); + + test("read-only tools are readOnlyHint:true", async () => { + const byName = new Map((await advertised()).map((t) => [t.name, t])); + for (const name of READ_ONLY) expect(byName.get(name)?.annotations?.readOnlyHint, name).toBe(true); + }); + + test("destructive tools keep the spec-default destructiveHint (not overridden to false)", async () => { + const byName = new Map((await advertised()).map((t) => [t.name, t])); + for (const name of DESTRUCTIVE) expect(byName.get(name)?.annotations?.destructiveHint, name).not.toBe(false); + for (const name of ["browser_navigate", "browser_fill", "browser_close"]) { + expect(byName.get(name)?.annotations?.destructiveHint, name).toBe(false); + } + }); + + test("write-capable tools (path / harPath / outputDir / baselines) are not readOnlyHint", async () => { + const byName = new Map((await advertised()).map((t) => [t.name, t])); + for (const name of WRITE_CAPABLE) expect(byName.get(name)?.annotations?.readOnlyHint, name).toBe(false); + }); + + test("action tools are not readOnlyHint", async () => { + const byName = new Map((await advertised()).map((t) => [t.name, t])); + for (const name of ACTIONS) expect(byName.get(name)?.annotations?.readOnlyHint, name).toBe(false); + }); + + test("a read-only tool never carries destructive/idempotent hints (meaningless, costs tokens)", () => { + for (const [name, a] of Object.entries(TOOL_ANNOTATIONS)) { + if (a.readOnlyHint) { + expect(a.destructiveHint, name).toBeUndefined(); + expect(a.idempotentHint, name).toBeUndefined(); + } + } + }); +}); diff --git a/tests/unit/tool-presets.test.ts b/tests/unit/tool-presets.test.ts new file mode 100644 index 0000000..127a230 --- /dev/null +++ b/tests/unit/tool-presets.test.ts @@ -0,0 +1,128 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { CAP_GROUPS } from "../../src/server/caps.js"; +import { getPreset, isPresetName, PRESET_NAMES, parsePreset } from "../../src/server/presets.js"; +import { createServer } from "../../src/server/server.js"; +import { TOOL_ANNOTATIONS } from "../../src/server/tool-annotations.js"; +import { listAdvertisedTools, measureSurface, sizeTool, totalSizes } from "../../src/server/tool-sizes.js"; + +/** Every registered tool = every annotated tool (the coverage test pins table and server together). */ +const ALL = Object.keys(TOOL_ANNOTATIONS).length; +const errSpy = spyOn(console, "error").mockImplementation(() => {}); +const savedCaps = process.env.FUSE_CAPS; +const savedPreset = process.env.FUSE_PRESET; +beforeEach(() => { + delete process.env.FUSE_CAPS; + delete process.env.FUSE_PRESET; +}); +afterEach(() => { + errSpy.mockClear(); + if (savedCaps === undefined) delete process.env.FUSE_CAPS; + else process.env.FUSE_CAPS = savedCaps; + if (savedPreset === undefined) delete process.env.FUSE_PRESET; + else process.env.FUSE_PRESET = savedPreset; +}); + +const names = async (opts?: Parameters[0]) => + (await listAdvertisedTools(createServer(opts))).map((t) => t.name); + +describe("parsePreset", () => { + test("blank / undefined is full", () => { + expect(parsePreset(undefined)).toBe("full"); + expect(parsePreset(" ")).toBe("full"); + }); + test("known names, case and whitespace tolerant", () => { + expect(parsePreset(" DOCS ")).toBe("docs"); + expect(parsePreset("qa")).toBe("qa"); + }); + test("unknown name is reported on stderr and falls back to full", () => { + expect(parsePreset("bogus")).toBe("full"); + expect(String(errSpy.mock.calls[0]?.[0])).toContain('unknown FUSE_PRESET "bogus"'); + }); + test("isPresetName", () => { + expect(PRESET_NAMES).toEqual(["full", "docs", "qa"]); + expect(isPresetName("docs")).toBe(true); + expect(isPresetName("nope")).toBe(false); + }); +}); + +describe("preset definitions", () => { + test("every allow-listed tool exists in the annotation table (= is a real tool)", () => { + for (const name of PRESET_NAMES) { + for (const tool of getPreset(name).tools ?? []) expect(TOOL_ANNOTATIONS[tool], `${name}: ${tool}`).toBeDefined(); + } + }); +}); + +describe("createServer with a preset", () => { + test("default (no env, no option) exposes every annotated tool", async () => { + expect(await names()).toHaveLength(ALL); + }); + + test("preset full exposes the same tools as the default", async () => { + expect(new Set(await names({ preset: "full" }))).toEqual(new Set(await names())); + }); + + test("docs exposes exactly its allow-list", async () => { + expect((await names({ preset: "docs" })).sort()).toEqual([...(getPreset("docs").tools ?? [])].sort()); + }); + + test("qa exposes exactly its allow-list", async () => { + expect((await names({ preset: "qa" })).sort()).toEqual([...(getPreset("qa").tools ?? [])].sort()); + }); + + test("FUSE_PRESET selects the preset when no option is passed", async () => { + process.env.FUSE_PRESET = "docs"; + expect(await names()).toHaveLength(getPreset("docs").tools?.length ?? -1); + }); + + test("an explicit option wins over FUSE_PRESET", async () => { + process.env.FUSE_PRESET = "docs"; + expect(await names({ preset: "full" })).toHaveLength(ALL); + }); + + test("FUSE_CAPS narrows on top of a preset (both must allow a tool)", async () => { + process.env.FUSE_CAPS = "debug"; + expect((await names({ preset: "qa" })).sort()).toEqual(["browser_console", "browser_network", "browser_visual_diff"]); + }); + + test("a preset and FUSE_CAPS with no common group never yield an empty server: caps ignored, stderr notice", async () => { + process.env.FUSE_CAPS = "core"; + expect((await names({ preset: "docs" })).sort()).toEqual([...(getPreset("docs").tools ?? [])].sort()); + expect(String(errSpy.mock.calls.at(-1)?.[0])).toContain("no common tool group"); + process.env.FUSE_CAPS = "batch"; + expect(await names({ preset: "qa" })).toHaveLength(getPreset("qa").tools?.length ?? -1); + }); + + test("a removed tool is gone from tools/list and keeps its annotations on the rest", async () => { + const tools = await listAdvertisedTools(createServer({ preset: "docs" })); + expect(tools.map((t) => t.name)).not.toContain("browser_click"); + for (const t of tools) expect(t.annotations).toEqual(TOOL_ANNOTATIONS[t.name]); + }); +}); + +describe("tool size measurement", () => { + test("sizeTool counts UTF-8 bytes of the four definition fields; tokens = ceil(bytes/4)", () => { + const tool = { name: "t", description: "é", inputSchema: { type: "object" as const }, annotations: { readOnlyHint: true } }; + const s = sizeTool(tool); + const expected = Buffer.byteLength(JSON.stringify({ name: "t", description: "é", inputSchema: { type: "object" } }), "utf8"); + expect(s.bytes).toBe(expected); + expect(s.tokens).toBe(Math.ceil(expected / 4)); + expect(s.fullBytes).toBeGreaterThan(s.bytes); + }); + + test("measureSurface: presets are strictly smaller than full, and totals add up", async () => { + const full = totalSizes(await measureSurface("full")); + const docs = totalSizes(await measureSurface("docs")); + const qa = totalSizes(await measureSurface("qa")); + expect(full.tools).toBe(ALL); + expect(docs.bytes).toBeLessThan(full.bytes); + expect(qa.bytes).toBeLessThan(full.bytes); + expect(docs.tools + qa.tools).toBeLessThan(full.tools); + }); + + test("caps groups still partition the full surface", async () => { + let count = 0; + for (const g of CAP_GROUPS) count += (await measureSurface("full", new Set([g]))).length; + expect(count).toBe(ALL); + }); +}); diff --git a/tests/unit/tools-cli.test.ts b/tests/unit/tools-cli.test.ts new file mode 100644 index 0000000..1dc405c --- /dev/null +++ b/tests/unit/tools-cli.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, test } from "bun:test"; +import { getPreset } from "../../src/server/presets.js"; +import { TOOL_ANNOTATIONS } from "../../src/server/tool-annotations.js"; + +/** Run a bin entry point as a real subprocess (the public entry point, real argv). */ +function run(entry: string, args: string[], env: Record = {}) { + const proc = Bun.spawnSync(["node", "--import", "tsx", entry, ...args], { + env: { ...process.env, FUSE_PRESET: "", FUSE_CAPS: "", ...env }, + stdout: "pipe", + stderr: "pipe", + }); + return { code: proc.exitCode, out: proc.stdout.toString(), err: proc.stderr.toString() }; +} + +const CLI = "src/bin/cli.ts"; +const MCP = "src/bin/mcp.ts"; + +describe("fuse-browser tools --tokens", () => { + test("prints the per-tool table, group subtotals, total and the estimate method", () => { + const r = run(CLI, ["tools", "--tokens"]); + expect(r.code).toBe(0); + expect(r.out).toContain("preset full"); + expect(r.out).toContain("estimate"); + expect(r.out).toContain("browser_fetch"); + expect(r.out).toMatch(new RegExp(`TOTAL\\s+${Object.keys(TOOL_ANNOTATIONS).length} tools`)); + expect(r.out).toMatch(/core\s+\d+ tools/); + }); + + test("--preset docs lists only the docs tools", () => { + const r = run(CLI, ["tools", "--tokens", "--preset", "docs"]); + expect(r.code).toBe(0); + expect(r.out).toContain("preset docs"); + expect(r.out).toMatch(new RegExp(`TOTAL\\s+${getPreset("docs").tools?.length} tools`)); + expect(r.out).not.toContain("browser_click"); + }); + + test("FUSE_PRESET selects the active preset", () => { + const r = run(CLI, ["tools", "--tokens"], { FUSE_PRESET: "qa" }); + expect(r.out).toContain("preset qa"); + expect(r.out).toMatch(new RegExp(`TOTAL\\s+${getPreset("qa").tools?.length} tools`)); + }); + + test("an unknown --preset is an error (exit 1) naming the known presets", () => { + const r = run(CLI, ["tools", "--tokens", "--preset", "bogus"]); + expect(r.code).toBe(1); + expect(r.err).toContain("unknown preset 'bogus'"); + expect(r.err).toContain("full, docs, qa"); + }); + + test("`tools` without --tokens falls through to the usage error", () => { + const r = run(CLI, ["tools"]); + expect(r.code).toBe(1); + expect(r.err).toContain("tools --tokens"); + }); +}); + +describe("browser-mcp --preset", () => { + test("an unknown preset exits 1 before the stdio transport binds", () => { + const r = run(MCP, ["--preset", "bogus"]); + expect(r.code).toBe(1); + expect(r.err).toContain("unknown preset 'bogus'"); + expect(r.out).toBe(""); + }); + + test("an unknown flag is still rejected", () => { + const r = run(MCP, ["--nope"]); + expect(r.code).toBe(1); + expect(r.err).toContain("Unknown option '--nope'"); + }); + + test("--help documents --preset", () => { + const r = run(MCP, ["--help"]); + expect(r.code).toBe(0); + expect(r.out).toContain("--preset full|docs|qa"); + }); +}); diff --git a/tests/unit/verify-checks.test.ts b/tests/unit/verify-checks.test.ts new file mode 100644 index 0000000..6e39048 --- /dev/null +++ b/tests/unit/verify-checks.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from "bun:test"; +import { evaluateExpectations } from "../../src/agent/verify-checks.js"; +import { renderReceipt, resolveBaseline } from "../../src/agent/verify-evidence.js"; +import type { PageProbe, VerifyLogs } from "../../src/interfaces/verify.js"; + +const probe = (text: string, state: Awaited> = "visible"): PageProbe => ({ + bodyText: async () => text, + visibility: async () => state, +}); +const logs = (over: Partial = {}): VerifyLogs => ({ network: [], console: [], engine: "playwright", ...over }); + +describe("evaluateExpectations", () => { + test("text is a case-sensitive substring; reasons per visibility state", async () => { + expect((await evaluateExpectations([{ text: "Welcome" }], probe("Welcome home"), logs())).failed).toEqual([]); + expect((await evaluateExpectations([{ text: "welcome" }], probe("Welcome home"), logs())).failed[0]?.reason).toBe("text_not_found"); + for (const [state, reason] of [["hidden", "not_visible"], ["missing", "selector_not_found"], ["invalid", "invalid_selector"]] as const) { + expect((await evaluateExpectations([{ visible: "#x" }], probe("", state), logs())).failed[0]?.reason).toBe(reason); + } + }); + + test("noFailedRequests: responses >= 400, and (fail closed) a request that never got a response", async () => { + const net = [ + { type: "request", url: "http://a/x.js", method: "GET" }, + { type: "response", url: "http://a/x.js", status: 200 }, + { type: "request", url: "http://a/y.png", method: "GET" }, + { type: "response", url: "http://a/y.png", status: 404 }, + { type: "request", url: "http://a/pending" }, + ]; + const r = await evaluateExpectations([{ noFailedRequests: true }], probe(""), logs({ network: net })); + expect(r.failed[0]?.detail).toEqual([ + { url: "http://a/y.png", status: 404 }, + { url: "http://a/pending", error: "no_response" }, + ]); + }); + + test("noConsoleErrors: errors fail on any engine; clean passes only where the console is captured", async () => { + const err = [{ type: "error", text: "boom" }]; + expect((await evaluateExpectations([{ noConsoleErrors: true }], probe(""), logs({ console: err }))).failed[0]?.reason).toBe("console_errors"); + expect((await evaluateExpectations([{ noConsoleErrors: true }], probe(""), logs({ engine: "patchright", console: err }))).failed[0]?.reason).toBe("console_errors"); + expect((await evaluateExpectations([{ noConsoleErrors: true }], probe(""), logs())).failed).toEqual([]); + const pw = await evaluateExpectations([{ noConsoleErrors: true }], probe(""), logs({ engine: "patchright" })); + expect(pw.failed[0]?.reason).toBe("console_unavailable_on_patchright"); + expect(pw.consoleAvailable).toBe(false); + }); +}); + +describe("receipt", () => { + test("renders a pass/fail table and the evidence paths", () => { + const md = renderReceipt({ + pass: false, + url: "http://x/", + title: "T", + engine: "playwright", + expectations: [{ text: "a" }, { visible: "#b" }], + failed: [{ expect: { visible: "#b" }, reason: "not_visible" }], + files: { after: "/e/after.png" }, + }); + expect(md).toContain("- result: FAIL"); + expect(md).toContain("| 1 | `{\"text\":\"a\"}` | pass | |"); + expect(md).toContain("not_visible"); + expect(md).toContain("- after: /e/after.png"); + }); + + test("a baseline that does not exist resolves to null", () => { + expect(resolveBaseline("/no/such/file.png")).toBeNull(); + expect(resolveBaseline("/no/such/receipt.md")).toBeNull(); + }); +}); diff --git a/tests/unit/verify-evidence.test.ts b/tests/unit/verify-evidence.test.ts new file mode 100644 index 0000000..8a4f4c0 --- /dev/null +++ b/tests/unit/verify-evidence.test.ts @@ -0,0 +1,76 @@ +/** + * `browser_verify` evidence: baseline diff, receipt as baseline, write + * confinement and the default evidence directory. Real tool, real browser. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import { call } from "../integration/helpers/safe-actions-harness.js"; +import type { FixtureServer } from "./helpers/fixture-server.js"; +import { inSession, startSite, tmpDir } from "./helpers/verify-site.js"; + +let site: FixtureServer; +beforeAll(() => { + site = startSite(); +}); +afterAll(() => site.stop()); +const T = 120_000; + +describe("browser_verify baseline", () => { + test("identical page: diff present, nothing changed; changed page: diff shows the change", async () => { + await inSession(async (c, sessionId) => { + const first = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), expect: [{ visible: "body" }] }); + const same = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), baseline: first.evidence.after, expect: [{ visible: "body" }] }); + expect(same.evidence.before).toBe(first.evidence.after); + expect(same.evidence.diff.changed).toBe(false); + expect(same.evidence.diff.diffPixels).toBe(0); + const changed = await call(c, "browser_verify", { sessionId, url: `${site.origin}/changed`, evidenceDir: tmpDir(), baseline: first.evidence.after, expect: [{ visible: "body" }] }); + expect(changed.pass).toBe(true); + expect(changed.evidence.diff.changed).toBe(true); + expect(changed.evidence.diff.diffPixels).toBeGreaterThan(0); + expect(existsSync(changed.evidence.diff.image)).toBe(true); + }); + }, T); + + test("a previous receipt works as baseline; a missing baseline is a failed expectation, not a crash", async () => { + await inSession(async (c, sessionId) => { + const first = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), expect: [{ visible: "body" }] }); + const viaReceipt = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), baseline: first.evidence.receiptMd, expect: [{ visible: "body" }] }); + expect(viaReceipt.evidence.diff.changed).toBe(false); + const missing = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), baseline: join(tmpDir(), "nope.png"), expect: [{ visible: "body" }] }); + expect(missing.pass).toBe(false); + expect(missing.failed[0].reason).toBe("baseline_not_found"); + }); + }, T); +}); + +describe("browser_verify evidence location", () => { + test("evidence is written only inside the confined directory; outside is refused and nothing is written", async () => { + const root = tmpDir(); + const outside = tmpDir(); + process.env.FUSE_CONFINE_WRITES = root; + try { + await inSession(async (c, sessionId) => { + const bad = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: outside, expect: [{ visible: "body" }] }); + expect(JSON.stringify(bad)).toContain("path_outside_confinement"); + expect(readdirSync(outside)).toEqual([]); + const inside = join(root, "ev"); + mkdirSync(inside, { recursive: true }); + const ok = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: inside, expect: [{ visible: "body" }] }); + expect(ok.pass).toBe(true); + expect(readdirSync(inside).length).toBeGreaterThanOrEqual(4); + }); + } finally { + delete process.env.FUSE_CONFINE_WRITES; + } + }, T); + + test("without evidenceDir the evidence goes under /verify", async () => { + const out = tmpDir(); + await inSession(async (c, _sessionId) => { + const r = await call(c, "browser_verify", { url: `${site.origin}/good`, outputDir: out, headless: true, expect: [{ visible: "body" }] }); + expect(r.evidence.after.startsWith(join(out, "verify"))).toBe(true); + expect(existsSync(r.evidence.after)).toBe(true); + }); + }, T); +}); diff --git a/tests/unit/verify-tool.test.ts b/tests/unit/verify-tool.test.ts new file mode 100644 index 0000000..c074dfc --- /dev/null +++ b/tests/unit/verify-tool.test.ts @@ -0,0 +1,106 @@ +/** + * `browser_verify`: expectations, blocked verdict, console availability. + * Tested through the REAL tool (in-memory MCP client, real headless Chromium) + * against local fixture pages. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { call } from "../integration/helpers/safe-actions-harness.js"; +import type { FixtureServer } from "./helpers/fixture-server.js"; +import { inSession, startSite, tmpDir } from "./helpers/verify-site.js"; + +let site: FixtureServer; +beforeAll(() => { + site = startSite(); +}); +afterAll(() => site.stop()); +const T = 120_000; + +describe("browser_verify expectations", () => { + test("a page that passes every expectation, with the evidence files and receipt", async () => { + const dir = tmpDir(); + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { + sessionId, + url: `${site.origin}/good`, + evidenceDir: dir, + expect: [{ text: "Welcome" }, { visible: "#cta" }, { noFailedRequests: true }], + }); + expect(r.pass).toBe(true); + expect(r.failed).toEqual([]); + for (const f of [r.evidence.after, r.evidence.consoleLog, r.evidence.networkLog, r.evidence.receiptMd]) { + expect(f.startsWith(dir)).toBe(true); + expect(existsSync(f)).toBe(true); + } + expect(readFileSync(r.evidence.receiptMd, "utf8")).toContain("PASS"); + expect(r.evidence.diff).toBeUndefined(); + }); + }, T); + + test("missing text, hidden selector, absent selector fail with a reason", async () => { + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { + sessionId, + url: `${site.origin}/good`, + evidenceDir: tmpDir(), + expect: [{ text: "Goodbye" }, { visible: "#hidden" }, { visible: "#nope" }, { text: "Welcome" }], + }); + expect(r.pass).toBe(false); + expect(r.failed.map((f: { reason: string }) => f.reason)).toEqual(["text_not_found", "not_visible", "selector_not_found"]); + expect(r.failed[0].expect).toEqual({ text: "Goodbye" }); + }); + }, T); + + test("a 404 subresource fails noFailedRequests and names the URL", async () => { + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/bad-img`, evidenceDir: tmpDir(), expect: [{ noFailedRequests: true }] }); + expect(r.pass).toBe(false); + expect(r.failed[0].reason).toBe("failed_requests"); + expect(JSON.stringify(r.failed[0].detail)).toContain("/missing.png"); + }); + }, T); + + test("url alone opens and closes its own session", async () => { + await inSession(async (c, sessionId) => { + const before = (await call(c, "browser_status", {})).sessions.length; + const r = await call(c, "browser_verify", { url: `${site.origin}/good`, evidenceDir: tmpDir(), expect: [{ text: "Welcome" }], headless: true }); + expect(r.pass).toBe(true); + expect(r.sessionId).toBeUndefined(); + expect((await call(c, "browser_status", {})).sessions.length).toBe(before); + expect(sessionId.length).toBeGreaterThan(0); + }); + }, T); + + test("a blocked interstitial FAILS verify with the blocked reason, even when the text expectation would match", async () => { + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/cf-moment`, evidenceDir: tmpDir(), expect: [{ text: "a" }] }); + expect(r.pass).toBe(false); + expect(r.blocked).toBe(true); + expect(r.failed.some((f: { reason: string }) => f.reason === "blocked:cloudflare")).toBe(true); + }); + }, T); +}); + +describe("browser_verify console expectation", () => { + test("patchright: explicit unavailable reason, never a silent pass", async () => { + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), expect: [{ noConsoleErrors: true }] }); + expect(r.pass).toBe(false); + expect(r.consoleAvailable).toBe(false); + expect(r.failed[0]).toMatchObject({ expect: { noConsoleErrors: true }, reason: "console_unavailable_on_patchright" }); + }); + }, T); + + test("playwright: a console error fails, a clean page passes", async () => { + await inSession(async (c, sessionId) => { + const bad = await call(c, "browser_verify", { sessionId, url: `${site.origin}/console-error`, evidenceDir: tmpDir(), expect: [{ noConsoleErrors: true }] }); + expect(bad.consoleAvailable).toBe(true); + expect(bad.failed[0].reason).toBe("console_errors"); + expect(JSON.stringify(bad.failed[0].detail)).toContain("boom-from-page"); + const good = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), expect: [{ noConsoleErrors: true }] }); + expect(good.pass).toBe(true); + expect(readFileSync(join(good.evidence.consoleLog), "utf8")).toContain("["); + }, "playwright"); + }, T); +}); diff --git a/tests/unit/verify-windows.test.ts b/tests/unit/verify-windows.test.ts new file mode 100644 index 0000000..c6057e6 --- /dev/null +++ b/tests/unit/verify-windows.test.ts @@ -0,0 +1,140 @@ +/** + * `browser_verify` challenger regressions: the log window, uncaught exceptions, + * failure-then-success, the 250-entry cap, confinement of the default dir, and + * the receipt-baseline path rule. Real tool, real browser, local fixtures. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, readdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { call } from "../integration/helpers/safe-actions-harness.js"; +import type { FixtureServer } from "./helpers/fixture-server.js"; +import { inSession, startSite, tmpDir } from "./helpers/verify-site.js"; + +let site: FixtureServer; +beforeAll(() => { + site = startSite(); +}); +afterAll(() => site.stop()); +const T = 120_000; +const both = [{ noConsoleErrors: true }, { noFailedRequests: true }] as const; + +describe("browser_verify log window and failure sources", () => { + test("without url the session's own buffer is checked (as documented)", async () => { + await inSession(async (c, sessionId) => { + await call(c, "browser_navigate", { sessionId, url: `${site.origin}/noisy` }); + const r = await call(c, "browser_verify", { sessionId, evidenceDir: tmpDir(), expect: [...both] }); + expect(r.pass).toBe(false); + expect(r.failed.map((f: { reason: string }) => f.reason).sort()).toEqual(["console_errors", "failed_requests"]); + }, "playwright"); + }, T); + + test("with url, entries from before the verification do not leak in", async () => { + await inSession(async (c, sessionId) => { + await call(c, "browser_navigate", { sessionId, url: `${site.origin}/noisy` }); + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), expect: [...both] }); + expect(r.pass).toBe(true); + }, "playwright"); + }, T); + + test("an uncaught exception fails noConsoleErrors (page_errors) on playwright; patchright delivers no page errors (measured) and says unavailable", async () => { + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/throw`, evidenceDir: tmpDir(), expect: [{ noConsoleErrors: true }] }); + expect(r.pass).toBe(false); + expect(JSON.stringify(r.failed)).toContain("uncaught-x"); + expect(r.failed[0].reason).toBe("page_errors"); + }, "playwright"); + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/throw`, evidenceDir: tmpDir(), expect: [{ noConsoleErrors: true }] }); + expect(r.pass).toBe(false); + expect(r.failed[0].reason).toBe("console_unavailable_on_patchright"); + }); + }, T); + + test("a 500 followed by a 200 on the same URL still fails noFailedRequests", async () => { + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/flaky-page`, evidenceDir: tmpDir(), expect: [{ noFailedRequests: true }] }); + expect(r.pass).toBe(false); + expect(JSON.stringify(r.failed[0].detail)).toContain("500"); + }); + }, T); + + test("an early failure is not evicted by 300 later requests (log cap)", async () => { + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/many`, evidenceDir: tmpDir(), expect: [{ noFailedRequests: true }] }); + expect(r.pass).toBe(false); + expect(JSON.stringify(r.failed[0].detail)).toContain("gone-first"); + }); + }, T); + + test("session mode: a request with no response (network failure) can never pass; a redirect is not one", async () => { + await inSession(async (c, sessionId) => { + await call(c, "browser_navigate", { sessionId, url: `${site.origin}/netfail` }); + const bad = await call(c, "browser_verify", { sessionId, evidenceDir: tmpDir(), expect: [{ noFailedRequests: true }] }); + expect(bad.pass).toBe(false); + expect(bad.failed[0].reason).toBe("failed_requests"); + expect(JSON.stringify(bad.failed[0].detail)).toContain("no_response"); + }); + await inSession(async (c, sessionId) => { + await call(c, "browser_navigate", { sessionId, url: `${site.origin}/redir` }); + const ok = await call(c, "browser_verify", { sessionId, evidenceDir: tmpDir(), expect: [{ noFailedRequests: true }] }); + expect(ok.pass).toBe(true); + }); + }, T); + + test("an empty expect list is rejected (nothing would be verified)", async () => { + await inSession(async (c, sessionId) => { + const r = await c.callTool({ name: "browser_verify", arguments: { sessionId, url: `${site.origin}/good`, expect: [] } }); + expect(r.isError).toBe(true); + }); + }, T); + + test("empty text / selector expectations are rejected, not vacuously passed", async () => { + await inSession(async (c, sessionId) => { + const r = await c.callTool({ name: "browser_verify", arguments: { sessionId, url: `${site.origin}/good`, expect: [{ text: "" }] } }); + expect(r.isError).toBe(true); + }); + }, T); +}); + +describe("browser_verify evidence paths", () => { + test("the DEFAULT evidence dir is confined too (outputDir outside FUSE_CONFINE_WRITES is refused)", async () => { + const root = tmpDir(); + const outside = tmpDir(); + process.env.FUSE_CONFINE_WRITES = root; + try { + await inSession(async (c) => { + const r = await call(c, "browser_verify", { url: `${site.origin}/good`, outputDir: outside, headless: true, expect: [{ visible: "body" }] }); + expect(JSON.stringify(r)).toContain("path_outside_confinement"); + expect(existsSync(join(outside, "verify"))).toBe(false); + }); + } finally { + delete process.env.FUSE_CONFINE_WRITES; + } + }, T); + + test("a receipt baseline may only point at an after.png (no arbitrary file via the '- after:' line)", async () => { + const dir = tmpDir(); + const secret = join(dir, "secret.bin"); + writeFileSync(secret, "not an image"); + const receipt = join(dir, "receipt.md"); + writeFileSync(receipt, `# r\n- after: ${secret}\n`); + await inSession(async (c, sessionId) => { + const r = await call(c, "browser_verify", { sessionId, url: `${site.origin}/good`, evidenceDir: tmpDir(), baseline: receipt, expect: [{ visible: "body" }] }); + expect(r.pass).toBe(false); + expect(r.failed[0].reason).toBe("baseline_not_found"); + expect(r.evidence.before).toBeUndefined(); + }); + expect(readdirSync(dir).length).toBe(2); + }, T); + + test("a failed evidence write is reported as such, not as a confinement refusal", async () => { + const dir = tmpDir(); + const file = join(dir, "afile"); + writeFileSync(file, "x"); + await inSession(async (c, sessionId) => { + const r = await c.callTool({ name: "browser_verify", arguments: { sessionId, url: `${site.origin}/good`, evidenceDir: join(file, "sub"), expect: [{ visible: "body" }] } }); + expect(r.isError).toBe(true); + expect(JSON.stringify(r.structuredContent)).toContain("evidence_write_failed"); + }); + }, T); +});