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: resolve Pinterest share links for mood boards (#10530)
[._.]/ Adam Eivyb4b200827845
diff --git a/server/lib/README.md b/server/lib/README.mdindex 55afde6d19..6c3da44202 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -468,8 +468,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `federatedMediaRequest.js` | Builds and validates the versioned federated-media submission body for a visual kind, so every call site that persists a remote-job marker projects local params onto the wire identically. || `federatedMediaWire.js` | Versioned federated-media status schema/constants plus fail-closed consumer freshness checks (stale and clock-skewed snapshots are never assignable). `FEDERATED_MEDIA_FEATURES` + `federatedMediaSupports(status, feature, capability)` answer "does the peer BUILD speak this wire feature" from the status-root `features` list — the one place the "absent reads as the wire-v1 baseline" rule lives; a published list wins outright, with the `inputAssets` capability block retained as its only legacy overlap tell because it is genuinely per-model. `federatedMediaDeclaresFeatures(status)` and `federatedMediaDeniesFeature(status, feature, capability)` separate "positively denied" from "could not establish" for MESSAGE selection only — both gate identically, and which missing signal indicts the peer’s build is recorded per feature rather than at each call site. || `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Reuse when a caller needs a best-effort local reachability signal. Also `isPortReachable({host?, port, timeoutMs?})` — the same connect primitive aimed at ONE address, for "is anything listening there yet?"; use it rather than a bind probe whenever another process is expected to own the port, since a bind probe can win the race and kill that process with `EADDRINUSE`. |-| `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), exported strict `isPrivateAddress`, 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. Also `readBodyCapped(response, maxBytes)` bounds streamed bodies without choosing a network policy. |-| `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. |+| `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), exported strict `isPrivateAddress`, plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap), and `resolvePublicUrl` (bounded, pinned short-link resolution with an optional hop allow-list) 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. Also `readBodyCapped(response, maxBytes)` bounds streamed bodies without choosing a network policy. |+| `pinterestFeed.js` | Pure Pinterest board RSS helpers: `isPinterestHost(host)` (explicit domain allow-list) + `normalizePinterestFeedUrl(input)` (board URL or `.rss` → `{ feedUrl, boardUrl }`, host/path-gated) + `parsePinterestRss(xml)` (per-pin `pinUrl`/`imageUrl`/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer. || `xPostMedia.js` | Pure x.com/twitter.com post helpers: `parseXPostUrl(input)` (post URL → `{ statusId, canonicalUrl }`, host-gated) + `buildSyndicationUrl`/`syndicationToken` (Twitter's public unauthenticated tweet-syndication endpoint) + `extractXPostMedia(json)` (→ `{ images, video }`). Feeds the mood-board X post 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/pinterestFeed.js b/server/lib/pinterestFeed.jsindex 04e5003878..ee4b8f711f 100644--- a/server/lib/pinterestFeed.js+++ b/server/lib/pinterestFeed.js@@ -38,7 +38,7 @@ const PINTEREST_DOMAINS = Object.freeze([// Accepts pinterest.com, www.pinterest.com, br.pinterest.com, pinterest.co.uk;// rejects pinterest.zip, pinterest.evil.com, pinterest.com.evil.com,// evilpinterest.com.-function isPinterestHost(host) {+export function isPinterestHost(host) {const h = host.toLowerCase();return PINTEREST_DOMAINS.some((d) => h === d || h.endsWith(`.${d}`));}@@ -84,6 +84,9 @@ export function normalizePinterestFeedUrl(input) {// /<user>/<board>; the RSS feed always lives at the first two segments.const logicalPath = isRss ? path.slice(0, -'.rss'.length) : path;const segments = logicalPath.split('/').filter(Boolean);+ if (segments.length < 2 || /^(?:pin|login|session|url_shortener)$/i.test(segments[0])) {+ throw badUrl('Use a Pinterest board URL, not a pin or profile link');+ }const isSection = segments.length > 2;const feedPath = isSection ? `/${segments.slice(0, 2).join('/')}.rss` : `${logicalPath}.rss`;// Keep the section path the user pasted as the displayed board URL.diff --git a/server/lib/pinterestFeed.test.js b/server/lib/pinterestFeed.test.jsindex 4290cbecff..e2644c089c 100644--- a/server/lib/pinterestFeed.test.js+++ b/server/lib/pinterestFeed.test.js@@ -66,6 +66,9 @@ describe('normalizePinterestFeedUrl', () => {['embedded brand name', 'https://evilpinterest.com/jane/board'],['ftp scheme', 'ftp://pinterest.com/jane/board'],['root path only', 'https://www.pinterest.com/'],+ ['profile link', 'https://www.pinterest.com/jane/'],+ ['single pin', 'https://www.pinterest.com/pin/123/'],+ ['API shortener instead of board', 'https://api.pinterest.com/url_shortener/code/redirect/'],])('rejects %s with a 400', (_label, input) => {expect(() => normalizePinterestFeedUrl(input)).toThrow();try { normalizePinterestFeedUrl(input); } catch (e) {diff --git a/server/lib/safeUrlFetch.js b/server/lib/safeUrlFetch.jsindex 7b53f493fb..e372e9348c 100644--- a/server/lib/safeUrlFetch.js+++ b/server/lib/safeUrlFetch.js@@ -230,6 +230,40 @@ async function fetchGuarded(url, { timeoutMs = DEFAULT_TIMEOUT_MS, headers, blocreturn res;}+/**+ * Resolve a short URL without reading its body. Every hop is DNS-vetted and+ * pinned, with a bounded redirect count and a shared request-time budget.+ * `allowUrl(URL)` can restrict every hop to a service's own hosts. Returns the+ * final 2xx URL, or null on an unsafe/disallowed hop or resolution failure.+ */+export async function resolvePublicUrl(url, {+ timeoutMs = DEFAULT_TIMEOUT_MS, maxRedirects = 3, headers,+ blockPrivate = false, allowUrl,+} = {}) {+ if (!Number.isInteger(maxRedirects) || maxRedirects < 0 || maxRedirects > 10) return null;+ const deadline = Date.now() + timeoutMs;+ let current = url;+ for (let redirects = 0; redirects <= maxRedirects; redirects++) {+ if (!URL.canParse(current)) return null;+ const target = new URL(current);+ if (allowUrl && !allowUrl(target)) return null;+ const resolved = await resolvePublicHttpUrl(target.href, { blockPrivate });+ const remainingMs = deadline - Date.now();+ if (!resolved.safe || remainingMs <= 0) return null;+ const res = await pinnedFetch(target.href, resolved, { redirect: 'manual', headers }, remainingMs);+ if (!res) return null;+ // Headers are all we need; do not download a Pinterest page (or retain a+ // redirect response's socket) just to learn its destination.+ await res.body?.cancel().catch(() => {});+ if (res.ok) return target.href;+ if (res.status < 300 || res.status >= 400 || redirects === maxRedirects) return null;+ const location = res.headers.get('location');+ if (!location || !URL.canParse(location, target.href)) return null;+ current = new URL(location, target.href).href;+ }+ return null;+}+/*** Read a response body into a Buffer bounded by `maxBytes`, or null when the* body exceeds the cap. The cap is enforced first via Content-Length (cheapdiff --git a/server/lib/safeUrlFetch.test.js b/server/lib/safeUrlFetch.test.jsindex 39d27f4e37..0c78a24914 100644--- a/server/lib/safeUrlFetch.test.js+++ b/server/lib/safeUrlFetch.test.js@@ -20,7 +20,7 @@ vi.mock('./fetchWithTimeout.js', () => ({const {isPublicHttpUrlSafe, assertPublicHttpUrl, fetchPublicText, fetchPublicBinary, buildPinnedLookup,- buildPinnedDispatcher,+ buildPinnedDispatcher, resolvePublicUrl,} = await import('./safeUrlFetch.js');const res = ({ ok = true, status = 200, headers = {}, text = '', body = new ArrayBuffer(0) } = {}) => ({@@ -285,3 +285,60 @@ describe('fetchPublicBinary', () => {expect(r.body._cancel).toHaveBeenCalled(); // stream was cancelled rather than fully read});});+++describe('resolvePublicUrl', () => {+ it('resolves a two-redirect share chain, pins each hop and cancels every body', async () => {+ const cancel = vi.fn().mockResolvedValue();+ fetchMock.mockResolvedValueOnce({ ...res({ status: 302, ok: false, headers: { location: 'https://api.pinterest.com/url_shortener/example/redirect/' } }), body: { cancel } })+ .mockResolvedValueOnce({ ...res({ status: 302, ok: false, headers: { location: 'https://www.pinterest.com/example/board/?invite_code=example' } }), body: { cancel } })+ .mockResolvedValueOnce({ ...res(), body: { cancel } });+ expect(await resolvePublicUrl('https://pin.it/example', { timeoutMs: 8000, blockPrivate: true }))+ .toBe('https://www.pinterest.com/example/board/?invite_code=example');+ expect(lookupMock.mock.calls.map(([host]) => host)).toEqual(['pin.it', 'api.pinterest.com', 'www.pinterest.com']);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ for (const [, options, timeout] of fetchMock.mock.calls) {+ expect(options).toMatchObject({ redirect: 'manual', dispatcher: expect.anything() });+ expect(timeout).toBeLessThanOrEqual(8000);+ }+ expect(cancel).toHaveBeenCalledTimes(3);+ });++ it('stops before another fetch when the shared timeout budget expires', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValueOnce(0).mockReturnValueOnce(100).mockReturnValue(900);+ fetchMock.mockResolvedValue(res({ status: 302, ok: false, headers: { location: '/next' } }));+ try {+ expect(await resolvePublicUrl('https://pin.it/example', { timeoutMs: 800 })).toBeNull();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0][2]).toBe(700);+ } finally {+ now.mockRestore();+ }+ });++ it('refuses a redirect outside the caller allow-list before resolving or fetching it', async () => {+ fetchMock.mockResolvedValue(res({ status: 302, ok: false, headers: { location: 'https://example.com/board' } }));+ expect(await resolvePublicUrl('https://pin.it/example', { allowUrl: (url) => url.hostname === 'pin.it' })).toBeNull();+ expect(lookupMock).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('refuses a redirect whose DNS resolves private under strict policy', async () => {+ lookupMock.mockResolvedValueOnce({ address: '93.184.216.34' }).mockResolvedValueOnce({ address: '192.168.1.1' });+ fetchMock.mockResolvedValue(res({ status: 302, ok: false, headers: { location: 'https://www.pinterest.com/example/board/' } }));+ expect(await resolvePublicUrl('https://pin.it/example', { blockPrivate: true })).toBeNull();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('bounds redirect loops and fails closed on missing/malformed locations and network errors', async () => {+ fetchMock.mockResolvedValue(res({ status: 302, ok: false, headers: { location: '/loop' } }));+ expect(await resolvePublicUrl('https://pin.it/example', { maxRedirects: 2 })).toBeNull();+ expect(fetchMock).toHaveBeenCalledTimes(3);+ fetchMock.mockResolvedValue(res({ status: 302, ok: false }));+ expect(await resolvePublicUrl('https://pin.it/example')).toBeNull();+ fetchMock.mockResolvedValue(res({ status: 302, ok: false, headers: { location: 'http://[' } }));+ expect(await resolvePublicUrl('https://pin.it/example')).toBeNull();+ fetchMock.mockRejectedValue(new Error('network failure'));+ expect(await resolvePublicUrl('https://pin.it/example')).toBeNull();+ });+});diff --git a/server/services/moodBoard/pinterest.js b/server/services/moodBoard/pinterest.jsindex ae0b217117..3348010015 100644--- a/server/services/moodBoard/pinterest.js+++ b/server/services/moodBoard/pinterest.js@@ -26,6 +26,7 @@ import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js'import { emitRecordUpdated } from '../sharing/recordEvents.js';import { MAX_ITEMS_PER_BOARD } from './logic.js';import * as store from './db.js';+import { resolvePinterestBoardUrl } from './pinterestUrl.js';const FEED_TIMEOUT_MS = 20000;const IMAGE_TIMEOUT_MS = 20000;@@ -68,7 +69,7 @@ export async function downloadPinImage({ pinUrl, imageUrl, imageUrlOriginal }) {* normalizes the URL (throws 400 on a non-Pinterest host) and stores the link.*/export async function linkPinterestBoard(boardId, { url }) {- const { feedUrl, boardUrl, isSection } = normalizePinterestFeedUrl(url);+ const { feedUrl, boardUrl, isSection } = await resolvePinterestBoardUrl(url);const board = await store.setPinterestLink(boardId, { feedUrl, boardUrl });emitRecordUpdated('moodBoard', boardId);console.log(`📌 Pinterest link set: board ${boardId} → ${feedUrl}${isSection ? ' (section URL — feed covers the whole board; Pinterest has no per-section RSS)' : ''}`);diff --git a/server/services/moodBoard/pinterest.test.js b/server/services/moodBoard/pinterest.test.jsindex d089ad761c..4d17f87e83 100644--- a/server/services/moodBoard/pinterest.test.js+++ b/server/services/moodBoard/pinterest.test.js@@ -16,7 +16,7 @@ const store = {};vi.mock('./db.js', () => store);-const net = { fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn() };+const net = { fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn(), resolvePublicUrl: vi.fn() };vi.mock('../../lib/safeUrlFetch.js', () => net);const emitRecordUpdated = vi.fn();@@ -49,6 +49,38 @@ const PIN1 = { title: 'one', link: 'https://www.pinterest.com/pin/1/', img: 'httconst PIN2 = { title: 'two', link: 'https://www.pinterest.com/pin/2/', img: 'https://i.pinimg.com/236x/b.jpg' };describe('linkPinterestBoard', () => {+ it('resolves a share link, stores the canonical feed and syncs its pins', async () => {+ net.resolvePublicUrl.mockResolvedValue('https://www.pinterest.com/example/board/?invite_code=example');+ store.setPinterestLink.mockImplementation(async (id, pinterest) => ({ id, items: [], pinterest }));+ const linked = await linkPinterestBoard('mb-1', { url: 'https://pin.it/example' });+ expect(linked.pinterest).toEqual({+ feedUrl: 'https://www.pinterest.com/example/board.rss',+ boardUrl: 'https://www.pinterest.com/example/board/',+ });+ const [, policy] = net.resolvePublicUrl.mock.calls[0];+ expect(policy).toMatchObject({ blockPrivate: true, timeoutMs: 8000, maxRedirects: 3 });+ expect(policy.allowUrl(new URL('https://api.pinterest.com/url_shortener/example/redirect/'))).toBe(true);+ expect(policy.allowUrl(new URL('https://pinterest.com.evil.com/example/board/'))).toBe(false);+ store.getBoard.mockResolvedValue(linked);+ net.fetchPublicText.mockResolvedValue(feedXml(PIN1));+ net.fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from([0xff, 0xd8, 0xff, 0x00]) });+ store.appendPinterestItems.mockImplementation(async (_id, imported) => ({ board: linked, added: imported.length }));+ expect(await syncPinterestBoard('mb-1')).toMatchObject({ added: 1, feedCount: 1 });+ expect(net.fetchPublicText).toHaveBeenCalledWith(linked.pinterest.feedUrl, expect.anything());+ expect(store.appendPinterestItems.mock.calls[0][1][0]).toMatchObject({ source: PIN1.link });+ });++ it.each([+ ['pin', 'https://www.pinterest.com/pin/123/'],+ ['unrelated host', 'https://example.com/example/board/'],+ ['unresolved share', null],+ ])('rejects a share link resolving to %s without storing a link', async (_label, destination) => {+ net.resolvePublicUrl.mockResolvedValue(destination);+ await expect(linkPinterestBoard('mb-1', { url: 'https://pin.it/example' }))+ .rejects.toMatchObject({ status: 400, code: 'INVALID_PINTEREST_URL' });+ expect(store.setPinterestLink).not.toHaveBeenCalled();+ });+it('normalizes the URL and stores the link', async () => {store.setPinterestLink.mockResolvedValue({ id: 'mb-1', pinterest: { feedUrl: 'x' } });await linkPinterestBoard('mb-1', { url: 'https://www.pinterest.com/jane/board/' });diff --git a/server/services/moodBoard/pinterestUrl.js b/server/services/moodBoard/pinterestUrl.jsnew file mode 100644index 0000000000..e900fffbb4--- /dev/null+++ b/server/services/moodBoard/pinterestUrl.js@@ -0,0 +1,27 @@+import { ServerError } from '../../lib/errorHandler.js';+import { isPinterestHost, normalizePinterestFeedUrl } from '../../lib/pinterestFeed.js';+import { resolvePublicUrl } from '../../lib/safeUrlFetch.js';++// Keep ordinary board URLs synchronous/pure; only a user-supplied share link+// needs network I/O. The API shortener hop is on Pinterest's own domain.+export async function resolvePinterestBoardUrl(input) {+ const url = typeof input === 'string' && URL.canParse(input.trim()) ? new URL(input.trim()) : null;+ if (url?.hostname !== 'pin.it') return normalizePinterestFeedUrl(input);+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.port) {+ throw new ServerError('Use an http(s) Pinterest share link', { status: 400, code: 'INVALID_PINTEREST_URL' });+ }+ url.protocol = 'https:';+ const resolved = await resolvePublicUrl(url.href, {+ timeoutMs: 8000,+ maxRedirects: 3,+ blockPrivate: true,+ allowUrl: (hop) => hop.protocol === 'https:' && !hop.username && !hop.password && !hop.port+ && (hop.hostname === 'pin.it' || isPinterestHost(hop.hostname)),+ });+ if (!resolved) {+ throw new ServerError('Could not resolve this Pinterest share link to a board; try its full board URL', {+ status: 400, code: 'INVALID_PINTEREST_URL',+ });+ }+ return normalizePinterestFeedUrl(resolved);+}diff --git a/server/services/moodBoard/privatePinterest.js b/server/services/moodBoard/privatePinterest.jsindex 24f2ff3c32..5b3e276a8c 100644--- a/server/services/moodBoard/privatePinterest.js+++ b/server/services/moodBoard/privatePinterest.js@@ -16,6 +16,7 @@ import { emitRecordUpdated } from '../sharing/recordEvents.js';import { MAX_ITEMS_PER_BOARD } from './logic.js';import * as store from './db.js';import { downloadPinImage } from './pinterest.js';+import { resolvePinterestBoardUrl } from './pinterestUrl.js';const PINTEREST_PAGE_SETTLE_MS = 2500;// The pinned DOM scan can take up to roughly 58 seconds: a 32 × 250 ms@@ -142,7 +143,7 @@ function sameBoardPath(left, right) {* @returns {Promise<{ board: object, added: number, found: number, skipped: number }>}*/export async function importPrivatePinterestBoard(boardId, { url }) {- const { boardUrl } = normalizePinterestFeedUrl(url);+ const { boardUrl } = await resolvePinterestBoardUrl(url);const board = await store.getBoard(boardId);if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/services/moodBoard/privatePinterest.test.js b/server/services/moodBoard/privatePinterest.test.jsindex 1b6aab40b4..4a04cbffdb 100644--- a/server/services/moodBoard/privatePinterest.test.js+++ b/server/services/moodBoard/privatePinterest.test.js@@ -25,6 +25,9 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {};});+const resolvePublicUrl = vi.hoisted(() => vi.fn());+vi.mock('../../lib/safeUrlFetch.js', () => ({ resolvePublicUrl }));+const downloadPinImage = vi.hoisted(() => vi.fn());vi.mock('./pinterest.js', () => ({ downloadPinImage }));@@ -63,6 +66,24 @@ beforeEach(() => {});describe('importPrivatePinterestBoard', () => {+ it('opens the resolved canonical board for a share link and imports its pins', async () => {+ resolvePublicUrl.mockResolvedValue(BOARD_URL + '?invite_code=example');+ mockReadableBoard({ boardTitle: 'Example Board', loginRequired: false, expectedCount: 1, pins: [firstPin] });+ expect(await importPrivatePinterestBoard('mb-example', { url: 'https://pin.it/example' }))+ .toMatchObject({ added: 1, found: 1 });+ expect(browser.navigateToUrlPinned).toHaveBeenCalledWith(BOARD_URL, expect.anything());+ expect(store.appendImportedItems.mock.calls[0][1][0]).toMatchObject({ source: firstPin.source });+ });++ it.each(['https://www.pinterest.com/pin/123/', 'https://example.com/example/board/'])+ ('rejects a non-board share destination before opening the browser: %s', async (destination) => {+ resolvePublicUrl.mockResolvedValue(destination);+ await expect(importPrivatePinterestBoard('mb-example', { url: 'https://pin.it/example' }))+ .rejects.toMatchObject({ status: 400, code: 'INVALID_PINTEREST_URL' });+ expect(browser.navigateToUrlPinned).not.toHaveBeenCalled();+ expect(store.appendImportedItems).not.toHaveBeenCalled();+ });+it('reads the requested board through pinned CDP and appends re-hosted, source-deduped images', async () => {store.getBoard.mockResolvedValue({id: 'mb-example',