Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

Pin LM Studio fetches to the DNS answer the guard checked

Barack Sokullu0314ddea7af7
diff --git a/lmstudio-plugin/README.md b/lmstudio-plugin/README.md
index cd39fc0a8..6b81e81b0 100644
--- a/lmstudio-plugin/README.md
+++ b/lmstudio-plugin/README.md
@@ -190,7 +190,7 @@ web-fetching primitives.
The plugin runs in your local Node process, so anything reachable
from that process is reachable from the LLM. The defenses below are
layered — each closes a class of bypass the previous one missed —
-but DNS rebinding is a known residual gap (see end of this section).
+but they are not a hardened sandbox (see end of this section).
**The browser bridge is a separate trust surface from the HTTP tools.**
Everything below concerns `fetch_url` / `research_url`. For `browser_task`:
@@ -216,11 +216,15 @@ Everything below concerns `fetch_url` / `research_url`. For `browser_task`:
cloud-metadata IPs, and `*.local` / `*.internal` / `*.lan` /
`*.home` / `*.corp` / `*.intranet` are blocked. Non-`http(s)`
protocols (`file://`, `ftp://`, `gopher://`, `javascript:`) too.
-- **DNS resolution check.** Before each hop, the hostname is
- resolved via `dns.lookup({all: true})` and every returned A/AAAA
- address is checked against the same private ranges. Closes the
- bypass where `attacker.example A 127.0.0.1` would otherwise pass
- the syntactic check.
+- **DNS resolution check, pinned to the connection.** On each hop the
+ hostname is resolved by the socket's own `lookup` hook via
+ `dns.lookup({all: true})`; every returned A/AAAA address is checked
+ against the same private ranges, and only those checked addresses
+ are dialled. Closes the bypass where `attacker.example A 127.0.0.1`
+ would otherwise pass the syntactic check, and DNS rebinding — a
+ TTL=0 record cannot answer public to the check and private to the
+ connection, because they are the same lookup. Requests use a fresh
+ connection each time, never a pooled socket resolved earlier.
- **Per-redirect re-validation.** Redirects are followed manually
(5 hops max). Each `Location` runs through both checks before we
follow it — a public URL cannot 302 to `http://169.254.169.254/...`.
@@ -240,17 +244,12 @@ Set `allowPrivate: true` on a per-call basis to opt out of the URL
guard + DNS check — useful when you actually want to talk to
localhost services.
-### Known residual gap: DNS rebinding
-
-An attacker controlling a domain with TTL=0 can return a public IP
-when our guard runs `dns.lookup` and a private IP a moment later when
-`fetch` connects. Closing this fully requires pinning the resolved
-IP via a custom `undici` Agent's `connect.lookup` hook so the
-connection uses the exact address we validated. Tracked as a
-follow-up. If you're running this on a cloud VM with sensitive
-instance-metadata endpoints, use a network policy that blocks
-`169.254.169.254` outbound rather than relying solely on this
-plugin's checks.
+### Not a sandbox
+
+These checks only see the address ranges they know about. If you're
+running this on a cloud VM with sensitive instance-metadata
+endpoints, use a network policy that blocks `169.254.169.254`
+outbound rather than relying solely on this plugin's checks.
## License
diff --git a/lmstudio-plugin/package.json b/lmstudio-plugin/package.json
index 095e49478..37caa5349 100644
--- a/lmstudio-plugin/package.json
+++ b/lmstudio-plugin/package.json
@@ -15,7 +15,7 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
- "test": "npm run build && node --test test/browserTask.test.mjs",
+ "test": "npm run build && node --test test/browserTask.test.mjs test/safeFetch.test.mjs",
"clean": "rm -rf dist"
},
"keywords": [
diff --git a/lmstudio-plugin/src/util/safeFetch.ts b/lmstudio-plugin/src/util/safeFetch.ts
index 1833b780d..2b421d124 100644
--- a/lmstudio-plugin/src/util/safeFetch.ts
+++ b/lmstudio-plugin/src/util/safeFetch.ts
@@ -1,8 +1,9 @@
/**
* Safe fetch wrapper for the LM Studio plugin.
*
- * Wraps the native `fetch` to add three security guarantees that are
- * easy to get wrong with the bare API:
+ * Replaces the native `fetch` with a `node:http(s)` request that
+ * returns a standard `Response`, adding three security guarantees that
+ * are easy to get wrong with the bare API:
*
* 1. Every redirect target is re-validated through the URL guard,
* so a public URL can't 30x to `http://169.254.169.254/...` (cloud
@@ -10,13 +11,14 @@
* bare `fetch(..., { redirect: "follow" })` follows redirects
* transparently without the caller getting a chance to intervene.
*
- * 2. Hostnames are resolved at the start of each hop and every
- * returned address is checked against private-IP ranges. This
- * closes the simple bypass where `attacker.example A 127.0.0.1`
- * passes a syntactic hostname check but resolves to localhost.
- * It does NOT fully close DNS-rebinding (TTL=0 returning a
- * different IP between guard and connect) — see the urlGuard
- * header comment for the residual window.
+ * 2. Hostnames are resolved by the socket's own `lookup` hook, which
+ * checks every returned address against private-IP ranges before
+ * handing them to the connection. This closes the bypass where
+ * `attacker.example A 127.0.0.1` passes a syntactic hostname check
+ * but resolves to localhost, and DNS rebinding: the address that
+ * was checked is the address that is dialled, so a TTL=0 record
+ * has no second lookup to answer differently. Global `fetch` can't
+ * do this without an undici Agent, which isn't importable here.
*
* 3. Response bodies are read with a hard byte cap so a malicious
* or accidental gigabyte response can't OOM the plugin. Chunks
@@ -29,7 +31,12 @@
* open-redirect chain.
*/
-import { lookup as dnsLookup } from "node:dns/promises";
+import { lookup as dnsLookup, type LookupAddress } from "node:dns";
+import * as http from "node:http";
+import * as https from "node:https";
+import type { LookupFunction } from "node:net";
+import { pipeline, Readable } from "node:stream";
+import * as zlib from "node:zlib";
import {
assertSafeUrl,
isPrivateIpv4,
@@ -67,40 +74,13 @@ function stripCrossOriginHeaders(
}
/**
- * Resolve a hostname's A/AAAA records and reject if any address is in
- * a private range. Literal IPs are short-circuited (the sync URL guard
- * already covered them).
+ * Reject if any resolved address is in a private range.
*
- * Why we check ALL returned addresses rather than just the first one
- * fetch will use: defense-in-depth against accidentally-misconfigured
- * dual-stack hosts and against future fetch-implementation changes
- * about which family wins in `lookup({ all: false })`.
+ * Why we check ALL returned addresses rather than just the first one:
+ * Node's happy-eyeballs connect may try any of them, and it is
+ * defense-in-depth against accidentally-misconfigured dual-stack hosts.
*/
-async function assertHostnameDoesNotResolveToPrivate(
- parsed: URL,
- opts: UrlGuardOptions,
-): Promise<void> {
- if (opts.allowPrivate) return;
-
- // Strip the [..] wrapper IPv6 URL syntax adds.
- let host = parsed.hostname;
- if (host.startsWith("[") && host.endsWith("]")) {
- host = host.slice(1, -1);
- }
-
- // Literal IP — the sync guard already validated. Skip DNS.
- if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) return;
- if (host.includes(":")) return; // literal IPv6
-
- let addresses: Array<{ address: string; family: number }>;
- try {
- addresses = await dnsLookup(host, { all: true });
- } catch (e) {
- // Resolution failure isn't a security signal — let the subsequent
- // fetch surface a clean error. Don't fail the guard here.
- return;
- }
-
+function assertAddressesArePublic(host: string, addresses: LookupAddress[]): void {
for (const { address, family } of addresses) {
if (family === 4 && isPrivateIpv4(address)) {
throw new Error(
@@ -115,6 +95,200 @@ async function assertHostnameDoesNotResolveToPrivate(
}
}
+/**
+ * `lookup` hook for the request socket. Node calls it when connecting
+ * and dials only the addresses it hands back, so the check and the use
+ * are the same resolution — resolving first and then letting the HTTP
+ * client resolve the name again would let a TTL=0 record answer public
+ * to the check and private to the connection. Literal-IP hosts never
+ * reach a lookup; the sync URL guard covers them.
+ */
+const guardedLookup: LookupFunction = (hostname, options, callback) => {
+ dnsLookup(hostname, { ...options, all: true }, (err, addresses) => {
+ if (err) {
+ callback(err, "");
+ return;
+ }
+ try {
+ if (addresses.length === 0) throw new Error(`No addresses found for ${hostname}`);
+ assertAddressesArePublic(hostname, addresses);
+ } catch (e) {
+ callback(e as NodeJS.ErrnoException, "");
+ return;
+ }
+ if (options.all) callback(null, addresses);
+ else callback(null, addresses[0]!.address, addresses[0]!.family);
+ });
+};
+
+/** Statuses whose Response must have a null body (Fetch standard). */
+const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
+/** Lenient flushing, as fetch uses, so a truncated stream still yields what decoded. */
+const ZLIB_OPTIONS = {
+ flush: zlib.constants.Z_SYNC_FLUSH,
+ finishFlush: zlib.constants.Z_SYNC_FLUSH,
+};
+const BROTLI_OPTIONS = {
+ flush: zlib.constants.BROTLI_OPERATION_FLUSH,
+ finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,
+};
+
+function abortReason(signal: AbortSignal): Error {
+ return signal.reason ??
+ Object.assign(new Error("This operation was aborted"), { name: "AbortError" });
+}
+
+interface HopInit {
+ method: string;
+ headers: Record<string, string>;
+ body: string | undefined;
+ signal?: AbortSignal;
+}
+
+/**
+ * Headers fetch adds on its own. Without them some servers refuse the
+ * request (no User-Agent) or skip compression. Caller values win.
+ */
+function withFetchDefaultHeaders(
+ headers: Record<string, string>,
+ body: string | undefined,
+): Record<string, string> {
+ const out = { ...headers };
+ const present = new Set(Object.keys(out).map((k) => k.toLowerCase()));
+ const defaults: Array<[string, string]> = [
+ ["accept", "*/*"],
+ ["accept-encoding", "gzip, deflate, br"],
+ ["user-agent", "node"],
+ ];
+ if (body !== undefined) defaults.push(["content-type", "text/plain;charset=UTF-8"]);
+ for (const [k, v] of defaults) {
+ if (!present.has(k)) out[k] = v;
+ }
+ return out;
+}
+
+/**
+ * Undo Content-Encoding like fetch: gzip / deflate / br, last-applied
+ * first. An unknown coding leaves the body as it came.
+ */
+function decodeBody(incoming: http.IncomingMessage): Readable {
+ const codings = (incoming.headers["content-encoding"] || "")
+ .toLowerCase()
+ .split(",")
+ .map((c) => c.trim())
+ .filter(Boolean)
+ .reverse();
+ if (codings.length === 0) return incoming;
+ const decoders: NodeJS.ReadWriteStream[] = [];
+ for (const coding of codings) {
+ if (coding === "gzip" || coding === "x-gzip") decoders.push(zlib.createGunzip(ZLIB_OPTIONS));
+ else if (coding === "deflate") decoders.push(zlib.createInflate(ZLIB_OPTIONS));
+ else if (coding === "br") decoders.push(zlib.createBrotliDecompress(BROTLI_OPTIONS));
+ else return incoming;
+ }
+ // pipeline destroys every stage when one fails or the last is
+ // destroyed (e.g. readBodyCapped cancelling), which closes the socket.
+ return pipeline([incoming, ...decoders], () => {}) as unknown as Readable;
+}
+
+/**
+ * Send one request (no redirect following) over a connection whose
+ * address went through `guardedLookup`, and wrap the reply in a
+ * standard `Response` with `url` set, as fetch would return it.
+ */
+function pinnedFetch(url: URL, init: HopInit, opts: UrlGuardOptions): Promise<Response> {
+ return new Promise((resolve, reject) => {
+ const { signal } = init;
+ if (url.username || url.password) {
+ reject(new TypeError(
+ `Request cannot be constructed from a URL that includes credentials: ${url}`,
+ ));
+ return;
+ }
+ if (signal?.aborted) {
+ reject(abortReason(signal));
+ return;
+ }
+
+ let req: http.ClientRequest;
+ try {
+ req = (url.protocol === "https:" ? https : http).request(url, {
+ method: init.method,
+ headers: withFetchDefaultHeaders(init.headers, init.body),
+ // A fresh connection per request: a pooled keep-alive socket was
+ // resolved for whichever request opened it (possibly one with
+ // allowPrivate), so reusing it would skip this request's lookup.
+ agent: false,
+ ...(opts.allowPrivate ? {} : { lookup: guardedLookup }),
+ });
+ } catch (e) {
+ reject(e);
+ return;
+ }
+
+ const onAbort = () => req.destroy(abortReason(signal!));
+ signal?.addEventListener("abort", onAbort, { once: true });
+ // Kept for the request's lifetime: a late socket error with no
+ // listener would crash the plugin process.
+ req.on("error", (e) => {
+ signal?.removeEventListener("abort", onAbort);
+ reject(e);
+ });
+ req.once("response", (incoming) => {
+ signal?.removeEventListener("abort", onAbort);
+ try {
+ resolve(toFetchResponse(incoming, url, init.method, signal));
+ } catch (e) {
+ incoming.destroy();
+ reject(e);
+ }
+ });
+ req.end(init.body);
+ });
+}
+
+function toFetchResponse(
+ incoming: http.IncomingMessage,
+ url: URL,
+ method: string,
+ signal: AbortSignal | undefined,
+): Response {
+ const status = incoming.statusCode ?? 0;
+ if (status < 200 || status > 599) {
+ throw new Error(`Unsupported HTTP status ${status} from ${url.origin}`);
+ }
+ const headers = new Headers();
+ for (let i = 0; i + 1 < incoming.rawHeaders.length; i += 2) {
+ headers.append(incoming.rawHeaders[i]!, incoming.rawHeaders[i + 1]!);
+ }
+
+ let body: ReadableStream<Uint8Array> | null = null;
+ if (method === "HEAD" || NULL_BODY_STATUSES.has(status)) {
+ incoming.on("error", () => {});
+ incoming.resume();
+ } else {
+ const decoded = decodeBody(incoming);
+ if (signal) {
+ // Aborting mid-body errors the stream with the abort reason, as fetch does.
+ const onAbort = () => decoded.destroy(abortReason(signal));
+ signal.addEventListener("abort", onAbort, { once: true });
+ decoded.once("close", () => signal.removeEventListener("abort", onAbort));
+ }
+ body = Readable.toWeb(decoded) as unknown as ReadableStream<Uint8Array>;
+ }
+
+ // Response's constructor rejects reason phrases fetch would accept;
+ // the phrase is cosmetic.
+ const statusMessage = incoming.statusMessage ?? "";
+ const statusText = /^[\t\x20-\x7e\x80-\xff]*$/.test(statusMessage) ? statusMessage : "";
+ const res = new Response(body, { status, statusText, headers });
+ // Only fetch() can set Response.url; callers report it as the final URL.
+ const finalUrl = new URL(url);
+ finalUrl.hash = "";
+ Object.defineProperty(res, "url", { value: finalUrl.toString() });
+ return res;
+}
+
export interface SafeFetchInit {
method?: string;
headers?: Record<string, string>;
@@ -132,8 +306,9 @@ export interface SafeFetchInit {
* NOT been consumed — caller is responsible for reading it (use
* `readBodyCapped` to apply the streaming size limit).
*
- * Uses `redirect: "manual"` under the hood so we can intercept each
- * 3xx Location header. On exhausting the hop budget, throws.
+ * Follows redirects manually so we can intercept each 3xx Location
+ * header; every hop connects through the same pinned, guarded lookup.
+ * On exhausting the hop budget, throws.
*/
export async function safeFetch(
initialUrl: string,
@@ -142,11 +317,11 @@ export async function safeFetch(
const allowPrivate = !!init.allowPrivate;
const maxRedirects = init.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
- // Initial URL goes through the full guard (sync structural check
- // + DNS resolution). Throws on a private hostname / IP / TLD.
+ // Initial URL goes through the sync structural check here; DNS
+ // resolution is checked when the connection is made (guardedLookup).
+ // Throws on a private hostname / IP / TLD.
let current: URL;
current = assertSafeUrl(initialUrl, { allowPrivate });
- await assertHostnameDoesNotResolveToPrivate(current, { allowPrivate });
let originForCredentials = current.origin;
let headers = { ...(init.headers || {}) };
@@ -156,15 +331,20 @@ export async function safeFetch(
// every redirect to keep the surface predictable).
let method = (init.method || "GET").toUpperCase();
let body: string | undefined = init.body;
+ // The same requests fetch() refused before node:http replaced it.
+ if (method === "CONNECT" || method === "TRACE" || method === "TRACK") {
+ throw new TypeError(`'${method}' HTTP method is unsupported.`);
+ }
+ if (body !== undefined && (method === "GET" || method === "HEAD")) {
+ throw new TypeError("Request with GET/HEAD method cannot have body.");
+ }
for (let hop = 0; hop <= maxRedirects; hop++) {
- const res = await fetch(current.toString(), {
- method,
- headers,
- body,
- redirect: "manual",
- ...(init.signal ? { signal: init.signal } : {}),
- });
+ const res = await pinnedFetch(
+ current,
+ { method, headers, body, ...(init.signal ? { signal: init.signal } : {}) },
+ { allowPrivate },
+ );
// Not a redirect — return as-is. Caller reads the body.
if (res.status < 300 || res.status >= 400) return res;
@@ -172,6 +352,9 @@ export async function safeFetch(
const location = res.headers.get("location");
if (!location) return res; // 3xx without Location — let caller see it.
+ // Redirect bodies are never read; release the connection.
+ await res.body?.cancel().catch(() => {});
+
let next: URL;
try {
next = new URL(location, current);
@@ -179,10 +362,9 @@ export async function safeFetch(
throw new Error(`Invalid redirect Location: ${location}`);
}
- // Re-validate the redirect target. Both sync (protocol /
- // hostname-pattern checks) and async (DNS resolution).
+ // Re-validate the redirect target: sync protocol / hostname-pattern
+ // checks here, DNS resolution when the next hop connects.
next = assertSafeUrl(next.toString(), { allowPrivate });
- await assertHostnameDoesNotResolveToPrivate(next, { allowPrivate });
// Cross-origin redirect → drop sensitive headers.
headers = stripCrossOriginHeaders(headers, originForCredentials, next.origin);
diff --git a/lmstudio-plugin/src/util/urlGuard.ts b/lmstudio-plugin/src/util/urlGuard.ts
index 2f95374b7..d2773d386 100644
--- a/lmstudio-plugin/src/util/urlGuard.ts
+++ b/lmstudio-plugin/src/util/urlGuard.ts
@@ -15,23 +15,20 @@
* - literal RFC1918 / loopback / link-local / ULA IPv6 hostnames
* - common private DNS spellings (localhost, *.local, *.internal, *.lan)
*
- * The DNS-resolution-aware check
- * (`assertHostnameDoesNotResolveToPrivate`) lives in `safeFetch.ts`
- * because it requires `node:dns` and is awaited once per redirect hop
- * inside the `safeFetch` wrapper. That additional layer closes the case
+ * The DNS-resolution-aware check (`guardedLookup`) lives in
+ * `safeFetch.ts` because it requires `node:dns`. It runs as the request
+ * socket's `lookup` hook on every hop, so the connection can only use
+ * addresses that passed it. That additional layer closes the case
* where a public-looking hostname has an A record pointing into
* RFC1918 / loopback / link-local space, e.g. `attacker.example A
- * 127.0.0.1`. `isPrivateIpv4` / `isPrivateIpv6` are exported so the
- * resolver-side check reuses the same range definitions.
+ * 127.0.0.1`, and DNS rebinding (a TTL=0 record answering public to a
+ * check and private to the connection), because there is no separate
+ * check to answer. `isPrivateIpv4` / `isPrivateIpv6` are exported so
+ * the resolver-side check reuses the same range definitions.
*
- * Residual gap: DNS rebinding. An attacker controlling a domain with
- * TTL=0 can return a public IP at the time of the guard check and a
- * private IP at the time `fetch` connects. Closing this fully requires
- * pinning the resolved IP via a custom undici Agent + `lookup` hook —
- * tracked as a follow-up. The current layered defense (sync check +
- * DNS check + per-redirect re-validation) raises the bar enough to
- * stop drive-by SSRF from open redirects and naive hostname tricks
- * but is NOT a hardened sandbox.
+ * The layered defense (sync check + connect-time DNS check +
+ * per-redirect re-validation) stops drive-by SSRF from open redirects,
+ * naive hostname tricks and rebinding, but is NOT a hardened sandbox.
*
* To opt-out (e.g. you really do want to point this at your intranet)
* call assertSafeUrl(url, { allowPrivate: true }) and pass the same
diff --git a/lmstudio-plugin/test/safeFetch.test.mjs b/lmstudio-plugin/test/safeFetch.test.mjs
new file mode 100644
index 000000000..92c4fce9c
--- /dev/null
+++ b/lmstudio-plugin/test/safeFetch.test.mjs
@@ -0,0 +1,141 @@
+import assert from "node:assert/strict";
+import dns from "node:dns";
+import { once } from "node:events";
+import { createServer } from "node:http";
+import { gzipSync } from "node:zlib";
+import { after, afterEach, before, test } from "node:test";
+
+import { readBodyCapped, safeFetch } from "../dist/util/safeFetch.js";
+
+const originalLookup = dns.lookup;
+const originalPromisesLookup = dns.promises.lookup;
+
+let server;
+let port;
+const hits = [];
+
+before(async () => {
+ server = createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk) => { body += chunk; });
+ req.on("end", () => {
+ hits.push({ method: req.method, url: req.url, host: req.headers.host, body });
+ if (req.url === "/start") {
+ res.writeHead(302, { location: "/final" });
+ res.end();
+ } else if (req.url === "/final") {
+ res.writeHead(200, { "content-type": "text/plain", "content-encoding": "gzip" });
+ res.end(gzipSync("hello pinned"));
+ } else if (req.url === "/echo") {
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end(`${req.method} ${req.headers["content-type"]} ${body}`);
+ } else if (req.url === "/slow") {
+ // Never answers; the caller's signal has to end the request.
+ } else {
+ res.writeHead(200, { "content-type": "text/plain" });
+ res.end("internal secret");
+ }
+ });
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ port = server.address().port;
+});
+
+after(() => {
+ server.closeAllConnections();
+ server.close();
+});
+
+afterEach(() => {
+ dns.lookup = originalLookup;
+ dns.promises.lookup = originalPromisesLookup;
+ hits.length = 0;
+});
+
+/**
+ * Answer each resolution of `hostname` with the next entry of `answers`
+ * (the last one repeats), through both the callback and promise DNS
+ * APIs — like an attacker's TTL=0 record that changes between queries.
+ */
+function fakeDns(hostname, answers) {
+ let calls = 0;
+ const next = () => answers[Math.min(calls++, answers.length - 1)];
+ dns.lookup = function (host, options, callback) {
+ if (typeof options === "function") {
+ callback = options;
+ options = {};
+ }
+ if (host !== hostname) return originalLookup.call(this, host, options, callback);
+ const addresses = next();
+ process.nextTick(() => {
+ if (options?.all) callback(null, addresses);
+ else callback(null, addresses[0].address, addresses[0].family);
+ });
+ };
+ dns.promises.lookup = async (host, options) => {
+ if (host !== hostname) return originalPromisesLookup(host, options);
+ const addresses = next();
+ return options?.all ? addresses : addresses[0];
+ };
+}
+
+const PUBLIC = { address: "192.0.2.10", family: 4 }; // TEST-NET-1: public to the guard, never routed
+const LOOPBACK = { address: "127.0.0.1", family: 4 };
+
+test("a DNS answer that changes after the check cannot move the connection to a private address", async () => {
+ fakeDns("rebind.example", [[PUBLIC], [LOOPBACK]]);
+
+ // The connection may only use the answer that was validated (PUBLIC),
+ // which is unroutable, so the request fails or times out. Before the
+ // fix, fetch resolved the name again and reached the loopback server.
+ await assert.rejects(
+ safeFetch(`http://rebind.example:${port}/secret`, { signal: AbortSignal.timeout(1500) }),
+ );
+ assert.deepEqual(hits, []);
+});
+
+test("every address the connection could use is checked before connecting", async () => {
+ fakeDns("mixed.example", [[PUBLIC, LOOPBACK]]);
+
+ await assert.rejects(
+ safeFetch(`http://mixed.example:${port}/secret`),
+ /resolves to private IPv4 127\.0\.0\.1/,
+ );
+ assert.deepEqual(hits, []);
+});
+
+test("allowPrivate requests follow redirects and keep the fetch response shape", async () => {
+ fakeDns("intranet.example", [[LOOPBACK]]);
+
+ const res = await safeFetch(`http://intranet.example:${port}/start`, { allowPrivate: true });
+ assert.equal(res.status, 200);
+ assert.equal(res.ok, true);
+ assert.equal(res.url, `http://intranet.example:${port}/final`);
+ assert.equal(res.headers.get("content-type"), "text/plain");
+ const { text, truncated } = await readBodyCapped(res, 1024);
+ assert.equal(text, "hello pinned");
+ assert.equal(truncated, false);
+ assert.deepEqual(hits.map((hit) => [hit.url, hit.host]), [
+ ["/start", `intranet.example:${port}`],
+ ["/final", `intranet.example:${port}`],
+ ]);
+
+ const echo = await safeFetch(`http://intranet.example:${port}/echo`, {
+ method: "post",
+ body: "a=1",
+ allowPrivate: true,
+ });
+ assert.equal(await echo.text(), "POST text/plain;charset=UTF-8 a=1");
+});
+
+test("aborting a pending request rejects with an AbortError", async () => {
+ fakeDns("intranet.example", [[LOOPBACK]]);
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(), 100);
+
+ await assert.rejects(
+ safeFetch(`http://intranet.example:${port}/slow`, { allowPrivate: true, signal: controller.signal }),
+ { name: "AbortError" },
+ );
+});
diff --git a/web/docs/lm-studio/index.html b/web/docs/lm-studio/index.html
index 5c7af9591..16ea875c8 100644
--- a/web/docs/lm-studio/index.html
+++ b/web/docs/lm-studio/index.html
@@ -47,7 +47,7 @@ lms dev --install</code></pre><p>See LM Studio’s current <a href="https://lmst
<section class="doc-section" id="lifecycle"><h2>Let continuing browser runs continue</h2><p><code>browser_task</code> waits for a result, but its timeout does not cancel work already running in the extension. Keep the returned <code>runId</code> and use the recovery tool that matches the state.</p><div class="status-strip" aria-label="LM Studio browser task statuses"><div class="status-item"><code>running</code><span>Poll with browser_status</span></div><div class="status-item waiting"><code>needs_user_input</code><span>Ask, then browser_respond</span></div><div class="status-item done"><code>completed</code><span>Result is ready</span></div><div class="status-item"><code>failed</code><span>Read the error and evidence</span></div><div class="status-item"><code>aborted</code><span>Stopped; earlier actions remain</span></div></div><ul><li>Do not start a duplicate <code>browser_task</code> after a timeout; poll the existing run.</li><li>Never invent an answer to a WebBrain clarification. Ask the human and forward their response verbatim.</li><li><code>browser_abort</code> stops future steps. It cannot undo a submitted form, sent message, or other completed action.</li></ul></section>
- <section class="doc-section" id="security"><h2>Keep the two trust surfaces clear</h2><ul><li><strong>Public HTTP runs in the local plugin process.</strong> <code>fetch_url</code> can send methods, headers, and bodies, so only request a mutation when you intend one.</li><li><strong>Private network targets are blocked by default.</strong> Loopback, RFC1918, link-local, cloud-metadata, and common intranet hostnames are refused. Use <code>allowPrivate: true</code> only for an explicit local-network task you understand.</li><li><strong>Redirects are rechecked.</strong> The plugin validates each destination and strips credential-like headers when a redirect crosses origins.</li><li><strong>The browser listener stays on loopback.</strong> Never forward or proxy port <code>17375</code>. The extension handshake identifies the client but is not shared-secret authentication; treat local software as trusted.</li><li><strong>Ask mode is the default.</strong> Use Act only when the requested outcome requires visible browser interaction, and keep the browser where you can stop unexpected behavior.</li><li><strong>The LM Studio model sees tool results.</strong> A browser run also sends task context through the active provider configured inside WebBrain. Choose both model boundaries deliberately.</li></ul><p>For the implementation-level details and residual DNS-rebinding limitation, read the plugin’s <a href="https://github.com/webbrain-one/webbrain/blob/main/lmstudio-plugin/README.md#safety-notes">safety notes</a>.</p></section>
+ <section class="doc-section" id="security"><h2>Keep the two trust surfaces clear</h2><ul><li><strong>Public HTTP runs in the local plugin process.</strong> <code>fetch_url</code> can send methods, headers, and bodies, so only request a mutation when you intend one.</li><li><strong>Private network targets are blocked by default.</strong> Loopback, RFC1918, link-local, cloud-metadata, and common intranet hostnames are refused. Use <code>allowPrivate: true</code> only for an explicit local-network task you understand.</li><li><strong>Redirects are rechecked.</strong> The plugin validates each destination and strips credential-like headers when a redirect crosses origins.</li><li><strong>The browser listener stays on loopback.</strong> Never forward or proxy port <code>17375</code>. The extension handshake identifies the client but is not shared-secret authentication; treat local software as trusted.</li><li><strong>Ask mode is the default.</strong> Use Act only when the requested outcome requires visible browser interaction, and keep the browser where you can stop unexpected behavior.</li><li><strong>The LM Studio model sees tool results.</strong> A browser run also sends task context through the active provider configured inside WebBrain. Choose both model boundaries deliberately.</li></ul><p>For the implementation-level details, including how each connection is pinned to the address that was checked, read the plugin’s <a href="https://github.com/webbrain-one/webbrain/blob/main/lmstudio-plugin/README.md#safety-notes">safety notes</a>.</p></section>
<section class="doc-section" id="troubleshooting"><h2>Troubleshooting by symptom</h2><div class="table-wrap"><table><thead><tr><th>Symptom</th><th>What it usually means</th><th>Fix</th></tr></thead><tbody><tr><td>The tools do not appear</td><td>The plugin is not enabled for this chat, or the selected model cannot call tools.</td><td>Enable <strong>webbrain/web-tools</strong> beside the chat input and select a tool-capable model.</td></tr><tr><td><code>browser_status</code> reports disconnected</td><td>The plugin is available, but the WebBrain extension has not attached.</td><td>Use Chromium, enable MCP, and enter exactly <code>ws://127.0.0.1:17375/extension</code>.</td></tr><tr><td>The listener cannot start or reports an address conflict</td><td>Another plugin instance or process already owns port <code>17375</code>.</td><td>Close the duplicate instance, then reload the plugin. Inspect first with <code>lsof -nP -iTCP:17375 -sTCP:LISTEN</code>.</td></tr><tr><td>A public page is empty</td><td>The page renders with JavaScript or hides content behind login.</td><td>If <code>spaSuspected</code> is true, connect the extension and use <code>browser_task</code>.</td></tr><tr><td>The task timed out but the browser is still moving</td><td>The wait budget ended without cancelling the WebBrain run.</td><td>Call <code>browser_status</code> with the returned <code>runId</code>, or <code>browser_abort</code> if you want it stopped.</td></tr><tr><td>Firefox never connects</td><td>Firefox has no offscreen-document bridge runtime.</td><td>Use a Chromium browser for browser tools. The two public HTTP tools remain usable without any extension.</td></tr><tr><td>MCP or WebBrain Cloud disconnected</td><td>The LM Studio URL replaced the extension’s one bridge destination.</td><td>Switch Settings back to port <code>17374</code> for MCP or <code>17373</code> for WebBrain Cloud when finished.</td></tr></tbody></table></div></section>
diff --git a/web/docs/zh/lm-studio/index.html b/web/docs/zh/lm-studio/index.html
index 634924b6d..d8c2bd4fd 100644
--- a/web/docs/zh/lm-studio/index.html
+++ b/web/docs/zh/lm-studio/index.html
@@ -48,7 +48,7 @@ lms dev --install</code></pre><p>参阅 LM Studio 的 <a href="https://lmstudio.
<section class="doc-section" id="lifecycle"><h2>让正在进行的浏览器运行继续</h2><p><code>browser_task</code> 会等待结果,但其超时不会取消扩展中已在运行的工作。保留返回的 <code>runId</code>,并使用与状态匹配的恢复工具。</p><div class="status-strip" aria-label="LM Studio 浏览器任务状态"><div class="status-item"><code>running</code><span>使用 browser_status 轮询</span></div><div class="status-item waiting"><code>needs_user_input</code><span>提问,然后使用 browser_respond</span></div><div class="status-item done"><code>completed</code><span>结果已就绪</span></div><div class="status-item"><code>failed</code><span>查看错误和证据</span></div><div class="status-item"><code>aborted</code><span>已停止;之前的操作仍然有效</span></div></div><ul><li>超时后不要启动重复的 <code>browser_task</code>;轮询现有运行。</li><li>永远不要为 WebBrain 的澄清问题编造答案。询问用户并逐字转发他们的回答。</li><li><code>browser_abort</code> 停止后续步骤。它无法撤销已提交的表单、已发送的消息或其他已完成的操作。</li></ul></section>
- <section class="doc-section" id="security"><h2>保持两个信任面清晰</h2><ul><li><strong>公开 HTTP 在本地插件进程中运行。</strong><code>fetch_url</code> 可以发送方法、请求头和请求体,因此仅在你有意时才请求修改操作。</li><li><strong>默认阻止私有网络目标。</strong>本地回环、RFC1918、链路本地、云元数据和常见内网主机名均被拒绝。仅在你理解的明确本地网络任务中使用 <code>allowPrivate: true</code>。</li><li><strong>重定向会被重新检查。</strong>插件会验证每个目标,并在重定向跨域时去除类似凭据的请求头。</li><li><strong>浏览器监听器保持在本地回环。</strong>永远不要转发或代理端口 <code>17375</code>。扩展握手可以识别客户端但不是共享密钥认证;将本地软件视为可信软件。</li><li><strong>Ask 模式是默认选项。</strong>仅在请求的结果需要可见浏览器交互时使用 Act,并保持浏览器在你可以停止意外行为的范围内。</li><li><strong>LM Studio 模型可以看到工具结果。</strong>浏览器运行还会通过 WebBrain 内配置的活跃提供商发送任务上下文。请慎重选择两个模型的边界。</li></ul><p>有关实现级别的细节和残余 DNS 重绑定限制,请阅读插件的 <a href="https://github.com/webbrain-one/webbrain/blob/main/lmstudio-plugin/README.md#safety-notes">安全说明</a>。</p></section>
+ <section class="doc-section" id="security"><h2>保持两个信任面清晰</h2><ul><li><strong>公开 HTTP 在本地插件进程中运行。</strong><code>fetch_url</code> 可以发送方法、请求头和请求体,因此仅在你有意时才请求修改操作。</li><li><strong>默认阻止私有网络目标。</strong>本地回环、RFC1918、链路本地、云元数据和常见内网主机名均被拒绝。仅在你理解的明确本地网络任务中使用 <code>allowPrivate: true</code>。</li><li><strong>重定向会被重新检查。</strong>插件会验证每个目标,并在重定向跨域时去除类似凭据的请求头。</li><li><strong>浏览器监听器保持在本地回环。</strong>永远不要转发或代理端口 <code>17375</code>。扩展握手可以识别客户端但不是共享密钥认证;将本地软件视为可信软件。</li><li><strong>Ask 模式是默认选项。</strong>仅在请求的结果需要可见浏览器交互时使用 Act,并保持浏览器在你可以停止意外行为的范围内。</li><li><strong>LM Studio 模型可以看到工具结果。</strong>浏览器运行还会通过 WebBrain 内配置的活跃提供商发送任务上下文。请慎重选择两个模型的边界。</li></ul><p>有关实现级别的细节(包括每个连接如何固定到已检查的地址),请阅读插件的 <a href="https://github.com/webbrain-one/webbrain/blob/main/lmstudio-plugin/README.md#safety-notes">安全说明</a>。</p></section>
<section class="doc-section" id="troubleshooting"><h2>按症状排查</h2><div class="table-wrap"><table><thead><tr><th>症状</th><th>通常含义</th><th>解决方法</th></tr></thead><tbody><tr><td>工具没有出现</td><td>此聊天未启用插件,或所选模型无法调用工具。</td><td>在聊天输入旁启用 <strong>webbrain/web-tools</strong>,并选择支持工具的模型。</td></tr><tr><td><code>browser_status</code> 报告已断开连接</td><td>插件可用,但 WebBrain 扩展尚未连接。</td><td>使用 Chromium,启用云桥接,并精确输入 <code>ws://127.0.0.1:17375/extension</code>。</td></tr><tr><td>监听器无法启动或报告地址冲突</td><td>另一个插件实例或进程已占用端口 <code>17375</code>。</td><td>关闭重复实例,然后重新加载插件。先使用 <code>lsof -nP -iTCP:17375 -sTCP:LISTEN</code> 检查。</td></tr><tr><td>公开页面为空</td><td>页面使用 JavaScript 渲染或将内容隐藏在登录后。</td><td>如果 <code>spaSuspected</code> 为 true,连接扩展并使用 <code>browser_task</code>。</td></tr><tr><td>任务超时但浏览器仍在操作</td><td>等待预算已用尽,但 WebBrain 运行未被取消。</td><td>使用返回的 <code>runId</code> 调用 <code>browser_status</code>,或在需要停止时使用 <code>browser_abort</code>。</td></tr><tr><td>Firefox 始终无法连接</td><td>Firefox 没有离屏文档桥接运行时。</td><td>使用 Chromium 浏览器进行浏览器工具操作。两个公开 HTTP 工具无需扩展即可使用。</td></tr><tr><td>MCP 或 WebBrain Cloud 已断开连接</td><td>LM Studio URL 替换了扩展的单个桥接目标。</td><td>完成后将设置切换回端口 <code>17374</code>(MCP)或 <code>17373</code>(WebBrain Cloud)。</td></tr></tbody></table></div></section>