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: read the DOM on the same pinned CDP session, re-verified after the read (#2068)

Adam Eivy7033e1a950f1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a630ce7d8d..1053e2a6b3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,7 +3,7 @@
## 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).
-- **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).
+- **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 HTTP redirect, AND any client-side navigation that fires during the post-load settle window) connected to a non-blocked address, failing closed (tab torn down, ingest refused) on any disallowed hop or a top-level navigation still in flight. The DOM read runs on the SAME pinned CDP session and is re-verified after the read, so no late navigation can slip between "stop monitoring" and "read the page" (#2068).
## Workspace Contexts
diff --git a/server/services/browserService.js b/server/services/browserService.js
index 0552e7c6ea..f0f91257b2 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -352,30 +352,57 @@ async function closeCdpPage(id) {
await cdpRequest(`/json/close/${id}`, { timeout: HEALTH_TIMEOUT_MS }).catch(() => {});
}
+// Pure gate over a captured CDP message stream: returns a refusal reason string,
+// or null when every main-frame hop connected to an allowed address and no
+// top-level navigation is still in flight. Exported for unit testing.
+export function ssrfPinRefusalReason(messages, verifyRemoteIp, url) {
+ const { hops, pendingMainRequestIds } = pickMainFrameHops(messages);
+ if (!hops.length) return 'no main-frame document response was observed';
+ for (const hop of hops) {
+ if (!hop.remoteIPAddress || !verifyRemoteIp(hop.remoteIPAddress)) {
+ return `Chrome connected to a disallowed address ${hop.remoteIPAddress || '(unknown)'} for ${hop.url || url}`;
+ }
+ }
+ // A top-level navigation that STARTED but produced no response was never
+ // pinned — Chrome could be mid-connect to a private/metadata target.
+ if (pendingMainRequestIds.length) return 'a top-level navigation was still in flight (unpinned)';
+ return null;
+}
+
/**
* Navigate to a URL in a fresh tab and verify — against Chrome's OWN reported
* connection IP — that EVERY main-frame hop connected to an allowed address:
* the initial `Page.navigate`, every HTTP redirect, AND any client-side
* top-level navigation (meta-refresh / `location.replace`) that fires during the
- * post-load `settleMs` window before the DOM is read. This closes the
- * DNS-rebinding TOCTOU a pre-navigation `dns.lookup` cannot — Chrome resolves
- * DNS itself, so we open a BLANK tab, subscribe to CDP Network events, THEN
- * drive `Page.navigate`, keep the subscription open across the settle window,
- * and check the `remoteIPAddress` Chrome actually dialed for each hop.
+ * post-load `settleMs` window. This closes the DNS-rebinding TOCTOU a
+ * pre-navigation `dns.lookup` cannot — Chrome resolves DNS itself, so we open a
+ * BLANK tab, subscribe to CDP Network events, THEN drive `Page.navigate`, keep
+ * the subscription open across the settle window, and check the
+ * `remoteIPAddress` Chrome actually dialed for each hop.
*
- * `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.
+ * `verifyRemoteIp(ip)` returns false to refuse. On ANY refusal (unverifiable /
+ * empty IP, a navigation that never yields a document response, or a top-level
+ * nav still in flight) we fail closed: close the tab and throw, so a
+ * rebind-to-private answer never reaches the caller.
*
- * The caller does NOT sleep before reading — the settle wait happens HERE, so
- * the DOM has had `settleMs` to render (and every navigation in that window is
- * pinned) by the time this resolves.
+ * When `evaluateExpression` is given, the DOM read runs on the SAME CDP session
+ * (a `Runtime.evaluate` after settle), and the pin is RE-checked over events
+ * captured up to and during that read — so there is no gap between "stop
+ * monitoring" and "read the DOM" for a late client-side navigation to slip
+ * through. The evaluated value is returned as `evalResult` (or null). Without
+ * `evaluateExpression` the caller gets a page handle to read separately.
*
- * Returns a page object shaped like a `listCdpPages` entry
- * (`{ id, url, title, webSocketDebuggerUrl }`) so callers can `evaluateOnPage` it.
+ * The caller does NOT sleep — the settle wait happens HERE, so the DOM has had
+ * `settleMs` to render (and every navigation in that window is pinned) by the
+ * time this resolves. Returns `{ id, url, title, webSocketDebuggerUrl, evalResult }`.
*/
-export async function navigateToUrlPinned(url, { verifyRemoteIp, settleMs = 0, navigateTimeoutMs = NAVIGATE_TIMEOUT_MS } = {}) {
+export async function navigateToUrlPinned(url, {
+ verifyRemoteIp,
+ settleMs = 0,
+ navigateTimeoutMs = NAVIGATE_TIMEOUT_MS,
+ evaluateExpression = null,
+ evaluateTimeoutMs = CDP_EVALUATE_TIMEOUT_MS,
+} = {}) {
if (typeof verifyRemoteIp !== 'function') {
throw new Error('navigateToUrlPinned requires a verifyRemoteIp(ip) predicate');
}
@@ -393,18 +420,22 @@ export async function navigateToUrlPinned(url, { verifyRemoteIp, settleMs = 0, n
throw new Error(`CDP open-blank returned a malformed response for ${url}`);
}
+ const READ_ID = 3;
const { default: WebSocket } = await import('ws');
const messages = [];
const result = await new Promise((resolve) => {
const ws = new WebSocket(target.webSocketDebuggerUrl);
let settled = false;
+ let phase = 'nav';
let overallTimer;
let settleTimer = null;
+ let evalTimer = null;
const finish = (value) => {
if (settled) return;
settled = true;
clearTimeout(overallTimer);
clearTimeout(settleTimer);
+ clearTimeout(evalTimer);
try { ws.close(); } catch {}
resolve(value);
};
@@ -414,6 +445,24 @@ export async function navigateToUrlPinned(url, { verifyRemoteIp, settleMs = 0, n
navigateTimeoutMs,
);
+ // Settle expired: verify everything captured so far, then either read the DOM
+ // on THIS same session (so no monitoring gap) or resolve for a separate read.
+ const onSettleEnd = () => {
+ const bad = ssrfPinRefusalReason(messages, verifyRemoteIp, url);
+ if (bad) return finish({ ok: false, reason: bad });
+ if (!evaluateExpression) {
+ const { finalUrl } = pickMainFrameHops(messages);
+ return finish({ ok: true, finalUrl, evalResult: null });
+ }
+ phase = 'read';
+ evalTimer = setTimeout(() => finish({ ok: false, reason: 'DOM read timed out' }), evaluateTimeoutMs);
+ ws.send(JSON.stringify({
+ id: READ_ID,
+ method: 'Runtime.evaluate',
+ params: { expression: evaluateExpression, returnByValue: true, awaitPromise: true },
+ }));
+ };
+
ws.on('open', () => {
ws.send(JSON.stringify({ id: 1, method: 'Network.enable' }));
ws.send(JSON.stringify({ id: 2, method: 'Page.navigate', params: { url } }));
@@ -421,45 +470,43 @@ export async function navigateToUrlPinned(url, { verifyRemoteIp, settleMs = 0, n
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.
+ // A Page.navigate Chrome rejects outright (bad scheme, etc.) errors on id 2.
if (msg.id === 2 && msg.error) return finish({ ok: false, reason: msg.error.message || 'navigate rejected' });
+ if (msg.id === READ_ID) {
+ // DOM read returned. RE-verify over ALL events captured up to now: any
+ // top-level navigation that committed during the read is in `messages`,
+ // so a late rebind that changed the page under us fails closed here.
+ const bad = ssrfPinRefusalReason(messages, verifyRemoteIp, url);
+ if (bad) return finish({ ok: false, reason: bad });
+ const evalResult = (msg.error || msg.result?.exceptionDetails) ? null : (msg.result?.result?.value ?? null);
+ const { finalUrl } = pickMainFrameHops(messages);
+ return finish({ ok: true, finalUrl, evalResult });
+ }
if (!msg.method) return;
messages.push(msg);
- // The main document RESPONSE headers arriving (type 'Document', which the
- // main frame's doc emits before any sub-frame doc) starts the settle
- // window: keep capturing for settleMs so a client-side navigation during
- // settle is also pinned, THEN resolve. All hops are verified below.
- if (msg.method === 'Network.responseReceived' && msg.params?.type === 'Document' && !settleTimer) {
+ // First main-frame document RESPONSE (type 'Document', emitted before any
+ // sub-frame doc) starts the settle window; keep capturing across it so a
+ // client-side navigation during settle is pinned too.
+ if (phase === 'nav' && msg.method === 'Network.responseReceived' && msg.params?.type === 'Document' && !settleTimer) {
clearTimeout(overallTimer);
- settleTimer = setTimeout(() => finish({ ok: true }), settleMs);
+ settleTimer = setTimeout(onSettleEnd, settleMs);
}
});
ws.on('error', () => finish({ ok: false, reason: 'CDP websocket error during navigation' }));
});
- const { hops, finalUrl, pendingMainRequestIds } = pickMainFrameHops(messages);
-
- const fail = async (reason) => {
+ if (!result.ok) {
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}`);
- }
- }
- // Fail closed if a top-level navigation was still in flight when the settle
- // window ended: its final connection IP was never observed, so Chrome could be
- // mid-connect to a private/metadata target the DOM reader would then see.
- if (pendingMainRequestIds.length) {
- await fail('refusing to ingest: a top-level navigation was still in flight at read time (unpinned)');
+ throw new Error(`refusing to ingest: ${result.reason}`);
}
- return { id: target.id, url: finalUrl || url, title: '', webSocketDebuggerUrl: target.webSocketDebuggerUrl };
+ return {
+ id: target.id,
+ url: result.finalUrl || url,
+ title: '',
+ webSocketDebuggerUrl: target.webSocketDebuggerUrl,
+ evalResult: result.evalResult,
+ };
}
// ---------- CDP page listing (UI-shaped subset) ----------
diff --git a/server/services/browserService.test.js b/server/services/browserService.test.js
index 80b5d36a7a..1e8890b916 100644
--- a/server/services/browserService.test.js
+++ b/server/services/browserService.test.js
@@ -145,3 +145,58 @@ describe('pickMainFrameHops (SSRF pin — main-frame connection IPs)', () => {
expect(finalUrl).toBeNull();
});
});
+
+describe('ssrfPinRefusalReason (SSRF pin gate)', () => {
+ let ssrfPinRefusalReason;
+ beforeEach(async () => {
+ vi.resetModules();
+ ({ ssrfPinRefusalReason } = await import('./browserService.js'));
+ });
+
+ const allow = (ip) => !ip.startsWith('127.') && !ip.startsWith('169.254.');
+ const docRequest = (requestId, url, 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('passes (null) when every main-frame hop dialed an allowed IP', () => {
+ const reason = ssrfPinRefusalReason([
+ docRequest('R1', 'https://ex.com/a'),
+ docResponse('R1', 'https://ex.com/a', '93.184.216.34'),
+ ], allow, 'https://ex.com/a');
+ expect(reason).toBeNull();
+ });
+
+ it('refuses a hop that dialed a disallowed IP', () => {
+ const reason = ssrfPinRefusalReason([
+ docRequest('R1', 'http://127.0.0.1/x'),
+ docResponse('R1', 'http://127.0.0.1/x', '127.0.0.1'),
+ ], allow, 'http://127.0.0.1/x');
+ expect(reason).toMatch(/disallowed address 127\.0\.0\.1/);
+ });
+
+ it('refuses an in-flight top-level navigation (started, no response)', () => {
+ const reason = ssrfPinRefusalReason([
+ docRequest('R1', 'https://ex.com/a'),
+ docResponse('R1', 'https://ex.com/a', '93.184.216.34'),
+ docRequest('R2', 'https://evil.example/x'),
+ ], allow, 'https://ex.com/a');
+ expect(reason).toMatch(/still in flight/);
+ });
+
+ it('refuses when no main-frame document response was observed', () => {
+ expect(ssrfPinRefusalReason([], allow, 'https://ex.com/a')).toMatch(/no main-frame document response/);
+ });
+
+ it('refuses a hop with a missing/empty remote IP (unverifiable)', () => {
+ const reason = ssrfPinRefusalReason([
+ docRequest('R1', 'https://ex.com/a'),
+ docResponse('R1', 'https://ex.com/a', ''),
+ ], allow, 'https://ex.com/a');
+ expect(reason).toMatch(/disallowed address \(unknown\)/);
+ });
+});
diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.js
index 336fa07ae3..acc36d9c22 100644
--- a/server/services/catalogIngestSources.js
+++ b/server/services/catalogIngestSources.js
@@ -32,7 +32,6 @@ import { extractIngredientsForScrap } from './catalogExtraction.js';
import { transcribe } from './voice/stt.js';
import {
navigateToUrlPinned,
- evaluateOnPage,
} from './browserService.js';
import { lookup } from 'dns/promises';
import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
@@ -115,29 +114,31 @@ async function assertIngestUrlSafe(target) {
export async function fetchUrlMainText(url, { settleMs = PAGE_SETTLE_MS } = {}) {
await assertIngestUrlSafe(url);
+ // Prefer the page's own <article>/<main> if present (skips nav/footer chrome),
+ // falling back to document body text. Runs in the page; returns a plain string
+ // so returnByValue marshals it cleanly.
+ const expression = `(() => {
+ const pick = document.querySelector('article') || document.querySelector('main') || document.body;
+ const title = (document.title || '').trim();
+ const text = (pick && pick.innerText ? pick.innerText : '').trim();
+ return JSON.stringify({ title, text });
+ })()`;
+
// Navigate in a fresh tab and PIN: verify Chrome's actual per-hop connection
// IP is not a blocked (loopback / link-local / metadata) address for the
// initial nav, every redirect, and any client-side nav during the settle
// window — closing the rebinding gap between our dns.lookup above and Chrome's
- // own resolution. Fails closed (tab torn down, throws) on any disallowed hop.
- // The pin waits out settleMs internally, so the DOM is ready + fully pinned
- // by the time it returns and we read.
+ // own resolution. The DOM read runs on the SAME pinned CDP session (via
+ // evaluateExpression), re-verified after the read, so no late navigation slips
+ // between "stop monitoring" and "read". Fails closed (tab torn down, throws)
+ // on any disallowed hop.
const page = await navigateToUrlPinned(url, {
verifyRemoteIp: (ip) => !isBlockedIngestHost(ip),
settleMs,
+ evaluateExpression: expression,
});
- // Prefer the page's own <article>/<main> if present (skips nav/footer
- // chrome), falling back to document body text. Runs in the page; returns a
- // plain string so evaluateOnPage's returnByValue marshals it cleanly.
- const expression = `(() => {
- const pick = document.querySelector('article') || document.querySelector('main') || document.body;
- const title = (document.title || '').trim();
- const text = (pick && pick.innerText ? pick.innerText : '').trim();
- return JSON.stringify({ title, text });
- })()`;
- const raw = await evaluateOnPage(page, expression);
- const parsed = raw ? safeJSONParse(raw, null) : null;
+ const parsed = page.evalResult ? safeJSONParse(page.evalResult, null) : null;
const text = clampText(parsed?.text || '');
if (!text.trim()) throw new Error('no readable text extracted from page');
return { text, title: parsed?.title || page.title || '', finalUrl: page.url || url };
diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.js
index 9ee23adbd9..fe22625843 100644
--- a/server/services/catalogIngestSources.test.js
+++ b/server/services/catalogIngestSources.test.js
@@ -33,7 +33,6 @@ vi.mock('./voice/stt.js', () => ({
}));
vi.mock('./browserService.js', () => ({
navigateToUrlPinned: vi.fn(),
- evaluateOnPage: vi.fn(),
}));
vi.mock('fs/promises', () => ({
writeFile: vi.fn(),
@@ -77,8 +76,13 @@ 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'] }));
+ // Default: Chrome dials a single public IP for the document (no rebind), and
+ // the pinned DOM read returns a simple article.
+ browserService.navigateToUrlPinned.mockImplementation(pinnedNav({
+ finalUrl: 'https://ex.com/a',
+ hops: ['93.184.216.34'],
+ evalResult: JSON.stringify({ title: 'Article A', text: 'Body text here.' }),
+ }));
});
/**
@@ -88,35 +92,37 @@ beforeEach(() => {
* window) 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. The pin owns the settle wait, so it also ignores a `settleMs` option.
+ * saw. On success it returns the DOM-read result (`evalResult`) it performed on
+ * the SAME pinned session — the real function reads the DOM itself, so no
+ * separate read is mocked. It owns the settle wait, so it ignores `settleMs`.
*/
-function pinnedNav({ finalUrl, hops }) {
+function pinnedNav({ finalUrl, hops, evalResult = null }) {
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' };
+ return { id: 'p1', url: finalUrl || url, title: '', webSocketDebuggerUrl: 'ws://x', evalResult };
};
}
describe('fetchUrlMainText', () => {
it('navigates + reads main text, returning title + text + finalUrl', async () => {
- 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' });
- // Navigated through the PINNED path with a remote-IP verifier predicate.
+ // Navigated through the PINNED path with a remote-IP verifier predicate AND
+ // the DOM-read expression (the read happens on the same pinned session).
expect(browserService.navigateToUrlPinned).toHaveBeenCalledWith(
'https://ex.com/a',
- expect.objectContaining({ verifyRemoteIp: expect.any(Function) }),
+ expect.objectContaining({ verifyRemoteIp: expect.any(Function), evaluateExpression: expect.any(String) }),
);
});
it('throws when the page extracts no readable text', async () => {
- browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: '', text: ' ' }));
-
+ browserService.navigateToUrlPinned.mockImplementation(pinnedNav({
+ finalUrl: 'https://ex.com/a', hops: ['93.184.216.34'], evalResult: JSON.stringify({ title: '', text: ' ' }),
+ }));
await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/no readable text/);
expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();
});
@@ -131,11 +137,11 @@ describe('fetchUrlMainText', () => {
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.
+ // catches Chrome's real connection and refuses (throws) before any text is 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();
+ expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();
});
it('refuses when a REDIRECT hop connects to a loopback address (per-hop pin)', async () => {
@@ -143,7 +149,6 @@ describe('fetchUrlMainText', () => {
// 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 CLIENT-SIDE navigation during the settle window that dials metadata', async () => {
@@ -153,12 +158,13 @@ describe('fetchUrlMainText', () => {
// IP is verified too — no stale-DNS re-vet that a rebind could slip past.
browserService.navigateToUrlPinned.mockImplementation(pinnedNav({ finalUrl: 'https://evil.example/x', hops: ['93.184.216.34', '169.254.169.254'] }));
await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/disallowed address 169\.254\.169\.254/);
- expect(browserService.evaluateOnPage).not.toHaveBeenCalled();
});
it('clamps an oversized page body to the raw-text cap (2M chars)', async () => {
const huge = 'x'.repeat(2_500_000);
- browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: 'Big', text: huge }));
+ browserService.navigateToUrlPinned.mockImplementation(pinnedNav({
+ finalUrl: 'https://ex.com/a', hops: ['93.184.216.34'], evalResult: JSON.stringify({ title: 'Big', text: huge }),
+ }));
const out = await fetchUrlMainText('https://ex.com/a', { settleMs: 0 });
expect(out.text.length).toBe(2_000_000);
});
@@ -166,7 +172,9 @@ describe('fetchUrlMainText', () => {
describe('ingestFromUrl', () => {
it('creates a url scrap with url metadata and runs extraction', async () => {
- browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: 'Article A', text: 'Body.' }));
+ browserService.navigateToUrlPinned.mockImplementation(pinnedNav({
+ finalUrl: 'https://ex.com/a', hops: ['93.184.216.34'], evalResult: JSON.stringify({ title: 'Article A', text: 'Body.' }),
+ }));
const { scrap, draft } = await ingestFromUrl({ url: 'https://ex.com/a', settleMs: 0 });
expect(draft).toBe(DRAFT);