Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: pin catalog URL-ingest Chrome fetch against DNS-rebinding TOCTOU (#2068)

Adam Eivya5e06071a61d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7f39a644f3..a630ce7d8d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,8 @@
## Security
-- **RSS feed fetches now pin the connection to the SSRF-vetted IP, closing a DNS-rebinding TOCTOU.** `feeds.js` previously resolved a feed hostname, verified it wasn't private, then made a *separate, unpinned* fetch — undici re-resolved at connect time, so an attacker's DNS could answer public during validation and private (home-network / cloud-metadata) at the actual connect. Feed fetches now route through the shared `safeUrlFetch` guard (the same one moodBoard/Pinterest uses since #1859): the hostname is resolved once and the connection is pinned to that exact vetted address, re-validated and re-pinned on every redirect hop. `safeUrlFetch` gained a strict `blockPrivate` mode so feeds keep their historical block-all-private posture (an arbitrary user-added feed URL still can't be aimed at the LAN) while gaining the pin, and a `throwOnUnsafe: false` option so the feeds path returns its existing friendly "Could not fetch feed" result instead of a bubbled 400 (#2046). The catalog URL-ingest path (Chrome/CDP) has a residual rebinding gap tracked separately.
+- **RSS feed fetches now pin the connection to the SSRF-vetted IP, closing a DNS-rebinding TOCTOU.** `feeds.js` previously resolved a feed hostname, verified it wasn't private, then made a *separate, unpinned* fetch — undici re-resolved at connect time, so an attacker's DNS could answer public during validation and private (home-network / cloud-metadata) at the actual connect. Feed fetches now route through the shared `safeUrlFetch` guard (the same one moodBoard/Pinterest uses since #1859): the hostname is resolved once and the connection is pinned to that exact vetted address, re-validated and re-pinned on every redirect hop. `safeUrlFetch` gained a strict `blockPrivate` mode so feeds keep their historical block-all-private posture (an arbitrary user-added feed URL still can't be aimed at the LAN) while gaining the pin, and a `throwOnUnsafe: false` option so the feeds path returns its existing friendly "Could not fetch feed" result instead of a bubbled 400 (#2046).
+- **Catalog URL-ingest (Chrome/CDP) now verifies Chrome's actual connection IP, closing the last DNS-rebinding gap.** Catalog "ingest from URL" pre-checked the hostname with a `dns.lookup` but then handed the fetch to Chrome, which re-resolves DNS itself — so a rebinding answer could steer Chrome to a loopback/link-local/cloud-metadata address after validation passed (a TOCTOU the undici pin in #2046 couldn't cover for a browser). Ingest now navigates through a pinned path (`navigateToUrlPinned`) that opens a blank tab, subscribes to CDP Network events, then drives the navigation — verifying against Chrome's OWN reported `remoteIPAddress` that every main-frame hop (initial request + each redirect) connected to a non-blocked address, and failing closed (tab torn down, ingest refused) before the DOM is ever read otherwise. The landed-URL hostname re-check is kept as defense-in-depth for in-page/JS redirects (#2068).
## Workspace Contexts
diff --git a/server/services/browserService.js b/server/services/browserService.js
index 44a3b7b811..19195edd67 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -279,6 +279,159 @@ export async function navigateToUrl(url) {
return { id: page.id, title: page.title || '(loading)', url: page.url, type: page.type };
}
+// ---------- CDP pinned navigation (SSRF: verify Chrome's ACTUAL connect IP) ----------
+
+/**
+ * Extract the main-frame document's network hops (initial request + every HTTP
+ * redirect + final response) from a captured stream of CDP Network events, each
+ * annotated with the *actual* IP Chrome connected to (`remoteIPAddress`).
+ *
+ * CDP marks the main document load with `requestId === loaderId`; redirects
+ * reuse that requestId and arrive as a `redirectResponse` on the following
+ * `Network.requestWillBeSent`, and the final hop lands as a
+ * `Network.responseReceived` with the same requestId. So walking these in order
+ * reconstructs every address Chrome dialed for the top document — the thing a
+ * pre-navigation `dns.lookup` can't know, because Chrome resolves DNS itself
+ * (the rebinding TOCTOU).
+ *
+ * Pure + exported so the SSRF-pin decision is unit-testable without a live
+ * browser. Returns `{ hops: [{ url, remoteIPAddress, status }], finalUrl,
+ * mainRequestId }`.
+ */
+export function pickMainFrameHops(messages) {
+ let mainRequestId = null;
+ const hops = [];
+ let finalUrl = null;
+ for (const msg of messages) {
+ const p = msg?.params;
+ if (!p) continue;
+ if (msg.method === 'Network.requestWillBeSent') {
+ // The first Document request whose requestId equals its loaderId is the
+ // top-level navigation; ignore sub-resource / sub-frame requests.
+ if (mainRequestId === null && p.type === 'Document' && p.requestId && p.requestId === p.loaderId) {
+ mainRequestId = p.requestId;
+ }
+ if (p.requestId === mainRequestId && p.redirectResponse) {
+ hops.push({
+ url: p.redirectResponse.url || null,
+ remoteIPAddress: p.redirectResponse.remoteIPAddress || '',
+ status: p.redirectResponse.status ?? null,
+ });
+ }
+ } else if (msg.method === 'Network.responseReceived') {
+ if (mainRequestId !== null && p.requestId === mainRequestId && p.response) {
+ hops.push({
+ url: p.response.url || null,
+ remoteIPAddress: p.response.remoteIPAddress || '',
+ status: p.response.status ?? null,
+ });
+ finalUrl = p.response.url || finalUrl;
+ }
+ }
+ }
+ return { hops, finalUrl, mainRequestId };
+}
+
+// Close a CDP tab by target id (best-effort). Used to fail closed after an
+// SSRF-pin refusal so a tab that connected to a disallowed address is torn down
+// rather than left open for the DOM reader.
+async function closeCdpPage(id) {
+ if (!id) return;
+ await cdpRequest(`/json/close/${id}`, { timeout: HEALTH_TIMEOUT_MS }).catch(() => {});
+}
+
+/**
+ * Navigate to a URL in a fresh tab and verify — against Chrome's OWN reported
+ * connection IP — that every main-frame hop (initial request + each redirect)
+ * connected to an allowed address. This closes the DNS-rebinding TOCTOU that a
+ * pre-navigation `dns.lookup` cannot: we open a BLANK tab, subscribe to CDP
+ * Network events, THEN drive `Page.navigate`, so we capture the
+ * `remoteIPAddress` Chrome actually dialed for the document and every redirect.
+ *
+ * `verifyRemoteIp(ip)` returns false to refuse. On ANY refusal (or an
+ * unverifiable / empty IP, or a navigation that never yields a document
+ * response) we fail closed: close the tab and throw, so a rebind-to-private
+ * answer never reaches the caller's DOM reader.
+ *
+ * Returns a page object shaped like a `listCdpPages` entry
+ * (`{ id, url, title, webSocketDebuggerUrl }`) so callers can `evaluateOnPage` it.
+ */
+export async function navigateToUrlPinned(url, { verifyRemoteIp, navigateTimeoutMs = NAVIGATE_TIMEOUT_MS } = {}) {
+ if (typeof verifyRemoteIp !== 'function') {
+ throw new Error('navigateToUrlPinned requires a verifyRemoteIp(ip) predicate');
+ }
+
+ // Open a BLANK tab first so Network listeners attach BEFORE the target URL is
+ // fetched — `/json/new?<url>` would navigate immediately and we'd miss the
+ // document request (and its remoteIPAddress).
+ const response = await cdpRequest('/json/new?about:blank', { method: 'PUT', timeout: navigateTimeoutMs });
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ throw new Error(`CDP open-blank failed (${response.status}): ${text}`);
+ }
+ const target = await readResponseJson(response, { fallback: null, emptyValue: null });
+ if (!target?.id || !target?.webSocketDebuggerUrl) {
+ throw new Error(`CDP open-blank returned a malformed response for ${url}`);
+ }
+
+ const { default: WebSocket } = await import('ws');
+ const messages = [];
+ const result = await new Promise((resolve) => {
+ const ws = new WebSocket(target.webSocketDebuggerUrl);
+ let settled = false;
+ let timer;
+ const finish = (value) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ try { ws.close(); } catch {}
+ resolve(value);
+ };
+ timer = setTimeout(
+ () => finish({ ok: false, reason: 'navigation timed out before the document response' }),
+ navigateTimeoutMs,
+ );
+
+ ws.on('open', () => {
+ ws.send(JSON.stringify({ id: 1, method: 'Network.enable' }));
+ ws.send(JSON.stringify({ id: 2, method: 'Page.navigate', params: { url } }));
+ });
+ ws.on('message', (data) => {
+ const msg = safeJSONParse(data.toString(), null, { context: 'cdp-pin' });
+ if (!msg) return;
+ // A Page.navigate Chrome rejects outright (bad scheme, etc.) returns an
+ // error on id 2 — fail closed rather than hang to the timeout.
+ if (msg.id === 2 && msg.error) return finish({ ok: false, reason: msg.error.message || 'navigate rejected' });
+ if (!msg.method) return;
+ messages.push(msg);
+ // Terminal signal: the main-frame document RESPONSE headers arrived (all
+ // redirect hops precede it as redirectResponses). We have every hop's IP.
+ if (msg.method === 'Network.responseReceived') {
+ const { mainRequestId } = pickMainFrameHops(messages);
+ if (mainRequestId !== null && msg.params?.requestId === mainRequestId) finish({ ok: true });
+ }
+ });
+ ws.on('error', () => finish({ ok: false, reason: 'CDP websocket error during navigation' }));
+ });
+
+ const { hops, finalUrl } = pickMainFrameHops(messages);
+
+ const fail = async (reason) => {
+ await closeCdpPage(target.id);
+ throw new Error(reason);
+ };
+
+ if (!result.ok) await fail(`refusing to ingest: ${result.reason}`);
+ if (!hops.length) await fail('refusing to ingest: no main-frame document response was observed');
+ for (const hop of hops) {
+ if (!hop.remoteIPAddress || !verifyRemoteIp(hop.remoteIPAddress)) {
+ await fail(`refusing to ingest: Chrome connected to a disallowed address ${hop.remoteIPAddress || '(unknown)'} for ${hop.url || url}`);
+ }
+ }
+
+ return { id: target.id, url: finalUrl || url, title: '', webSocketDebuggerUrl: target.webSocketDebuggerUrl };
+}
+
// ---------- CDP page listing (UI-shaped subset) ----------
export async function getOpenPages() {
diff --git a/server/services/browserService.test.js b/server/services/browserService.test.js
index 56bd987e6f..e650811071 100644
--- a/server/services/browserService.test.js
+++ b/server/services/browserService.test.js
@@ -55,3 +55,63 @@ describe('browserService config persistence', () => {
expect(reloaded.headless).toBe(false);
});
});
+
+describe('pickMainFrameHops (SSRF pin — main-frame connection IPs)', () => {
+ // Pure helper: no data-root proxy needed, import the real module directly.
+ let pickMainFrameHops;
+ beforeEach(async () => {
+ vi.resetModules();
+ ({ pickMainFrameHops } = await import('./browserService.js'));
+ });
+
+ // A main-document navigation: requestId === loaderId marks the top frame.
+ const docRequest = (requestId, url, remoteIPAddress, redirectResponse) => ({
+ method: 'Network.requestWillBeSent',
+ params: { requestId, loaderId: requestId, type: 'Document', request: { url }, ...(redirectResponse ? { redirectResponse } : {}) },
+ });
+ const docResponse = (requestId, url, remoteIPAddress) => ({
+ method: 'Network.responseReceived',
+ params: { requestId, type: 'Document', response: { url, remoteIPAddress, status: 200 } },
+ });
+
+ it('captures the single-hop main document response IP', () => {
+ const { hops, finalUrl, mainRequestId } = pickMainFrameHops([
+ docRequest('R1', 'https://ex.com/a', ''),
+ docResponse('R1', 'https://ex.com/a', '93.184.216.34'),
+ ]);
+ expect(mainRequestId).toBe('R1');
+ expect(finalUrl).toBe('https://ex.com/a');
+ expect(hops).toEqual([{ url: 'https://ex.com/a', remoteIPAddress: '93.184.216.34', status: 200 }]);
+ });
+
+ it('captures EVERY redirect hop IP plus the final response (per-hop pin)', () => {
+ const { hops } = pickMainFrameHops([
+ docRequest('R1', 'https://ex.com/a', ''),
+ // redirect: the response that caused the redirect rides on the NEXT request
+ docRequest('R1', 'http://127.0.0.1:5555/secret', '', { url: 'https://ex.com/a', remoteIPAddress: '93.184.216.34', status: 302 }),
+ docResponse('R1', 'http://127.0.0.1:5555/secret', '127.0.0.1'),
+ ]);
+ expect(hops.map((h) => h.remoteIPAddress)).toEqual(['93.184.216.34', '127.0.0.1']);
+ });
+
+ it('ignores sub-resource requests (requestId !== loaderId)', () => {
+ const { hops, mainRequestId } = pickMainFrameHops([
+ docRequest('R1', 'https://ex.com/a', ''),
+ // A sub-resource: different requestId/loaderId, type Image — must be excluded.
+ { method: 'Network.requestWillBeSent', params: { requestId: 'R2', loaderId: 'R1', type: 'Image', request: { url: 'http://169.254.169.254/latest' } } },
+ { method: 'Network.responseReceived', params: { requestId: 'R2', type: 'Image', response: { url: 'http://169.254.169.254/latest', remoteIPAddress: '169.254.169.254', status: 200 } } },
+ docResponse('R1', 'https://ex.com/a', '93.184.216.34'),
+ ]);
+ expect(mainRequestId).toBe('R1');
+ expect(hops.map((h) => h.remoteIPAddress)).toEqual(['93.184.216.34']);
+ });
+
+ it('returns no hops when no main-frame document load is present', () => {
+ const { hops, mainRequestId, finalUrl } = pickMainFrameHops([
+ { method: 'Network.requestWillBeSent', params: { requestId: 'R2', loaderId: 'R1', type: 'Image', request: { url: 'https://cdn/x.png' } } },
+ ]);
+ expect(mainRequestId).toBeNull();
+ expect(hops).toEqual([]);
+ expect(finalUrl).toBeNull();
+ });
+});
diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.js
index 9fe0b60f7e..b0c6223821 100644
--- a/server/services/catalogIngestSources.js
+++ b/server/services/catalogIngestSources.js
@@ -31,8 +31,7 @@ import * as brainStorage from './brainStorage.js';
import { extractIngredientsForScrap } from './catalogExtraction.js';
import { transcribe } from './voice/stt.js';
import {
- navigateToUrl,
- listCdpPages,
+ navigateToUrlPinned,
evaluateOnPage,
} from './browserService.js';
import { lookup } from 'dns/promises';
@@ -98,32 +97,36 @@ async function assertIngestUrlSafe(target) {
* resolve correctly — a bare `fetch()` would only see the server-rendered
* HTML shell of an SPA.
*
+ * SSRF pin: Chrome re-resolves DNS independently of our pre-check, so a rebinding
+ * DNS answer could steer Chrome's connection to a blocked address after
+ * `assertIngestUrlSafe` vetted the hostname (a TOCTOU). `navigateToUrlPinned`
+ * closes that window by verifying, against Chrome's OWN reported
+ * `remoteIPAddress`, that every main-frame hop (initial + each redirect)
+ * connected to an allowed address — refusing (and tearing the tab down) before
+ * the DOM is read otherwise. The `isBlockedIngestHost` blocklist is the SAME
+ * criterion `assertIngestUrlSafe` vets with, so the pin and the pre-check agree.
+ *
* Returns `{ text, title, finalUrl }`. Throws when the browser can't reach
* the page or extracts nothing usable, so the route surfaces a clean 4xx/5xx.
*/
export async function fetchUrlMainText(url, { settleMs = PAGE_SETTLE_MS } = {}) {
await assertIngestUrlSafe(url);
- // `navigateToUrl` opens a fresh tab at the exact URL and returns it; we drive
- // and read that tab below. (Don't call findOrOpenPage first — it would open a
- // SECOND, orphaned tab per ingest, since navigateToUrl never reuses one.)
- const opened = await navigateToUrl(url);
+ // Navigate in a fresh tab and PIN: verify Chrome's actual per-hop connection
+ // IP is not a blocked (loopback / link-local / metadata) address — closing the
+ // rebinding gap between our dns.lookup above and Chrome's own resolution. Fails
+ // closed (tab torn down, throws) if any hop dialed a disallowed address.
+ const page = await navigateToUrlPinned(url, {
+ verifyRemoteIp: (ip) => !isBlockedIngestHost(ip),
+ });
await sleep(settleMs);
- // Re-list to get the live webSocketDebuggerUrl for the tab we just drove.
- // Match strictly by the id (then the exact url) navigateToUrl returned —
- // never fall back to an arbitrary `pages[0]`, which could be an unrelated
- // open tab and would ingest the wrong (possibly sensitive) page.
- const pages = await listCdpPages();
- const page = pages.find((p) => p.id === opened.id)
- || pages.find((p) => p.url === opened.url);
- if (!page) throw new Error('could not match the navigated tab after navigation (refusing to read an arbitrary tab)');
-
- // Re-run the FULL gate (scheme + DNS) against the FINAL url before reading the
- // DOM: a server-controlled redirect could have sent Chrome to a blocked
- // target, or to a hostname that itself resolves to one. The first-hop gate
- // doesn't cover the landed page.
- const landedUrl = page.url || opened.url || url;
+ // Defense in depth: re-run the scheme+DNS gate against the FINAL landed url.
+ // The remoteIP pin above already proved Chrome dialed an allowed address for
+ // every hop; this additionally rejects a landed hostname that is itself a
+ // blocked literal (e.g. an in-page/JS redirect after load that the network-hop
+ // pin didn't cover).
+ const landedUrl = page.url || url;
await assertIngestUrlSafe(landedUrl);
// Prefer the page's own <article>/<main> if present (skips nav/footer
diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.js
index 46ea9dd84a..2bdc0c612c 100644
--- a/server/services/catalogIngestSources.test.js
+++ b/server/services/catalogIngestSources.test.js
@@ -32,8 +32,7 @@ vi.mock('./voice/stt.js', () => ({
transcribe: vi.fn(),
}));
vi.mock('./browserService.js', () => ({
- navigateToUrl: vi.fn(),
- listCdpPages: vi.fn(),
+ navigateToUrlPinned: vi.fn(),
evaluateOnPage: vi.fn(),
}));
vi.mock('fs/promises', () => ({
@@ -78,24 +77,42 @@ beforeEach(() => {
catalogDB.createChunkedScrap.mockImplementation(async (args) => ({ id: 'cat-scrap-1', ...args }));
// Hostnames resolve to a safe public address by default (the DNS SSRF guard).
dnsp.lookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
+ // Default: Chrome dials a single public IP for the document (no rebind).
+ browserService.navigateToUrlPinned.mockImplementation(pinnedNav({ finalUrl: 'https://ex.com/a', hops: ['93.184.216.34'] }));
});
+/**
+ * Faithfully mimic the real `navigateToUrlPinned` fail-closed contract: it
+ * verifies each main-frame hop's ACTUAL Chrome-reported connection IP via the
+ * caller's `verifyRemoteIp` predicate and throws (tearing the tab down) if any
+ * hop is refused. `hops` are the IPs Chrome actually dialed — a rebinding DNS
+ * answer surfaces here as a private IP the pre-nav dns.lookup never saw.
+ */
+function pinnedNav({ finalUrl, hops }) {
+ return async (url, { verifyRemoteIp } = {}) => {
+ for (const ip of hops) {
+ if (!verifyRemoteIp(ip)) {
+ throw new Error(`refusing to ingest: Chrome connected to a disallowed address ${ip} for ${url}`);
+ }
+ }
+ return { id: 'p1', url: finalUrl || url, title: '', webSocketDebuggerUrl: 'ws://x' };
+ };
+}
+
describe('fetchUrlMainText', () => {
it('navigates + reads main text, returning title + text + finalUrl', async () => {
- browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
- browserService.listCdpPages.mockResolvedValue([
- { id: 'p1', url: 'https://ex.com/a', title: 'A', webSocketDebuggerUrl: 'ws://x' },
- ]);
browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: 'Article A', text: 'Body text here.' }));
const out = await fetchUrlMainText('https://ex.com/a', { settleMs: 0 });
expect(out).toEqual({ text: 'Body text here.', title: 'Article A', finalUrl: 'https://ex.com/a' });
- expect(browserService.navigateToUrl).toHaveBeenCalledWith('https://ex.com/a');
+ // Navigated through the PINNED path with a remote-IP verifier predicate.
+ expect(browserService.navigateToUrlPinned).toHaveBeenCalledWith(
+ 'https://ex.com/a',
+ expect.objectContaining({ verifyRemoteIp: expect.any(Function) }),
+ );
});
it('throws when the page extracts no readable text', async () => {
- browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
- browserService.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'https://ex.com/a', title: '', webSocketDebuggerUrl: 'ws://x' }]);
browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: '', text: ' ' }));
await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/no readable text/);
@@ -106,32 +123,40 @@ describe('fetchUrlMainText', () => {
// Schema passes (it's a normal hostname), but DNS points it at cloud metadata.
dnsp.lookup.mockResolvedValue({ address: '169.254.169.254', family: 4 });
await expect(fetchUrlMainText('https://evil.example/x', { settleMs: 0 })).rejects.toThrow(/resolves to a blocked/);
- expect(browserService.navigateToUrl).not.toHaveBeenCalled();
+ expect(browserService.navigateToUrlPinned).not.toHaveBeenCalled();
+ });
+
+ it('refuses when Chrome connects to a private IP AFTER DNS validation passed (rebinding TOCTOU)', async () => {
+ // Pre-nav dns.lookup answers a public IP so assertIngestUrlSafe passes — but
+ // Chrome re-resolves and actually dials cloud metadata. The remote-IP pin
+ // must catch Chrome's real connection and refuse before any DOM read.
+ dnsp.lookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
+ browserService.navigateToUrlPinned.mockImplementation(pinnedNav({ finalUrl: 'https://evil.example/x', hops: ['169.254.169.254'] }));
+ await expect(fetchUrlMainText('https://evil.example/x', { settleMs: 0 })).rejects.toThrow(/disallowed address 169\.254\.169\.254/);
+ expect(browserService.evaluateOnPage).not.toHaveBeenCalled();
});
- it('refuses to ingest a redirect that lands on a blocked (loopback) host', async () => {
- browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
- // The first-hop URL passed the schema guard, but Chrome followed a redirect
- // to a loopback target — the landed page.url is what we must re-check.
- browserService.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'http://127.0.0.1:5555/secret', title: 'x', webSocketDebuggerUrl: 'ws://x' }]);
- await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/loopback|link-local/);
+ it('refuses when a REDIRECT hop connects to a loopback address (per-hop pin)', async () => {
+ // First hop dials a public IP, but the redirect Chrome followed landed on a
+ // loopback address — the pin verifies EVERY main-frame hop, not just the last.
+ browserService.navigateToUrlPinned.mockImplementation(pinnedNav({ finalUrl: 'http://127.0.0.1:5555/secret', hops: ['93.184.216.34', '127.0.0.1'] }));
+ await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/disallowed address 127\.0\.0\.1/);
expect(browserService.evaluateOnPage).not.toHaveBeenCalled();
});
- it('refuses a redirect to a HOSTNAME that resolves to a blocked address (DNS re-check on landed url)', async () => {
- // First hop resolves safe; the landed redirect host resolves to metadata.
+ it('refuses a landed HOSTNAME that resolves to a blocked address (defense-in-depth re-check)', async () => {
+ // All network hops dialed public IPs (pin passes), but the FINAL landed url
+ // is a hostname that itself resolves to metadata — the landed-url re-vet
+ // still catches an in-page/JS redirect the network-hop pin didn't cover.
dnsp.lookup
.mockResolvedValueOnce({ address: '93.184.216.34', family: 4 })
.mockResolvedValueOnce({ address: '169.254.169.254', family: 4 });
- browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
- browserService.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'https://evil.example/x', title: 'x', webSocketDebuggerUrl: 'ws://x' }]);
+ browserService.navigateToUrlPinned.mockImplementation(pinnedNav({ finalUrl: 'https://evil.example/x', hops: ['93.184.216.34'] }));
await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/resolves to a blocked/);
expect(browserService.evaluateOnPage).not.toHaveBeenCalled();
});
it('clamps an oversized page body to the raw-text cap (2M chars)', async () => {
- browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
- browserService.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'https://ex.com/a', title: 'Big', webSocketDebuggerUrl: 'ws://x' }]);
const huge = 'x'.repeat(2_500_000);
browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: 'Big', text: huge }));
const out = await fetchUrlMainText('https://ex.com/a', { settleMs: 0 });
@@ -141,8 +166,6 @@ describe('fetchUrlMainText', () => {
describe('ingestFromUrl', () => {
it('creates a url scrap with url metadata and runs extraction', async () => {
- browserService.navigateToUrl.mockResolvedValue({ id: 'p1', url: 'https://ex.com/a' });
- browserService.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'https://ex.com/a', title: 'A', webSocketDebuggerUrl: 'ws://x' }]);
browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: 'Article A', text: 'Body.' }));
const { scrap, draft } = await ingestFromUrl({ url: 'https://ex.com/a', settleMs: 0 });