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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: pin SSRF-vetted IP at connect time to close DNS-rebinding TOCTOU (#1859)
[._.]/ Adam Eivyd3b191f1b3d5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8d084fc781..59f7cdb00f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,7 @@## Security+- **`safeUrlFetch` SSRF guard now pins the vetted IP at connect time, closing a DNS-rebinding TOCTOU** — `isPublicHttpUrlSafe` resolved a hostname's DNS to validate it was public, but the subsequent `fetch` re-resolved the same hostname at connect time, so a rebinding host could answer a public address for the check and a loopback/link-local/cloud-metadata address for the actual connection, slipping past the guard. The guard now resolves once and the connection is pinned to that exact validated address via a per-request undici `Agent` whose `connect.lookup` always returns the vetted IP — while Host header and TLS SNI stay the original hostname, so cert validation is unaffected. Every redirect hop is still independently re-validated and re-pinned. (Low real-world exploitability — PortOS is single-user on a private network and URL sources are user-pasted Pinterest boards / stored feeds — but the connect-time re-resolution is now eliminated.) (#1859)- **Resolved active `npm audit` CVEs in the kokoro-js → protobufjs chain and the client `ws` transitive** — the server's `[email protected]` pulled `protobufjs <=7.6.0` (GHSA-wcpc-wj8m-hjx6 DoS, GHSA-f38q-mgvj-vph7), and the stale `protobufjs: 7.5.9` override sat *inside* the vulnerable range. Pinned `kokoro-js` to `1.2.0` (the audit-stated fix, still within the code's documented `^1.2.x` compatibility window — `KokoroTTS`/`TextSplitterStream` exports unchanged) and bumped the `protobufjs` override to `7.6.3` in root + `server/package.json`. On the client, `engine.io-client` nested its own `[email protected]` (GHSA-96hv-2xvq-fx4p memory-exhaustion DoS) that the root `ws: 8.21.0` override couldn't reach; added `ws: 8.21.0` to `client/package.json` overrides. Both `npm audit` runs now report 0 vulnerabilities for these chains. (#1823)- **Backup restore/delete path validation hardened** — `subdirFilter` on `POST /api/backup/restore` was an unconstrained string interpolated into an rsync `--include=${subdirFilter}/***` arg, so `*` could override the filter chain (restoring everything over live data) and `../foo` could traverse out of the snapshot subdir; it now validates against a relative path pattern that rejects wildcard, `..`, and absolute-path segments, with a mirrored defense-in-depth guard in `restoreSnapshot` for non-route callers. `deleteBackup` previously validated `filename.replace(/[.]/g,'')` (so the real dotted filename was never checked, leaving only the `startsWith(backupDir)` guard) — it now validates the raw filename directly and explicitly rejects `..`. (#1822)- **Settings API no longer leaks third-party API tokens** — `GET` and `PUT /api/settings` redacted only the top-level `secrets` key, so `imageGen.hfToken` (HuggingFace) and `civitai.apiKey` were returned in full on both initial load and after any save. Both responses now run through a single sanitizer that strips those tokens (sibling config preserved), matching how the Settings UI already reads only token *presence* from the dedicated `/image-gen/setup/hf-token-status` and `/loras/auth/civitai` status routes. On-disk values are untouched. (#1821)diff --git a/server/lib/safeUrlFetch.js b/server/lib/safeUrlFetch.jsindex cd60b13d20..75ca5b1bb8 100644--- a/server/lib/safeUrlFetch.js+++ b/server/lib/safeUrlFetch.js@@ -18,6 +18,7 @@*/import dns from 'dns/promises';+import { Agent } from 'undici';import { ServerError } from './errorHandler.js';import { fetchWithTimeout } from './fetchWithTimeout.js';import { isSafeIngestUrl, isBlockedIngestHost } from './catalogValidation.js';@@ -26,21 +27,79 @@ const DEFAULT_TIMEOUT_MS = 15000;const DEFAULT_MAX_BYTES = 12 * 1024 * 1024; // 12 MB — generous for a single image/feed/**- * Boolean SSRF gate: scheme + blocked-host-literal (sync, via isSafeIngestUrl),- * AND a DNS resolve so a hostname whose A record points at a blocked address- * (cloud metadata / loopback / link-local) is rejected too. Returns false on any- * failure — never throws — so redirect revalidation can fail closed.+ * 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+ * address (cloud metadata / loopback / link-local) is rejected too. Returns the+ * vetted IP so the caller can PIN it at connect time — closing the DNS-rebinding+ * TOCTOU where a re-resolution at connect could land on a private address the+ * validation lookup never saw. Never throws.+ *+ * `address` is null when there is nothing to pin: an IP-literal target (the+ * connect goes straight to the literal — no name to re-resolve, so no TOCTOU)+ * or a lookup that failed (the fetch falls back to its own resolution, exactly+ * as before, preserving prior fail-open-on-resolve behavior).+ *+ * @returns {Promise<{ safe: boolean, address?: string|null, family?: number }>}*/-export async function isPublicHttpUrlSafe(target) {- if (!isSafeIngestUrl(target)) return false;+async function resolvePublicHttpUrl(target) {+ if (!isSafeIngestUrl(target)) return { safe: false };const { hostname } = new URL(target);- // Host literals were already classified by isSafeIngestUrl; only resolve names.+ // 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) {- const resolved = await dns.lookup(hostname).catch(() => null);- if (resolved?.address && isBlockedIngestHost(resolved.address)) return false;- }- return true;+ if (isIpLiteral) return { safe: true, address: null };+ const resolved = await dns.lookup(hostname).catch(() => null);+ if (resolved?.address && isBlockedIngestHost(resolved.address)) return { safe: false };+ // resolved null (lookup failed) → safe but unpinned (matches prior behavior).+ return { safe: true, address: resolved?.address ?? null, family: resolved?.family };+}++/**+ * Boolean SSRF gate. Returns false on any failure — never throws — so redirect+ * revalidation can fail closed.+ */+export async function isPublicHttpUrlSafe(target) {+ return (await resolvePublicHttpUrl(target)).safe;+}++/**+ * net.lookup-compatible function that ALWAYS yields the SSRF-vetted IP, ignoring+ * the hostname undici would otherwise re-resolve. This is what closes the+ * rebinding TOCTOU: undici connects to exactly the address the guard approved,+ * while Host header + TLS SNI stay the original hostname (undici derives+ * `servername` from the host), so cert validation is unaffected. undici asks+ * with `all: true`, so honor both the array and single-address callback shapes.+ */+export function buildPinnedLookup(address, family) {+ const fam = family || (address.includes(':') ? 6 : 4);+ return (_hostname, options, callback) => {+ const cb = typeof options === 'function' ? options : callback;+ const entry = { address, family: fam };+ cb(null, options?.all ? [entry] : entry.address, entry.family);+ };+}++// One-shot dispatcher that pins every connection to the vetted IP. Created+// per-request and left for GC after the body is consumed (single-user,+// low-volume tool — a pooled keep-alive agent would only hold a stale socket).+function pinnedDispatcher(address, family) {+ return new Agent({ connect: { lookup: buildPinnedLookup(address, family) } });+}++// Fetch the URL with its connection pinned to the SSRF-vetted address (when we+// have one), falling back to the runtime's own resolution otherwise.+function pinnedFetch(url, resolved, options, timeoutMs) {+ const fetchOptions = resolved.address+ ? { ...options, dispatcher: pinnedDispatcher(resolved.address, resolved.family) }+ : options;+ return fetchWithTimeout(url, fetchOptions, timeoutMs).catch(() => null);+}++function throwUnsafeUrl() {+ throw new ServerError('refusing to fetch a non-http(s) or loopback/link-local URL', {+ status: 400,+ code: 'UNSAFE_URL',+ });}/**@@ -48,26 +107,25 @@ export async function isPublicHttpUrlSafe(target) {* target surfaces a clean 400 at the route instead of a silent null.*/export async function assertPublicHttpUrl(target) {- if (!await isPublicHttpUrlSafe(target)) {- throw new ServerError('refusing to fetch a non-http(s) or loopback/link-local URL', {- status: 400,- code: 'UNSAFE_URL',- });- }+ if (!await isPublicHttpUrlSafe(target)) throwUnsafeUrl();}// Fetch with the first-hop gate (throws) + manual redirect revalidation (fails-// closed). Returns the Response, or null on a network error / blocked redirect /-// missing Location. The caller decides what to do with a non-ok status.+// 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 } = {}) {- await assertPublicHttpUrl(url);- const res = await fetchWithTimeout(url, { redirect: 'manual', headers }, timeoutMs).catch(() => null);+ const first = await resolvePublicHttpUrl(url);+ if (!first.safe) throwUnsafeUrl();+ 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;- if (!await isPublicHttpUrlSafe(redirectUrl)) return null;- return fetchWithTimeout(redirectUrl, { redirect: 'error', headers }, timeoutMs).catch(() => null);+ const hop = await resolvePublicHttpUrl(redirectUrl);+ if (!hop.safe) return null;+ return pinnedFetch(redirectUrl, hop, { redirect: 'error', headers }, timeoutMs);}return res;}diff --git a/server/lib/safeUrlFetch.test.js b/server/lib/safeUrlFetch.test.jsindex 31a8965f51..21574f2217 100644--- a/server/lib/safeUrlFetch.test.js+++ b/server/lib/safeUrlFetch.test.js@@ -5,6 +5,8 @@*/import { describe, it, expect, vi, beforeEach } from 'vitest';+import http from 'node:http';+import { Agent } from 'undici';const lookupMock = vi.fn();vi.mock('dns/promises', () => ({@@ -18,7 +20,7 @@ vi.mock('./fetchWithTimeout.js', () => ({}));const {- isPublicHttpUrlSafe, assertPublicHttpUrl, fetchPublicText, fetchPublicBinary,+ isPublicHttpUrlSafe, assertPublicHttpUrl, fetchPublicText, fetchPublicBinary, buildPinnedLookup,} = await import('./safeUrlFetch.js');const res = ({ ok = true, status = 200, headers = {}, text = '', body = new ArrayBuffer(0) } = {}) => ({@@ -86,6 +88,57 @@ describe('fetchPublicText', () => {});});+describe('connect-time IP pinning (DNS-rebinding TOCTOU, #1859)', () => {+ it('pins the vetted address, ignoring the hostname undici would re-resolve', () => {+ const lookup = buildPinnedLookup('93.184.216.34', 4);+ // undici asks with { all: true } → array of { address, family } entries.+ let all;+ lookup('evil.example.com', { all: true }, (_e, addrs) => { all = addrs; });+ expect(all).toEqual([{ address: '93.184.216.34', family: 4 }]);+ // net.lookup single-address shape (no `all`).+ let single;+ lookup('evil.example.com', {}, (_e, addr, fam) => { single = [addr, fam]; });+ expect(single).toEqual(['93.184.216.34', 4]);+ });++ it('derives the family from the address when undici omits it', () => {+ const lookup = buildPinnedLookup('2606:2800:220:1:248:1893:25c8:1946');+ let single;+ lookup('h', {}, (_e, addr, fam) => { single = [addr, fam]; });+ expect(single).toEqual(['2606:2800:220:1:248:1893:25c8:1946', 6]);+ });++ it('hands the fetch a dispatcher pinned to the validation-time address', async () => {+ // Validation resolves the host to a PUBLIC ip; the connection is pinned to+ // that exact address so a connect-time rebind to a private ip is impossible.+ lookupMock.mockResolvedValue({ address: '93.184.216.34', family: 4 });+ fetchMock.mockResolvedValue(res({ text: 'ok' }));+ await fetchPublicText('https://rebind.example.com/x');+ expect(fetchMock.mock.calls[0][1].dispatcher).toBeDefined();+ });++ it('skips pinning (no dispatcher) when the lookup fails — preserves fail-open', async () => {+ lookupMock.mockRejectedValue(new Error('ENOTFOUND'));+ fetchMock.mockResolvedValue(res({ text: 'ok' }));+ await fetchPublicText('https://transient-dns.example.com/x');+ expect(fetchMock.mock.calls[0][1].dispatcher).toBeUndefined();+ });++ // End-to-end proof the mechanism actually defeats rebinding: a hostname that+ // never resolves in real DNS still reaches the server, so undici MUST have+ // used our pinned address rather than re-resolving at connect time.+ it('undici connects to the pinned address for a non-resolving hostname', async () => {+ const server = http.createServer((req, res2) => res2.end(`host:${req.headers.host}`));+ await new Promise((r) => server.listen(0, '127.0.0.1', r));+ const { port } = server.address();+ const dispatcher = new Agent({ connect: { lookup: buildPinnedLookup('127.0.0.1', 4) } });+ const out = await fetch(`http://rebind.invalid:${port}/`, { dispatcher });+ expect(await out.text()).toBe(`host:rebind.invalid:${port}`); // Host preserved, IP pinned+ await dispatcher.close();+ await new Promise((r) => server.close(r));+ });+});+// Streaming response double — getReader() yields the given Uint8Array chunks.const streamRes = (chunks, { headers = {}, ok = true, status = 200 } = {}) => {let i = 0;diff --git a/server/package.json b/server/package.jsonindex 327a38cb98..ab9925b600 100644--- a/server/package.json+++ b/server/package.json@@ -27,6 +27,7 @@"sharp": "0.35.2","socket.io": "4.8.3","socket.io-client": "4.8.3",+ "undici": "^7.28.0","zod": "^4.4.3"},"devDependencies": {