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: keep the SSRF pin active through the settle window, drop stale-DNS re-vet (#2068)

Adam Eivye9160e5b7dfa
diff --git a/server/services/browserService.js b/server/services/browserService.js
index 19195edd67..c63ff5ec23 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -282,36 +282,40 @@ export async function navigateToUrl(url) {
// ---------- 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`).
+ * Extract EVERY main-frame document network hop (each top-level navigation's
+ * 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
+ * CDP marks a 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).
+ * `Network.responseReceived` with the same requestId. A page can start MORE than
+ * one top-level navigation (a client-side `location.replace` / meta-refresh
+ * during the settle window is a fresh `requestId === loaderId`), so we track a
+ * SET of main requestIds — not just the first — and collect the hops of each.
+ * Walking these reconstructs every address Chrome dialed for the top document
+ * over the whole capture window — 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 }`.
+ * mainRequestIds: string[] }`.
*/
export function pickMainFrameHops(messages) {
- let mainRequestId = null;
+ const mainRequestIds = new Set();
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;
+ // A Document request whose requestId equals its loaderId is a top-level
+ // navigation; ignore sub-resource / sub-frame requests.
+ if (p.type === 'Document' && p.requestId && p.requestId === p.loaderId) {
+ mainRequestIds.add(p.requestId);
}
- if (p.requestId === mainRequestId && p.redirectResponse) {
+ if (mainRequestIds.has(p.requestId) && p.redirectResponse) {
hops.push({
url: p.redirectResponse.url || null,
remoteIPAddress: p.redirectResponse.remoteIPAddress || '',
@@ -319,7 +323,7 @@ export function pickMainFrameHops(messages) {
});
}
} else if (msg.method === 'Network.responseReceived') {
- if (mainRequestId !== null && p.requestId === mainRequestId && p.response) {
+ if (mainRequestIds.has(p.requestId) && p.response) {
hops.push({
url: p.response.url || null,
remoteIPAddress: p.response.remoteIPAddress || '',
@@ -329,7 +333,7 @@ export function pickMainFrameHops(messages) {
}
}
}
- return { hops, finalUrl, mainRequestId };
+ return { hops, finalUrl, mainRequestIds: [...mainRequestIds] };
}
// Close a CDP tab by target id (best-effort). Used to fail closed after an
@@ -342,21 +346,28 @@ async function closeCdpPage(id) {
/**
* 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.
+ * 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.
*
* `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.
*
+ * 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.
+ *
* 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 } = {}) {
+export async function navigateToUrlPinned(url, { verifyRemoteIp, settleMs = 0, navigateTimeoutMs = NAVIGATE_TIMEOUT_MS } = {}) {
if (typeof verifyRemoteIp !== 'function') {
throw new Error('navigateToUrlPinned requires a verifyRemoteIp(ip) predicate');
}
@@ -379,15 +390,18 @@ export async function navigateToUrlPinned(url, { verifyRemoteIp, navigateTimeout
const result = await new Promise((resolve) => {
const ws = new WebSocket(target.webSocketDebuggerUrl);
let settled = false;
- let timer;
+ let overallTimer;
+ let settleTimer = null;
const finish = (value) => {
if (settled) return;
settled = true;
- clearTimeout(timer);
+ clearTimeout(overallTimer);
+ clearTimeout(settleTimer);
try { ws.close(); } catch {}
resolve(value);
};
- timer = setTimeout(
+ // Overall cap: fail closed if the FIRST document response never arrives.
+ overallTimer = setTimeout(
() => finish({ ok: false, reason: 'navigation timed out before the document response' }),
navigateTimeoutMs,
);
@@ -404,11 +418,13 @@ export async function navigateToUrlPinned(url, { verifyRemoteIp, navigateTimeout
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 });
+ // 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) {
+ clearTimeout(overallTimer);
+ settleTimer = setTimeout(() => finish({ ok: true }), settleMs);
}
});
ws.on('error', () => finish({ ok: false, reason: 'CDP websocket error during navigation' }));
diff --git a/server/services/browserService.test.js b/server/services/browserService.test.js
index e650811071..6d50aca3e1 100644
--- a/server/services/browserService.test.js
+++ b/server/services/browserService.test.js
@@ -75,11 +75,11 @@ describe('pickMainFrameHops (SSRF pin — main-frame connection IPs)', () => {
});
it('captures the single-hop main document response IP', () => {
- const { hops, finalUrl, mainRequestId } = pickMainFrameHops([
+ const { hops, finalUrl, mainRequestIds } = pickMainFrameHops([
docRequest('R1', 'https://ex.com/a', ''),
docResponse('R1', 'https://ex.com/a', '93.184.216.34'),
]);
- expect(mainRequestId).toBe('R1');
+ expect(mainRequestIds).toEqual(['R1']);
expect(finalUrl).toBe('https://ex.com/a');
expect(hops).toEqual([{ url: 'https://ex.com/a', remoteIPAddress: '93.184.216.34', status: 200 }]);
});
@@ -94,23 +94,38 @@ describe('pickMainFrameHops (SSRF pin — main-frame connection IPs)', () => {
expect(hops.map((h) => h.remoteIPAddress)).toEqual(['93.184.216.34', '127.0.0.1']);
});
+ it('captures a SECOND top-level navigation (client-side nav during settle)', () => {
+ // A page that loads clean (R1 → public), then location.replace()s to a new
+ // top-level document (R2, a fresh requestId===loaderId) Chrome dials at
+ // metadata during the settle window. Both main-frame loads must be captured.
+ const { hops, finalUrl, mainRequestIds } = pickMainFrameHops([
+ docRequest('R1', 'https://ex.com/a', ''),
+ docResponse('R1', 'https://ex.com/a', '93.184.216.34'),
+ docRequest('R2', 'https://evil.example/x', ''),
+ docResponse('R2', 'https://evil.example/x', '169.254.169.254'),
+ ]);
+ expect(mainRequestIds).toEqual(['R1', 'R2']);
+ expect(hops.map((h) => h.remoteIPAddress)).toEqual(['93.184.216.34', '169.254.169.254']);
+ expect(finalUrl).toBe('https://evil.example/x');
+ });
+
it('ignores sub-resource requests (requestId !== loaderId)', () => {
- const { hops, mainRequestId } = pickMainFrameHops([
+ const { hops, mainRequestIds } = 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(mainRequestIds).toEqual(['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([
+ const { hops, mainRequestIds, finalUrl } = pickMainFrameHops([
{ method: 'Network.requestWillBeSent', params: { requestId: 'R2', loaderId: 'R1', type: 'Image', request: { url: 'https://cdn/x.png' } } },
]);
- expect(mainRequestId).toBeNull();
+ expect(mainRequestIds).toEqual([]);
expect(hops).toEqual([]);
expect(finalUrl).toBeNull();
});
diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.js
index 234158f1fd..336fa07ae3 100644
--- a/server/services/catalogIngestSources.js
+++ b/server/services/catalogIngestSources.js
@@ -32,11 +32,10 @@ import { extractIngredientsForScrap } from './catalogExtraction.js';
import { transcribe } from './voice/stt.js';
import {
navigateToUrlPinned,
- listCdpPages,
evaluateOnPage,
} from './browserService.js';
import { lookup } from 'dns/promises';
-import { PATHS, ensureDir, sleep, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
import { isSafeIngestUrl, isBlockedIngestHost } from '../lib/catalogValidation.js';
// Cap fetched/transcribed bodies at the scrap column boundary (the Zod
@@ -102,10 +101,13 @@ async function assertIngestUrlSafe(target) {
* 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.
+ * `remoteIPAddress`, that EVERY main-frame hop — the initial navigation, each
+ * HTTP redirect, AND any client-side navigation during the `settleMs` window
+ * before the DOM is read — connected to an allowed address, refusing (and
+ * tearing the tab down) otherwise. The `isBlockedIngestHost` blocklist is the
+ * SAME criterion `assertIngestUrlSafe` vets with, so the pin and the pre-check
+ * agree. The pin owns the settle wait, so there is no separate stale-DNS re-vet
+ * (which would itself be rebindable) after it returns.
*
* 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.
@@ -114,27 +116,16 @@ export async function fetchUrlMainText(url, { settleMs = PAGE_SETTLE_MS } = {})
await assertIngestUrlSafe(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.
+ // 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.
const page = await navigateToUrlPinned(url, {
verifyRemoteIp: (ip) => !isBlockedIngestHost(ip),
+ settleMs,
});
- await sleep(settleMs);
-
- // Defense in depth: re-query the tab's LIVE url AFTER the settle window and
- // re-vet it (scheme + DNS blocklist) before reading the DOM. The network-hop
- // pin above covers HTTP-level hops, but the page can client-side navigate
- // (meta refresh / location.replace) during the settle to a blocked host — so
- // read the CURRENT url from CDP, not the pre-settle url the pin captured, or
- // that redirect goes unchecked. Match strictly by the target id navigate
- // returned (never an arbitrary tab). Fall back to the pinned page's own
- // webSocketDebuggerUrl for the read if the re-list misses.
- const pages = await listCdpPages();
- const live = pages.find((p) => p.id === page.id);
- const landedUrl = live?.url || page.url || url;
- await assertIngestUrlSafe(landedUrl);
- const readTarget = live?.webSocketDebuggerUrl ? live : page;
// 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
@@ -145,11 +136,11 @@ export async function fetchUrlMainText(url, { settleMs = PAGE_SETTLE_MS } = {})
const text = (pick && pick.innerText ? pick.innerText : '').trim();
return JSON.stringify({ title, text });
})()`;
- const raw = await evaluateOnPage(readTarget, expression);
+ const raw = await evaluateOnPage(page, expression);
const parsed = raw ? safeJSONParse(raw, null) : null;
const text = clampText(parsed?.text || '');
if (!text.trim()) throw new Error('no readable text extracted from page');
- return { text, title: parsed?.title || live?.title || page.title || '', finalUrl: landedUrl };
+ 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 bfbcedaeea..9ee23adbd9 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(),
- listCdpPages: vi.fn(),
evaluateOnPage: vi.fn(),
}));
vi.mock('fs/promises', () => ({
@@ -80,16 +79,16 @@ beforeEach(() => {
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: the live tab (re-queried after settle) is the same safe url.
- browserService.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'https://ex.com/a', title: 'A', webSocketDebuggerUrl: 'ws://x' }]);
});
/**
* 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.
+ * verifies EVERY main-frame hop's ACTUAL Chrome-reported connection IP (the
+ * initial nav, each redirect, and any client-side navigation during the settle
+ * 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.
*/
function pinnedNav({ finalUrl, hops }) {
return async (url, { verifyRemoteIp } = {}) => {
@@ -147,24 +146,13 @@ describe('fetchUrlMainText', () => {
expect(browserService.evaluateOnPage).not.toHaveBeenCalled();
});
- 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 LIVE tab url after
- // settle 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.listCdpPages.mockResolvedValue([{ id: 'p1', url: 'https://evil.example/x', title: 'x', webSocketDebuggerUrl: 'ws://x' }]);
- await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/resolves to a blocked/);
- expect(browserService.evaluateOnPage).not.toHaveBeenCalled();
- });
-
- it('re-checks the LIVE tab url after the settle window (client-side nav to loopback)', async () => {
- // Pin passes (public hops), but the page client-side navigates (meta refresh /
- // location.replace) during the settle to a loopback address. We must re-read
- // the CURRENT tab url — not the pre-settle url the pin captured — and refuse.
- 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 a CLIENT-SIDE navigation during the settle window that dials metadata', async () => {
+ // Pin passes the initial public hop, but the page meta-refreshes /
+ // location.replaces during the settle window to a host Chrome dials at cloud
+ // metadata. Because the pin stays active through settle, that later hop's real
+ // 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();
});