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 feeds.js fetches against DNS-rebinding TOCTOU (#2046)

Adam Eivyced23040a2fb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2aa2f0d27a..82d4db8ad7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## 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.
+
## Workspace Contexts
- **Switch project workspaces from ⌘K and voice, and CoS now auto-snapshots the workspace it leaves.** A new `workspace_switch` action ("switch workspace to BookLoom", "restore my PortOS context") saves a snapshot of the workspace you're leaving, then reconciles the target project's saved context — git branch, in-repo shell sessions, scoped tasks — and reports what's still live to re-attach; it appears in the ⌘K palette and resolves by voice. When CoS dispatches a coding agent against a different app/repo than it was last working in, it now silently snapshots the previous workspace's context first (snapshot-only — no auto-restore, no LLM calls), so switching between repos preserves what each project looked like, visible on the Workspace Contexts page (#2035).
diff --git a/server/lib/safeUrlFetch.js b/server/lib/safeUrlFetch.js
index 95bc58c336..c7e37bff6b 100644
--- a/server/lib/safeUrlFetch.js
+++ b/server/lib/safeUrlFetch.js
@@ -15,6 +15,12 @@
* private/LAN hosts (a single-user tool legitimately reaches Tailscale peers /
* home wikis). A redirect to a blocked target fails CLOSED (returns null) — the
* landed hop is revalidated exactly like the first.
+ *
+ * Strict posture (`blockPrivate: true`): additionally reject ALL private/LAN
+ * addresses (RFC1918, CGNAT-adjacent, IPv6 ULA fc00::/7, …) — both host literals
+ * and DNS-resolved addresses. RSS feeds use this so an arbitrary user-added feed
+ * URL can't be pointed at the home network, preserving feeds.js's historical
+ * block-all-private posture while gaining the connect-time IP pin.
*/
import dns from 'dns/promises';
@@ -26,6 +32,50 @@ import { isSafeIngestUrl, isBlockedIngestHost } from './catalogValidation.js';
const DEFAULT_TIMEOUT_MS = 15000;
const DEFAULT_MAX_BYTES = 12 * 1024 * 1024; // 12 MB — generous for a single image/feed
+/**
+ * Classify an IP literal as private/loopback/link-local (IPv4 or IPv6) for the
+ * strict `blockPrivate` posture. `isBlockedIngestHost` only covers
+ * loopback/link-local/metadata (the default posture ALLOWS LAN); this widens the
+ * net to the full RFC1918 / CGNAT-adjacent / IPv6-ULA ranges so a feed URL can't
+ * reach the home network. An unparseable / empty value fails closed (private).
+ */
+function isPrivateAddress(ip) {
+ if (!ip) return true;
+ const lower = ip.toLowerCase();
+ if (lower.includes(':')) {
+ if (lower === '::1' || lower === '::') return true;
+ // IPv4-mapped IPv6 — both ::ffff:a.b.c.d (raw dns.resolve form) and
+ // ::ffff:wxyz:wxyz (the hex form URL parsing normalizes to).
+ const mappedDotted = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
+ if (mappedDotted) return isPrivateAddress(mappedDotted[1]);
+ const mappedHex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
+ if (mappedHex) {
+ const high = parseInt(mappedHex[1], 16);
+ const low = parseInt(mappedHex[2], 16);
+ return isPrivateAddress(`${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`);
+ }
+ const firstGroup = lower.split(':')[0];
+ if (firstGroup) {
+ const firstWord = parseInt(firstGroup, 16);
+ if (Number.isFinite(firstWord)) {
+ if ((firstWord & 0xfe00) === 0xfc00) return true; // ULA fc00::/7
+ if ((firstWord & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
+ }
+ }
+ return false;
+ }
+ const parts = lower.split('.').map(Number);
+ if (parts.length === 4 && parts.every((p) => !isNaN(p) && p >= 0 && p <= 255)) {
+ if (parts[0] === 10) return true;
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
+ if (parts[0] === 192 && parts[1] === 168) return true;
+ if (parts[0] === 169 && parts[1] === 254) return true;
+ if (parts[0] === 127) return true;
+ if (parts[0] === 0) return true;
+ }
+ return false;
+}
+
/**
* Core SSRF resolve: scheme + blocked-host-literal (sync, via isSafeIngestUrl),
* AND a single DNS resolve so a hostname whose A record points at a blocked
@@ -43,25 +93,32 @@ const DEFAULT_MAX_BYTES = 12 * 1024 * 1024; // 12 MB — generous for a single i
*
* @returns {Promise<{ safe: boolean, address?: string|null, family?: number }>}
*/
-async function resolvePublicHttpUrl(target) {
+async function resolvePublicHttpUrl(target, { blockPrivate = false } = {}) {
if (!isSafeIngestUrl(target)) return { safe: false };
const { hostname } = new URL(target);
// Host literals were already classified by isSafeIngestUrl and need no pinning
// (net connects straight to the literal — there's no name to rebind).
const isIpLiteral = /^[\d.]+$/.test(hostname) || hostname.includes(':');
- if (isIpLiteral) return { safe: true, address: null };
+ if (isIpLiteral) {
+ // Strict posture must still reject a private LITERAL (e.g. http://192.168.1.5)
+ // that isSafeIngestUrl deliberately allows in the default LAN-friendly gate.
+ const literal = hostname.replace(/^\[|\]$/g, '');
+ if (blockPrivate && isPrivateAddress(literal)) return { safe: false };
+ return { safe: true, address: null };
+ }
const resolved = await dns.lookup(hostname).catch(() => null);
if (!resolved?.address) return { safe: false }; // can't vet → can't safely pin → fail closed
if (isBlockedIngestHost(resolved.address)) return { safe: false };
+ if (blockPrivate && isPrivateAddress(resolved.address)) return { safe: false };
return { safe: true, address: resolved.address, family: resolved.family };
}
/**
* Boolean SSRF gate. Returns false on any failure — never throws — so redirect
- * revalidation can fail closed.
+ * revalidation can fail closed. `blockPrivate` opts into the strict posture.
*/
-export async function isPublicHttpUrlSafe(target) {
- return (await resolvePublicHttpUrl(target)).safe;
+export async function isPublicHttpUrlSafe(target, { blockPrivate = false } = {}) {
+ return (await resolvePublicHttpUrl(target, { blockPrivate })).safe;
}
/**
@@ -108,24 +165,30 @@ function throwUnsafeUrl() {
* Throwing variant for the FIRST hop (the user-supplied / stored URL) so a bad
* target surfaces a clean 400 at the route instead of a silent null.
*/
-export async function assertPublicHttpUrl(target) {
- if (!await isPublicHttpUrlSafe(target)) throwUnsafeUrl();
+export async function assertPublicHttpUrl(target, { blockPrivate = false } = {}) {
+ if (!await isPublicHttpUrlSafe(target, { blockPrivate })) throwUnsafeUrl();
}
-// Fetch with the first-hop gate (throws) + manual redirect revalidation (fails
-// closed). Every hop is resolved AND pinned, so the connect can't re-resolve to
-// a blocked address after the check passes. Returns the Response, or null on a
-// network error / blocked redirect / missing Location. The caller decides what
-// to do with a non-ok status.
-async function fetchGuarded(url, { timeoutMs = DEFAULT_TIMEOUT_MS, headers } = {}) {
- const first = await resolvePublicHttpUrl(url);
- if (!first.safe) throwUnsafeUrl();
+// Fetch with the first-hop gate + manual redirect revalidation (fails closed).
+// Every hop is resolved AND pinned, so the connect can't re-resolve to a blocked
+// address after the check passes. Returns the Response, or null on a network
+// error / blocked redirect / missing Location. The caller decides what to do
+// with a non-ok status. First-hop unsafe THROWS a clean 400 by default (routes
+// want that); `throwOnUnsafe: false` makes it fail closed to null instead — for
+// callers (RSS feeds) whose own contract is a friendly "couldn't fetch" result
+// rather than a bubbled error.
+async function fetchGuarded(url, { timeoutMs = DEFAULT_TIMEOUT_MS, headers, blockPrivate = false, throwOnUnsafe = true } = {}) {
+ const first = await resolvePublicHttpUrl(url, { blockPrivate });
+ if (!first.safe) {
+ if (throwOnUnsafe) throwUnsafeUrl();
+ return null;
+ }
const res = await pinnedFetch(url, first, { redirect: 'manual', headers }, timeoutMs);
if (res && res.status >= 300 && res.status < 400) {
const location = res.headers.get('location');
if (!location) return null;
const redirectUrl = new URL(location, url).href;
- const hop = await resolvePublicHttpUrl(redirectUrl);
+ const hop = await resolvePublicHttpUrl(redirectUrl, { blockPrivate });
if (!hop.safe) return null;
return pinnedFetch(redirectUrl, hop, { redirect: 'error', headers }, timeoutMs);
}
@@ -134,10 +197,13 @@ async function fetchGuarded(url, { timeoutMs = DEFAULT_TIMEOUT_MS, headers } = {
/**
* Fetch a URL's body as text. Returns the string on a 2xx, or null on any
- * failure (network error, non-ok status, blocked redirect).
+ * failure (network error, non-ok status, blocked redirect). `blockPrivate` opts
+ * into the strict block-all-private posture and `throwOnUnsafe: false` returns
+ * null (instead of throwing a 400) when the first hop is unsafe — both used by
+ * RSS feed fetches.
*/
-export async function fetchPublicText(url, { timeoutMs, headers } = {}) {
- const res = await fetchGuarded(url, { timeoutMs, headers });
+export async function fetchPublicText(url, { timeoutMs, headers, blockPrivate = false, throwOnUnsafe = true } = {}) {
+ const res = await fetchGuarded(url, { timeoutMs, headers, blockPrivate, throwOnUnsafe });
if (!res?.ok) return null;
return res.text();
}
@@ -151,8 +217,8 @@ export async function fetchPublicText(url, { timeoutMs, headers } = {}) {
* post-read check fires. Falls back to a buffered read only when the response
* exposes no stream (e.g. a test double).
*/
-export async function fetchPublicBinary(url, { timeoutMs, headers, maxBytes = DEFAULT_MAX_BYTES } = {}) {
- const res = await fetchGuarded(url, { timeoutMs, headers });
+export async function fetchPublicBinary(url, { timeoutMs, headers, maxBytes = DEFAULT_MAX_BYTES, blockPrivate = false, throwOnUnsafe = true } = {}) {
+ const res = await fetchGuarded(url, { timeoutMs, headers, blockPrivate, throwOnUnsafe });
if (!res?.ok) return null;
const contentType = res.headers.get('content-type') || '';
const declared = Number(res.headers.get('content-length'));
diff --git a/server/lib/safeUrlFetch.test.js b/server/lib/safeUrlFetch.test.js
index ba93bb1451..8d85769bac 100644
--- a/server/lib/safeUrlFetch.test.js
+++ b/server/lib/safeUrlFetch.test.js
@@ -56,6 +56,47 @@ describe('isPublicHttpUrlSafe', () => {
});
});
+describe('isPublicHttpUrlSafe — strict blockPrivate posture', () => {
+ it('allows a private/LAN host by default but rejects it under blockPrivate', async () => {
+ lookupMock.mockResolvedValue({ address: '192.168.1.50', family: 4 });
+ expect(await isPublicHttpUrlSafe('https://nas.local/feed')).toBe(true);
+ expect(await isPublicHttpUrlSafe('https://nas.local/feed', { blockPrivate: true })).toBe(false);
+ });
+ it('rejects a private IPv4 LITERAL under blockPrivate (no resolve)', async () => {
+ expect(await isPublicHttpUrlSafe('http://192.168.1.5/x')).toBe(true); // LAN allowed by default
+ expect(await isPublicHttpUrlSafe('http://192.168.1.5/x', { blockPrivate: true })).toBe(false);
+ expect(await isPublicHttpUrlSafe('http://10.1.2.3/x', { blockPrivate: true })).toBe(false);
+ expect(lookupMock).not.toHaveBeenCalled();
+ });
+ it('rejects an IPv6 ULA literal under blockPrivate', async () => {
+ expect(await isPublicHttpUrlSafe('http://[fd12:3456:789a::1]/x', { blockPrivate: true })).toBe(false);
+ });
+ it('rejects a hostname that RESOLVES to a private address under blockPrivate', async () => {
+ lookupMock.mockResolvedValue({ address: '10.0.0.42', family: 4 });
+ expect(await isPublicHttpUrlSafe('https://home.example.com/x', { blockPrivate: true })).toBe(false);
+ });
+ it('still allows a genuinely public host under blockPrivate', async () => {
+ lookupMock.mockResolvedValue({ address: '93.184.216.34', family: 4 });
+ expect(await isPublicHttpUrlSafe('https://example.com/x', { blockPrivate: true })).toBe(true);
+ });
+});
+
+describe('fetchPublicText — strict blockPrivate + throwOnUnsafe:false (RSS feed path)', () => {
+ it('returns null (no fetch, no throw) for a host that resolves private', async () => {
+ lookupMock.mockResolvedValue({ address: '10.0.0.5', family: 4 });
+ fetchMock.mockResolvedValue(res({ text: 'secret' }));
+ // The feeds path opts out of the 400 throw so its caller can show a friendly
+ // "couldn't fetch" message; the request must still never leave the box.
+ expect(await fetchPublicText('https://home.example.com/feed', { blockPrivate: true, throwOnUnsafe: false })).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ it('still THROWS a 400 for an unsafe first hop by default (route contract)', async () => {
+ lookupMock.mockResolvedValue({ address: '10.0.0.5', family: 4 });
+ await expect(fetchPublicText('https://home.example.com/feed', { blockPrivate: true }))
+ .rejects.toMatchObject({ status: 400, code: 'UNSAFE_URL' });
+ });
+});
+
describe('assertPublicHttpUrl', () => {
it('throws a 400 UNSAFE_URL for a blocked target', async () => {
await expect(assertPublicHttpUrl('http://localhost/x')).rejects.toMatchObject({ status: 400, code: 'UNSAFE_URL' });
diff --git a/server/services/feeds.js b/server/services/feeds.js
index 1e0dad5343..4482898635 100644
--- a/server/services/feeds.js
+++ b/server/services/feeds.js
@@ -10,10 +10,8 @@
import { randomUUID } from 'crypto';
import { join } from 'path';
-import dns from 'dns/promises';
-import net from 'net';
import { PATHS, createCachedStore } from '../lib/fileUtils.js';
-import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { fetchPublicText } from '../lib/safeUrlFetch.js';
import { decodeXmlEntities } from '../lib/xmlEntities.js';
const FEEDS_FILE = join(PATHS.data, 'feeds.json');
@@ -387,110 +385,26 @@ export async function getFeedStats() {
// ─── Internal Helpers ───────────────────────────────────────────────────────
-// Check if an IP address is private/loopback/link-local (IPv4 or IPv6).
-function isPrivateIP(ip) {
- if (!ip) return true;
- const lower = ip.toLowerCase();
- // IPv6
- if (lower.includes(':')) {
- if (lower === '::1' || lower === '::') return true;
- // IPv4-mapped IPv6 — accept both ::ffff:a.b.c.d (raw form from dns.resolve)
- // and ::ffff:wxyz:wxyz (the hex form Node's URL parser normalizes to).
- const mappedDotted = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
- if (mappedDotted) return isPrivateIP(mappedDotted[1]);
- const mappedHex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
- if (mappedHex) {
- const high = parseInt(mappedHex[1], 16);
- const low = parseInt(mappedHex[2], 16);
- return isPrivateIP(`${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`);
- }
- const firstGroup = lower.split(':')[0];
- if (firstGroup) {
- const firstWord = parseInt(firstGroup, 16);
- if (Number.isFinite(firstWord)) {
- // ULA fc00::/7 (top 7 bits = 1111110)
- if ((firstWord & 0xfe00) === 0xfc00) return true;
- // Link-local fe80::/10 (top 10 bits = 1111111010)
- if ((firstWord & 0xffc0) === 0xfe80) return true;
- }
- }
- return false;
- }
- // IPv4
- const parts = lower.split('.').map(Number);
- if (parts.length === 4 && parts.every(p => !isNaN(p) && p >= 0 && p <= 255)) {
- if (parts[0] === 10) return true;
- if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
- if (parts[0] === 192 && parts[1] === 168) return true;
- if (parts[0] === 169 && parts[1] === 254) return true;
- if (parts[0] === 127) return true;
- if (parts[0] === 0) return true;
- }
- return false;
-}
-
-// DNS error codes that mean "this record type does not exist" — safe to treat
-// as an empty result. Anything else (SERVFAIL, TIMEOUT, CONNREFUSED, …) is a
-// resolver failure that can't prove the family is safe; we must fail closed
-// because Node's fetch performs its own lookup and may still happy-eyeballs to
-// a private address we never got to inspect.
-const BENIGN_DNS_MISS_CODES = new Set(['ENOTFOUND', 'ENODATA', 'NODATA', 'NOTFOUND']);
-
-// Resolve hostname and verify it doesn't point to a private IP. Resolves A
-// and AAAA in parallel so a hostname with a public A but a private AAAA
-// (happy-eyeballs would prefer the AAAA in Node's fetch) is rejected; the
-// parallel AAAA lookup also lets AAAA-only feeds resolve.
-async function isHostSafe(hostname) {
- // URL.hostname preserves the [::1] bracketed form for IPv6 literals; strip
- // brackets so net.isIP recognizes the address before falling through to DNS.
- const stripped = hostname.startsWith('[') && hostname.endsWith(']')
- ? hostname.slice(1, -1)
- : hostname;
- if (net.isIP(stripped)) return !isPrivateIP(stripped);
- const wrap = (p) => p.then(
- addrs => ({ ok: true, addrs }),
- err => BENIGN_DNS_MISS_CODES.has(err?.code) ? { ok: true, addrs: [] } : { ok: false, addrs: [] },
- );
- const [v4, v6] = await Promise.all([
- wrap(dns.resolve4(stripped)),
- wrap(dns.resolve6(stripped)),
- ]);
- if (!v4.ok || !v6.ok) return false;
- const addresses = [...v4.addrs, ...v6.addrs];
- if (addresses.length === 0) return false;
- return addresses.every(addr => !isPrivateIP(addr));
-}
+const FEED_HEADERS = {
+ 'User-Agent': 'PortOS Feed Reader/1.0',
+ Accept: 'application/rss+xml, application/atom+xml, application/xml, text/xml',
+};
+// Fetch a feed's XML through the shared SSRF-guarded fetch. `blockPrivate: true`
+// keeps feeds' historical block-all-private posture (an arbitrary user-added
+// feed URL must not be aimable at the home network) while gaining the
+// connect-time IP PIN that closes the DNS-rebinding TOCTOU (#2046): the
+// hostname is resolved once and undici connects to exactly that vetted address,
+// re-validated and re-pinned on every redirect hop. `throwOnUnsafe: false`
+// preserves this module's contract of returning null on any failure (so addFeed
+// surfaces the friendly "Could not fetch feed" message rather than a bubbled
+// 400) for an unsafe/private host, network error, non-ok status, or blocked
+// redirect.
async function fetchFeedXml(url) {
- // Restrict to http/https to prevent SSRF via file://, data://, etc.
- const parsed = new URL(url);
- if (!['http:', 'https:'].includes(parsed.protocol)) return null;
- // Resolve DNS and block private/loopback/link-local IPs (prevents rebinding attacks)
- if (!await isHostSafe(parsed.hostname)) return null;
-
- const feedHeaders = { 'User-Agent': 'PortOS Feed Reader/1.0', Accept: 'application/rss+xml, application/atom+xml, application/xml, text/xml' };
-
- const res = await fetchWithTimeout(url, {
- redirect: 'manual',
- headers: feedHeaders
- }, FETCH_TIMEOUT_MS).catch(() => null);
-
- // Handle redirects manually to validate each redirect target
- if (res?.status >= 300 && res?.status < 400) {
- const location = res.headers.get('location');
- if (!location) return null;
- const redirectUrl = new URL(location, url);
- if (!['http:', 'https:'].includes(redirectUrl.protocol)) return null;
- if (!await isHostSafe(redirectUrl.hostname)) return null;
- // Follow the validated redirect
- const res2 = await fetchWithTimeout(redirectUrl.href, {
- redirect: 'error',
- headers: feedHeaders
- }, FETCH_TIMEOUT_MS).catch(() => null);
- if (!res2?.ok) return null;
- return res2.text();
- }
-
- if (!res?.ok) return null;
- return res.text();
+ return fetchPublicText(url, {
+ timeoutMs: FETCH_TIMEOUT_MS,
+ headers: FEED_HEADERS,
+ blockPrivate: true,
+ throwOnUnsafe: false,
+ });
}
diff --git a/server/services/feeds.test.js b/server/services/feeds.test.js
index 6446f4a5f9..78edd6d545 100644
--- a/server/services/feeds.test.js
+++ b/server/services/feeds.test.js
@@ -11,20 +11,20 @@ vi.mock('../lib/fileUtils.js', async () => {
return makePathsProxy(actual, { dataRoot: () => tmpRoot });
});
+// feeds.js fetches through the shared SSRF-guarded helper (server/lib/safeUrlFetch.js),
+// which is exercised for real here — we only mock its two boundaries: the DNS
+// resolve (dns.lookup) and the timed fetch. safeUrlFetch resolves a hostname
+// once via dns.lookup and PINS the connection to that vetted address, so these
+// tests drive the same rebinding-pin path production uses.
const fetchMock = vi.fn();
vi.mock('../lib/fetchWithTimeout.js', () => ({
fetchWithTimeout: (...args) => fetchMock(...args),
}));
-const dnsResolveMock = vi.fn();
-const dnsResolve6Mock = vi.fn();
+const lookupMock = vi.fn();
vi.mock('dns/promises', () => ({
- default: {
- resolve4: (...args) => dnsResolveMock(...args),
- resolve6: (...args) => dnsResolve6Mock(...args),
- },
- resolve4: (...args) => dnsResolveMock(...args),
- resolve6: (...args) => dnsResolve6Mock(...args),
+ default: { lookup: (...args) => lookupMock(...args) },
+ lookup: (...args) => lookupMock(...args),
}));
let feeds;
@@ -42,8 +42,7 @@ beforeEach(async () => {
tmpRoot = mkdtempSync(join(tmpdir(), 'portos-feeds-test-'));
vi.resetModules();
fetchMock.mockReset();
- dnsResolveMock.mockReset().mockResolvedValue(['93.184.216.34']);
- dnsResolve6Mock.mockReset().mockResolvedValue([]);
+ lookupMock.mockReset().mockResolvedValue({ address: '93.184.216.34', family: 4 });
feeds = await import('./feeds.js');
});
@@ -168,7 +167,7 @@ describe('addFeed', () => {
])('rejects literal private IPv4 %s without DNS lookup', async (host) => {
const result = await feeds.addFeed(`http://${host}/feed`);
expect(result).toEqual({ error: FETCH_ERROR });
- expect(dnsResolveMock).not.toHaveBeenCalled();
+ expect(lookupMock).not.toHaveBeenCalled(); // literal is classified without resolving
expect(fetchMock).not.toHaveBeenCalled();
});
@@ -183,7 +182,7 @@ describe('addFeed', () => {
])('rejects literal private IPv6 %s without DNS lookup', async (_label, host) => {
const result = await feeds.addFeed(`http://${host}/feed`);
expect(result).toEqual({ error: FETCH_ERROR });
- expect(dnsResolveMock).not.toHaveBeenCalled();
+ expect(lookupMock).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
@@ -191,83 +190,51 @@ describe('addFeed', () => {
fetchMock.mockResolvedValue(makeResponse({ body: RSS_FIXTURE }));
const result = await feeds.addFeed('http://[2606:4700:4700::1111]/rss');
expect(result.error).toBeUndefined();
- expect(dnsResolveMock).not.toHaveBeenCalled();
+ expect(lookupMock).not.toHaveBeenCalled(); // literal needs no resolve/pin
expect(fetchMock).toHaveBeenCalledTimes(1);
- // Bracketed form must survive into the outbound fetch URL — stripping happened only inside isHostSafe
+ // Bracketed form must survive into the outbound fetch URL — bracket-stripping
+ // happens only inside the private-literal classifier.
expect(fetchMock.mock.calls[0][0]).toContain('[2606:4700:4700::1111]');
});
it('rejects hostnames that resolve to a private IP (DNS rebinding guard)', async () => {
- dnsResolveMock.mockResolvedValue(['10.0.0.42']);
+ lookupMock.mockResolvedValue({ address: '10.0.0.42', family: 4 });
const result = await feeds.addFeed('https://evil.example.com/rss');
expect(result).toEqual({ error: FETCH_ERROR });
expect(fetchMock).not.toHaveBeenCalled();
});
- it('rejects hostnames with no A or AAAA records', async () => {
- dnsResolveMock.mockResolvedValue([]);
- dnsResolve6Mock.mockResolvedValue([]);
- const result = await feeds.addFeed('https://no-records.example.com/rss');
+ it('rejects hostnames that resolve to a link-local / metadata IP', async () => {
+ lookupMock.mockResolvedValue({ address: '169.254.169.254', family: 4 });
+ const result = await feeds.addFeed('https://metadata.example.com/rss');
expect(result).toEqual({ error: FETCH_ERROR });
expect(fetchMock).not.toHaveBeenCalled();
});
- it('rejects when AAAA resolves to a private IPv6 even if A is public (happy-eyeballs SSRF)', async () => {
- dnsResolveMock.mockResolvedValue(['93.184.216.34']);
- dnsResolve6Mock.mockResolvedValue(['fc00::1']);
- const result = await feeds.addFeed('https://dual-stack.example.com/rss');
+ it('fails closed when the hostname cannot be resolved (no unpinned fetch)', async () => {
+ // A hostname we can't vet must never fall through to an unpinned connect —
+ // that connect would re-resolve at TCP time, exactly the rebinding window.
+ lookupMock.mockRejectedValue(Object.assign(new Error('not found'), { code: 'ENOTFOUND' }));
+ const result = await feeds.addFeed('https://no-records.example.com/rss');
expect(result).toEqual({ error: FETCH_ERROR });
expect(fetchMock).not.toHaveBeenCalled();
});
- it('accepts AAAA-only hostnames (no A record, public IPv6)', async () => {
+ it('accepts a hostname that resolves to a public IPv6 address', async () => {
fetchMock.mockResolvedValue(makeResponse({ body: RSS_FIXTURE }));
- dnsResolveMock.mockResolvedValue([]);
- dnsResolve6Mock.mockResolvedValue(['2606:4700:4700::1111']);
+ lookupMock.mockResolvedValue({ address: '2606:4700:4700::1111', family: 6 });
const result = await feeds.addFeed('https://v6only.example.com/rss');
expect(result.error).toBeUndefined();
expect(fetchMock).toHaveBeenCalledTimes(1);
+ // Connection is pinned to the vetted address (undici would otherwise re-resolve).
+ expect(fetchMock.mock.calls[0][1].dispatcher).toBeDefined();
});
- it('rejects AAAA-only hostnames that point to private IPv6', async () => {
- dnsResolveMock.mockResolvedValue([]);
- dnsResolve6Mock.mockResolvedValue(['fe80::1']);
- const result = await feeds.addFeed('https://v6private.example.com/rss');
- expect(result).toEqual({ error: FETCH_ERROR });
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it('rejects when AAAA resolver fails (SERVFAIL) even if A is public (fail-closed)', async () => {
- // Node's fetch may still happy-eyeballs to a private AAAA on its own
- // lookup, so a resolver error on AAAA must reject — we cannot prove
- // the family is safe to fall through to the A result alone.
- const err = Object.assign(new Error('servfail'), { code: 'ESERVFAIL' });
- dnsResolveMock.mockResolvedValue(['93.184.216.34']);
- dnsResolve6Mock.mockRejectedValue(err);
- const result = await feeds.addFeed('https://flaky-aaaa.example.com/rss');
- expect(result).toEqual({ error: FETCH_ERROR });
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it('accepts when AAAA returns NODATA and A is public (benign no-records miss)', async () => {
- // ENODATA means "name exists, no records of this type" — the other
- // family covers the hostname and we should not fail closed on it.
- const err = Object.assign(new Error('no data'), { code: 'ENODATA' });
+ it('pins the connection to the vetted address (rebinding TOCTOU closed)', async () => {
fetchMock.mockResolvedValue(makeResponse({ body: RSS_FIXTURE }));
- dnsResolveMock.mockResolvedValue(['93.184.216.34']);
- dnsResolve6Mock.mockRejectedValue(err);
- const result = await feeds.addFeed('https://a-only.example.com/rss');
- expect(result.error).toBeUndefined();
- expect(fetchMock).toHaveBeenCalledTimes(1);
- });
-
- it('rejects when A resolver fails (TIMEOUT) even if AAAA is public (fail-closed)', async () => {
- const err = Object.assign(new Error('timeout'), { code: 'ETIMEOUT' });
- dnsResolveMock.mockRejectedValue(err);
- dnsResolve6Mock.mockResolvedValue(['2606:4700:4700::1111']);
- const result = await feeds.addFeed('https://flaky-a.example.com/rss');
- expect(result).toEqual({ error: FETCH_ERROR });
- expect(fetchMock).not.toHaveBeenCalled();
+ lookupMock.mockResolvedValue({ address: '93.184.216.34', family: 4 });
+ await feeds.addFeed('https://rebind.example.com/rss');
+ expect(fetchMock.mock.calls[0][1].dispatcher).toBeDefined();
});
it('follows a single safe redirect to the new URL', async () => {
@@ -282,12 +249,13 @@ describe('addFeed', () => {
});
it('rejects redirects to private IPs without making the second fetch', async () => {
- dnsResolveMock.mockImplementation(async (host) => host === 'evil.example.com' ? ['10.0.0.1'] : ['93.184.216.34']);
+ lookupMock.mockImplementation(async (host) =>
+ host === 'evil.example.com' ? { address: '10.0.0.1', family: 4 } : { address: '93.184.216.34', family: 4 });
fetchMock.mockResolvedValueOnce(makeResponse({ status: 302, headers: { location: 'https://evil.example.com/x' } }));
const result = await feeds.addFeed('https://example.com/redirect');
expect(result).toEqual({ error: FETCH_ERROR });
expect(fetchMock).toHaveBeenCalledTimes(1);
- expect(dnsResolveMock).toHaveBeenCalledWith('evil.example.com');
+ expect(lookupMock).toHaveBeenCalledWith('evil.example.com');
});
it('falls back to the URL hostname when the feed has no <title>', async () => {