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: port safeUrlFetch DNS-rebinding IP pinning to undici 8's connector API (#2890)
[._.]/ Adam Eivyda8ee2fd994e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0536f54e1f..0d00f8276f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -76,3 +76,4 @@- **[issue-2899] Fold the Creative Director / Music Video / Sprites `selectBackend()` dispatchers into `pgFileFacade`** — Creative Director, Music Video, and Sprites each memoized their own copy of the same file-vs-Postgres selector (already drifted: differing error text, differing test-mode predicate). A new `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` in `server/lib/pgFileFacade.js` wraps the existing `createPgFileFacade`/`resolvePgBackend` backbone for stores whose backends are whole modules rather than built objects, so the escape-hatch posture, the health-check → `ensureSchema` → one-time-migration bring-up, and the selection memoization live in one place. Public store surfaces are unchanged (`getProjectsBackendName()` still reports `'file'`/`'postgres'`), each store keeps its own requirement message, and Sprites keeps its stronger `isTestRunner()` test-mode signal via the new `isTestMode` hook — no gating semantics were weakened. The selector also exposes a `reset()` test seam matching the `_reset<X>Backend()` exports on the artists/tracks/albums/authors stores, which still hand-roll the same dispatcher and are tracked separately.- **[issue-2842] Barrel-split `checkInfra`, `layeredIntelligence`, and `seriesAutopilot` by sub-domain** — the three remaining ~2.6k-line multi-domain server files each become a thin re-exporting barrel over a new same-named directory, mirroring the `arcPlanner.js` split (#1152). `server/lib/editorial/checkInfra.js` → `checkInfra/{externals,taxonomy,revealForeshadowing,craftStages,voiceCanon,structureStages,povAndNames,canonScaffolding,llmRunner,readability,rosterCast,sceneAnalysis,proseDensity,comic}.js`; `server/services/layeredIntelligence.js` → `layeredIntelligence/{constants,config,dedup,proposal,outcomes,awareness,gates,prompt,runCli,sources,semanticDedup,forgeFiler,jiraFiler,planFiler}.js`; `server/services/pipeline/seriesAutopilot.js` → `seriesAutopilot/{state,config,convergence,stepResolver,session,childRuns,editorialSteps,visualSteps,revisionSteps,dispatch,dryRun,orchestrator}.js`. No caller changes — every existing deep import still resolves through the barrel, and `seriesAutopilot`'s `__testing` bundle is reassembled from the split modules. Three new `*Barrel.test.js` suites pin the contract (every module export reachable through the barrel as the same object, no cross-module symbol collisions). The largest resulting module is 439 lines, down from 2,635.- **[issue-2841] Convert long positional parameter lists to options objects** — `appendIntervalOccurrences` (8 args) and its sibling `appendCronOccurrences` in `server/services/workflow.js`, `scaffoldVite` (7 args) and the equally-long `scaffoldPortOS` in `server/routes/`, and `createAgentRun` (6 args) in `server/services/agentRunTracking.js` now take a single destructured options object, matching the codebase's dominant convention and removing the "which of these five interchangeable numbers goes where" hazard at each call site. All call sites updated; `scaffold.test.js` gains two regression tests pinning the named-options dispatch shape. Behavior-preserving.+- **[issue-2890] Take the held-back `undici` 8 bump** — the failing `safeUrlFetch` pin test turned out not to be about `connect.lookup` at all (undici 8's connector still honors it, so the DNS-rebinding IP pin is expressed exactly as before). undici 8 dropped v7's implicit wrapping of the legacy `onConnect`/`onHeaders`/`onComplete` request-handler shape, so a bare undici-8 `Agent` handed to the *built-in* `fetch` of any Node that still bundles undici 7 (22/24/25, including the 24.x CI matrix) throws `InvalidArgumentError: invalid onRequestStart method` — and because `fetchGuarded` swallows network errors to null, every guarded fetch would have silently returned null rather than falling back to an unpinned connect. The new exported `buildPinnedDispatcher()` wraps the pinned `Agent` in undici 8's documented `Dispatcher1Wrapper`, which both the legacy and the v8 handler contracts accept, so one build works across Node 22→26. The end-to-end pin proof now runs through that production factory instead of a hand-rolled `new Agent(...)`, so it also guards the runtime-compat half.diff --git a/server/lib/README.md b/server/lib/README.mdindex c45e37226d..71983e27f0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -172,7 +172,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). || `abortTimeout.js` | `withAbortTimeout(timeoutMs, fn)` — runs `fn(signal)` under an `AbortController` that aborts after `timeoutMs` and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent `peerFetch` (so can't use `fetchWithTimeout`) or one signal across parallel fetches. || `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |-| `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. |+| `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap) and `buildPinnedLookup`/`buildPinnedDispatcher` (the connect-time IP pin that closes the DNS-rebinding TOCTOU). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. || `pinterestFeed.js` | Pure Pinterest board RSS helpers: `normalizePinterestFeedUrl(input)` (board URL or `.rss` → `{ feedUrl, boardUrl }`, host-gated) + `parsePinterestRss(xml)` (per-pin `pinUrl`/`imageUrl`/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer. || `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes* (keyed off `res` close + `writableEnded`). Plus `anyAbortSignal(signals)` — combine several signals into one (native `AbortSignal.any` with a Node-18 fallback). || `readResponseJson.js` | Read a `Response` body as JSON, tolerating a non-JSON/HTML error page (no `Unexpected token <` crash). Object callers need no opts; pass `{ fallback, emptyValue }` for arrays or to surface the raw error text. |diff --git a/server/lib/safeUrlFetch.js b/server/lib/safeUrlFetch.jsindex 35bf383db7..6859a3c955 100644--- a/server/lib/safeUrlFetch.js+++ b/server/lib/safeUrlFetch.js@@ -24,7 +24,7 @@*/import dns from 'dns/promises';-import { Agent } from 'undici';+import { Agent, Dispatcher1Wrapper } from 'undici';import { ServerError } from './errorHandler.js';import { fetchWithTimeout } from './fetchWithTimeout.js';import { isSafeIngestUrl, isBlockedIngestHost } from './catalogValidation.js';@@ -132,10 +132,16 @@ export async function isPublicHttpUrlSafe(target, { blockPrivate = false } = {})/*** 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.+ * rebinding TOCTOU: undici's connector calls this instead of DNS, so the socket+ * goes to exactly the address the guard approved, while Host header + TLS SNI+ * stay the original hostname (undici's connector derives `servername` from the+ * requested host, not from the resolved address), so cert validation is+ * unaffected. undici asks with `all: true`, so honor both the array and+ * single-address callback shapes.+ *+ * undici 8 kept `connect.lookup` on the built-in connector — the v8 port did not+ * change how the pin itself is expressed, only how the dispatcher is handed to+ * fetch (see buildPinnedDispatcher).*/export function buildPinnedLookup(address, family) {const fam = family || (address.includes(':') ? 6 : 4);@@ -146,18 +152,35 @@ export function buildPinnedLookup(address, 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) } });+/**+ * 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).+ *+ * The `Dispatcher1Wrapper` is REQUIRED, not decorative. We hand this dispatcher+ * to the runtime's global `fetch` (via fetchWithTimeout), and Node's *bundled*+ * undici drives a dispatcher with whichever request-handler contract that Node+ * version speaks. undici 8 dropped v7's implicit wrapping of the legacy+ * (onConnect/onHeaders/onComplete) handler shape, so a bare undici-8 `Agent`+ * handed to the built-in fetch of any Node that still bundles undici 7 (22, 24,+ * 25 — including the 24.x CI matrix) throws `InvalidArgumentError: invalid+ * onRequestStart method` and the request never leaves. Since fetchGuarded+ * swallows network errors to null, that failure would be SILENT: every guarded+ * fetch would return null rather than fall back to an unpinned connect, but the+ * feature would be dead. `Dispatcher1Wrapper` is undici 8's documented adapter+ * for exactly this (the same one `setGlobalDispatcher` mirrors for Node's+ * built-in fetch) and is accepted by both the legacy and the v8 handler+ * contracts, so one build works across Node 22→26.+ */+export function buildPinnedDispatcher(address, family) {+ return new Dispatcher1Wrapper(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, dispatcher: buildPinnedDispatcher(resolved.address, resolved.family) }: options;return fetchWithTimeout(url, fetchOptions, timeoutMs).catch(() => null);}diff --git a/server/lib/safeUrlFetch.test.js b/server/lib/safeUrlFetch.test.jsindex a0b334c297..39d27f4e37 100644--- a/server/lib/safeUrlFetch.test.js+++ b/server/lib/safeUrlFetch.test.js@@ -6,7 +6,6 @@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', () => ({@@ -21,6 +20,7 @@ vi.mock('./fetchWithTimeout.js', () => ({const {isPublicHttpUrlSafe, assertPublicHttpUrl, fetchPublicText, fetchPublicBinary, buildPinnedLookup,+ buildPinnedDispatcher,} = await import('./safeUrlFetch.js');const res = ({ ok = true, status = 200, headers = {}, text = '', body = new ArrayBuffer(0) } = {}) => ({@@ -193,11 +193,16 @@ describe('connect-time IP pinning (DNS-rebinding TOCTOU, #1859)', () => {// 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.+ // Uses the PRODUCTION dispatcher factory (not a hand-rolled `new Agent(...)`)+ // against the runtime's global fetch — the same pairing fetchWithTimeout makes+ // — so this also proves the undici-8 dispatcher is accepted by the built-in+ // fetch of whichever Node runs the suite (see buildPinnedDispatcher's note on+ // the v7/v8 request-handler contract).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 dispatcher = buildPinnedDispatcher('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 pinnedawait dispatcher.close();diff --git a/server/package-lock.json b/server/package-lock.jsonindex 908cf515fa..490e1ff307 100644--- a/server/package-lock.json+++ b/server/package-lock.json@@ -20,7 +20,7 @@"sharp": "0.35.3","socket.io": "4.8.3","socket.io-client": "4.8.3",- "undici": "^7.28.0",+ "undici": "^8.8.0","zod": "^4.4.3"},"devDependencies": {@@ -4758,12 +4758,12 @@}},"node_modules/undici": {- "version": "7.28.0",- "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz",- "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==",+ "version": "8.8.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-8.8.0.tgz",+ "integrity": "sha512-ubshXMXwF3MQIMF1y/WxZdNBnjEKeSg2wF5mcGUtU55YTw34tnVVpKRlLf7ruDXZ5344KokPVX4RBx1wJm64Bw==","license": "MIT","engines": {- "node": ">=20.18.1"+ "node": ">=22.19.0"}},"node_modules/undici-types": {diff --git a/server/package.json b/server/package.jsonindex ccdba3824b..54a0167af0 100644--- a/server/package.json+++ b/server/package.json@@ -27,7 +27,7 @@"sharp": "0.35.3","socket.io": "4.8.3","socket.io-client": "4.8.3",- "undici": "^7.28.0",+ "undici": "^8.8.0","zod": "^4.4.3"},"devDependencies": {