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
add Pinterest board importer for mood boards (RSS link + manual sync)
[._.]/ Adam Eivy8f0fa0fa099b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 66a09e50a0..db559767e1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased+## Mood boards++- **Import a Pinterest board into a mood board — link it once, then "Sync now" pulls new pins on demand.** Paste a public Pinterest board URL onto a mood board and PortOS fetches the board's RSS feed, downloads each pin's image into your own `data/images/` (so it federates with the board and survives Pinterest link rot), and pins it as an image item with the pin's title as the caption and its permalink as the source. Syncing is incremental: the first sync after linking pulls everything the feed exposes; later syncs add only pins it hasn't seen (deduped by permalink), and re-linking to a different board pulls that one down. NOTE: Pinterest's RSS exposes only the most-recent ~25 pins, not the entire board — the UI states this rather than implying a full backfill. Feed and image fetches go through a new shared SSRF-guarded fetcher (`server/lib/safeUrlFetch.js`), and the link rides the board record's JSONB so it federates with no schema-version bump. (`server/lib/pinterestFeed.js`, `server/services/moodBoard/pinterest.js`, `server/routes/moodBoard.js`, `client/src/pages/MoodBoardDetail.jsx`)+## Creative onramp- **[issue-1633] A new "Start a Story" page gives you one clear front door for beginning a story.** Instead of guessing whether to open the Story Builder, the Importer, or the Writers Room, you now pick how you want to begin — from an idea, from an existing work, or by writing prose — and the page routes you into the right tool. You can also choose up front whether to start a fresh universe or attach the story to one you already have; that choice carries through to the Story Builder and Importer automatically. All the existing pages stay exactly where they were — this just adds a signposted entry point (reachable from the sidebar, ⌘K, and voice). (First phase of the larger creative-onramp effort; prose-mode universe linking comes later.)diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsxindex 6932aa9119..4b20605a66 100644--- a/client/src/pages/MoodBoardDetail.jsx+++ b/client/src/pages/MoodBoardDetail.jsx@@ -11,7 +11,7 @@import { useEffect, useState, useCallback } from 'react';import { useParams, useNavigate, Link } from 'react-router-dom';-import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save } from 'lucide-react';+import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw } from 'lucide-react';import toast from '../components/ui/Toast';import InlineConfirmRow from '../components/ui/InlineConfirmRow';import {@@ -20,8 +20,12 @@ import {addMoodBoardItem,updateMoodBoardItem,removeMoodBoardItem,+ linkMoodBoardPinterest,+ unlinkMoodBoardPinterest,+ syncMoodBoardPinterest,} from '../services/api';import { moodBoardItemSrc } from '../lib/moodBoardItemSrc';+import { timeAgo } from '../utils/formatters';export default function MoodBoardDetail() {const { id } = useParams();@@ -41,6 +45,12 @@ export default function MoodBoardDetail() {const [source, setSource] = useState('');const [adding, setAdding] = useState(false);+ // Pinterest link/sync.+ const [pinUrl, setPinUrl] = useState('');+ const [linking, setLinking] = useState(false);+ const [syncing, setSyncing] = useState(false);+ const [confirmingUnlink, setConfirmingUnlink] = useState(false);+const load = useCallback(async () => {setLoading(true);const data = await getMoodBoard(id, { silent: true }).catch(() => null);@@ -48,6 +58,7 @@ export default function MoodBoardDetail() {setBoard(data);setName(data.name || '');setDescription(data.description || '');+ setPinUrl(data.pinterest?.boardUrl || '');} else {toast.error('Mood board not found');}@@ -104,6 +115,36 @@ export default function MoodBoardDetail() {setBoard((prev) => (prev ? { ...prev, items: (prev.items || []).filter((it) => it.id !== itemId) } : prev));};+ const handleLinkPinterest = async () => {+ if (!pinUrl.trim()) { toast.error('Enter a Pinterest board URL'); return; }+ setLinking(true);+ const updated = await linkMoodBoardPinterest(id, pinUrl.trim(), { silent: true }).catch(() => null);+ setLinking(false);+ if (!updated) { toast.error('Could not link that Pinterest URL — is it a public board?'); return; }+ setBoard(updated);+ setPinUrl(updated.pinterest?.boardUrl || pinUrl.trim());+ toast.success('Pinterest board linked');+ };++ const handleUnlinkPinterest = async () => {+ setConfirmingUnlink(false);+ const updated = await unlinkMoodBoardPinterest(id, { silent: true }).catch(() => null);+ if (!updated) { toast.error('Failed to unlink'); return; }+ setBoard(updated);+ setPinUrl('');+ };++ const handleSyncPinterest = async () => {+ setSyncing(true);+ const result = await syncMoodBoardPinterest(id, { silent: true }).catch(() => null);+ setSyncing(false);+ if (!result?.board) { toast.error('Pinterest sync failed — the feed may be private or rate-limited'); return; }+ setBoard(result.board);+ toast.success(result.added > 0+ ? `Added ${result.added} new pin${result.added === 1 ? '' : 's'}`+ : 'Up to date — no new pins');+ };+if (loading) {return <div className="text-gray-400 text-sm py-8 text-center">Loading…</div>;}@@ -117,6 +158,42 @@ export default function MoodBoardDetail() {}const items = Array.isArray(board.items) ? board.items : [];+ const linkedFeedUrl = board.pinterest?.feedUrl || '';+ const linkedBoardUrl = board.pinterest?.boardUrl || '';+ const lastSyncedAt = board.pinterest?.lastSyncedAt || null;+ // "Sync now" reads the SAVED feed URL server-side, so disable it while the URL+ // input differs from what's persisted — otherwise a user edits the URL, doesn't+ // click Link, hits Sync, and the OLD board syncs.+ const pinDirty = pinUrl.trim() !== linkedBoardUrl;+ const isLinked = !!linkedFeedUrl;++ // The board-URL input is identical whether linking fresh or re-pointing an+ // already-linked board — only the label/button text and (for a re-link) the+ // dirty gate differ.+ const renderPinUrlForm = (label, buttonText) => (+ <div>+ <label htmlFor="pinterest-url" className="block text-xs text-gray-400 mb-1">{label}</label>+ <div className="flex gap-2">+ <input+ id="pinterest-url"+ type="text"+ value={pinUrl}+ maxLength={2048}+ placeholder="https://www.pinterest.com/user/board/"+ onChange={(e) => setPinUrl(e.target.value)}+ className="flex-1 min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none"+ />+ <button+ type="button"+ onClick={handleLinkPinterest}+ disabled={linking || !pinUrl.trim() || (isLinked && !pinDirty)}+ className="px-3 py-1.5 text-sm rounded bg-port-success text-white hover:bg-port-success/80 disabled:opacity-50 transition-colors"+ >+ {linking ? 'Linking…' : buttonText}+ </button>+ </div>+ </div>+ );return (<div className="max-w-5xl mx-auto">@@ -166,6 +243,70 @@ export default function MoodBoardDetail() {</div></div>+ {/* Pinterest link + sync */}+ <div className="bg-port-card border border-port-border rounded-md p-4 mb-6">+ <div className="flex items-center gap-2 mb-3">+ <Link2 className="w-4 h-4 text-port-accent" aria-hidden="true" />+ <h2 className="text-sm font-medium text-white">Pinterest board</h2>+ </div>+ {linkedFeedUrl ? (+ <div className="space-y-3">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">+ <a+ href={linkedBoardUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="text-port-accent hover:underline truncate max-w-full"+ >+ {linkedBoardUrl}+ </a>+ <span className="text-gray-500">+ {lastSyncedAt ? `Last synced ${timeAgo(lastSyncedAt)}` : 'Not synced yet'}+ </span>+ </div>+ <p className="text-[11px] text-gray-500">+ Pinterest’s feed exposes only the most-recent ~25 pins, so a sync pulls those — not the entire board.+ </p>+ <div className="flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={handleSyncPinterest}+ disabled={syncing || linking || pinDirty}+ title={pinDirty ? 'Link the new URL before syncing' : undefined}+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 transition-colors"+ >+ <RefreshCw className={`w-4 h-4 ${syncing ? 'animate-spin' : ''}`} aria-hidden="true" />+ {syncing ? 'Syncing…' : 'Sync now'}+ </button>+ {confirmingUnlink ? (+ <InlineConfirmRow+ question="Unlink this board?"+ confirmText="Unlink"+ onConfirm={handleUnlinkPinterest}+ onCancel={() => setConfirmingUnlink(false)}+ />+ ) : (+ <button+ type="button"+ onClick={() => setConfirmingUnlink(true)}+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-bg text-gray-400 hover:text-white transition-colors"+ >+ <Unlink className="w-4 h-4" aria-hidden="true" /> Unlink+ </button>+ )}+ </div>+ {renderPinUrlForm('Change board URL', 'Update')}+ </div>+ ) : (+ <div>+ {renderPinUrlForm('Board URL', 'Link')}+ <p className="text-[11px] text-gray-500 mt-2">+ Paste a public Pinterest board URL. “Sync now” downloads its pins (newest ~25) into this board.+ </p>+ </div>+ )}+ </div>+{/* Add item */}<div className="bg-port-card border border-port-border rounded-md p-4 mb-6"><div className="flex items-center gap-2 mb-3" role="tablist" aria-label="Item type">diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.jsindex a124f711ea..afcc3943d6 100644--- a/client/src/services/apiMoodBoard.js+++ b/client/src/services/apiMoodBoard.js@@ -45,3 +45,24 @@ export const removeMoodBoardItem = (id, itemId, options) =>method: 'DELETE',...options,});++// Pinterest importer: link a board to a Pinterest board URL, unlink, and run a+// manual "Sync now" that pulls new pins (download + dedupe) server-side.+export const linkMoodBoardPinterest = (id, url, options) =>+ request(`/mood-boards/${encodeURIComponent(id)}/pinterest`, {+ method: 'PUT',+ body: JSON.stringify({ url }),+ ...options,+ });++export const unlinkMoodBoardPinterest = (id, options) =>+ request(`/mood-boards/${encodeURIComponent(id)}/pinterest`, {+ method: 'DELETE',+ ...options,+ });++export const syncMoodBoardPinterest = (id, options) =>+ request(`/mood-boards/${encodeURIComponent(id)}/pinterest/sync`, {+ method: 'POST',+ ...options,+ });diff --git a/server/lib/README.md b/server/lib/README.mdindex a4987f2e47..1c16d031ef 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -144,6 +144,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). || `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. |+| `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. || `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary). |diff --git a/server/lib/index.js b/server/lib/index.jsindex a574c660f0..99e38733fa 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -138,7 +138,9 @@ export * from './networkExposure.js';export * from './peerHttpClient.js';export * from './peerSelfHost.js';export * from './peerUrl.js';+export * from './pinterestFeed.js';export * from './readResponseJson.js';+export * from './safeUrlFetch.js';export * from './sharingOrigin.js';export * from './syncIntegrity.js';export * from './syncWire.js';diff --git a/server/lib/moodBoardValidation.js b/server/lib/moodBoardValidation.jsindex e71959fb84..dd9123ff51 100644--- a/server/lib/moodBoardValidation.js+++ b/server/lib/moodBoardValidation.js@@ -72,6 +72,17 @@ export const moodBoardItemCreateSchema = z.object({}});+// Pinterest link body. The URL shape is validated lightly here (present, http(s),+// bounded); the Pinterest-host check + board-URL→feed-URL normalization happens+// in `normalizePinterestFeedUrl` (server/lib/pinterestFeed.js), which throws a+// specific 400 so the user sees *why* a non-Pinterest URL was rejected.+export const moodBoardPinterestLinkSchema = z.object({+ url: z.string().trim().min(1).max(2048).refine(+ (v) => /^https?:\/\//.test(v),+ 'url must be an http(s) Pinterest board URL',+ ),+}).strict();+// Item PATCH — caption/source on any item, plus the type-appropriate body// field. No `type` switch (an item's kind is fixed at creation); every field// optional so a partial edit validates.diff --git a/server/lib/pinterestFeed.js b/server/lib/pinterestFeed.jsnew file mode 100644index 0000000000..91537007c8--- /dev/null+++ b/server/lib/pinterestFeed.js@@ -0,0 +1,129 @@+/**+ * Pinterest board RSS — pure URL normalization + feed parsing (no I/O).+ *+ * A public Pinterest board exposes an RSS feed at `<board-url>.rss` (e.g.+ * `https://www.pinterest.com/user/board.rss`). The feed returns the board's+ * most-recent pins only (Pinterest caps it at ~the latest 25), NOT the full+ * board — the mood-board importer surfaces that limit in the UI. Each `<item>`+ * carries the pin's permalink (`<link>`) plus an image, which Pinterest places+ * in one of a few spots (`<media:content>`, `<enclosure>`, or an `<img>` inside+ * the HTML `<description>`); we probe all three.+ *+ * Kept pure (string in → data out) so the parsing + URL rules are unit-tested+ * without a network. The fetching/SSRF-guarding lives in `safeUrlFetch.js` and+ * the download/persist orchestration in `services/moodBoard/pinterest.js`.+ */++import { ServerError } from './errorHandler.js';++// pinterest.com, www.pinterest.com, pinterest.co.uk, br.pinterest.com, …+const PINTEREST_HOST_RE = /(^|\.)pinterest\.[a-z]{2,}(\.[a-z]{2,})?$/i;++const badUrl = (msg) => new ServerError(msg, { status: 400, code: 'INVALID_PINTEREST_URL' });++/**+ * Normalize a user-supplied Pinterest board URL (or an already-`.rss` feed URL)+ * into `{ feedUrl, boardUrl }`. Accepts the human board URL and appends `.rss`;+ * passes a `.rss` URL through. Throws a 400 ServerError for a non-URL, a+ * non-http(s) scheme, a non-Pinterest host, or a board-less root path.+ */+export function normalizePinterestFeedUrl(input) {+ if (typeof input !== 'string' || !input.trim()) {+ throw badUrl('A Pinterest board URL is required');+ }+ let u;+ try { u = new URL(input.trim()); } catch { throw badUrl('Not a valid URL'); }+ if (u.protocol !== 'http:' && u.protocol !== 'https:') {+ throw badUrl('Pinterest URL must be http(s)');+ }+ const host = u.hostname.toLowerCase();+ if (!PINTEREST_HOST_RE.test(host)) {+ throw badUrl('That doesn’t look like a Pinterest board URL');+ }+ // A board lives at /<user>/<board>/ and its feed at /<user>/<board>.rss.+ const path = u.pathname.replace(/\/+$/, '');+ if (!path) {+ throw badUrl('Include the board path, e.g. pinterest.com/user/board');+ }+ const isRss = path.toLowerCase().endsWith('.rss');+ const feedPath = isRss ? path : `${path}.rss`;+ const boardPath = isRss ? path.slice(0, -'.rss'.length) : path;+ return {+ feedUrl: `https://${host}${feedPath}`,+ boardUrl: `https://${host}${boardPath}/`,+ };+}++// Minimal HTML-entity decode for URLs/titles pulled out of the feed (the+// feed escapes `&` as `&` inside attribute values, which would corrupt an+// image URL's query string if left encoded).+const decodeEntities = (s) => (typeof s === 'string'+ ? s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/�?39;/g, "'").trim()+ : s);++// Non-greedy single-tag text extractor (CDATA-aware). Mirrors feeds.js's+// extractTag; kept local because the Pinterest parser also needs the RAW+// (un-stripped) <description> HTML to dig the <img> out of, which feeds.js's+// HTML-stripping reader discards.+const extractTag = (xml, tag) => {+ const re = new RegExp(`<${tag}[^>]*>\\s*(?:<!\\[CDATA\\[)?([\\s\\S]*?)(?:\\]\\]>)?\\s*</${tag}>`, 'i');+ const m = xml.match(re);+ return m ? m[1].trim() : '';+};++const stripHtml = (html) => html+ .replace(/<[^>]+>/g, ' ')+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/�?39;/g, "'")+ .replace(/\s+/g, ' ')+ .trim();++// Pull the pin's image URL from whichever of the three slots the feed used.+function extractImageUrl(block, rawDescription) {+ const media = block.match(/<media:content[^>]*\burl=["']([^"']+)["']/i);+ if (media) return media[1];+ const enclosure = block.match(/<enclosure\b[^>]*\burl=["']([^"']+)["'][^>]*>/i);+ if (enclosure) return enclosure[1];+ const img = rawDescription.match(/<img[^>]*\bsrc=["']([^"']+)["']/i);+ if (img) return img[1];+ return '';+}++// Pinterest serves a pin's image at several widths under a size segment in the+// path (`/236x/`, `/474x/`, `/736x/`, `/originals/`). The RSS feed links the+// small 236x thumbnail; bump it to 736x for a board-worthy resolution. Leaves+// `/originals/` and already-large paths untouched. Caller keeps the original as+// a download fallback in case the upsized variant 404s.+function upgradePinImageSize(url) {+ return url.replace(/\/\d{2,4}x\//, '/736x/');+}++/**+ * Parse a Pinterest board RSS document into pins. Skips any item missing a+ * permalink or an image. Returns `[{ pinUrl, imageUrl, imageUrlOriginal, title,+ * description, pubDate }]` — `pinUrl` is the dedupe key the importer stores as+ * each board item's `source`.+ */+export function parsePinterestRss(xml) {+ if (typeof xml !== 'string' || !xml) return [];+ const channelMatch = xml.match(/<channel>([\s\S]*)<\/channel>/i);+ const channel = channelMatch ? channelMatch[1] : xml;+ const blocks = channel.match(/<item>([\s\S]*?)<\/item>/gi) || [];+ const pins = [];+ for (const block of blocks) {+ const pinUrl = decodeEntities(extractTag(block, 'link') || extractTag(block, 'guid'));+ const rawDescription = extractTag(block, 'description');+ const found = decodeEntities(extractImageUrl(block, rawDescription));+ if (!pinUrl || !found) continue;+ pins.push({+ pinUrl,+ imageUrl: upgradePinImageSize(found),+ imageUrlOriginal: found,+ title: stripHtml(extractTag(block, 'title')).slice(0, 500),+ description: stripHtml(rawDescription).slice(0, 500),+ pubDate: extractTag(block, 'pubDate'),+ });+ }+ return pins;+}diff --git a/server/lib/pinterestFeed.test.js b/server/lib/pinterestFeed.test.jsnew file mode 100644index 0000000000..e9e1c97754--- /dev/null+++ b/server/lib/pinterestFeed.test.js@@ -0,0 +1,103 @@+/**+ * Pure tests for the Pinterest board RSS helpers — URL normalization rules and+ * per-pin extraction (image slot probing + size upgrade). No network.+ */++import { describe, it, expect } from 'vitest';+import { normalizePinterestFeedUrl, parsePinterestRss } from './pinterestFeed.js';++describe('normalizePinterestFeedUrl', () => {+ it('appends .rss to a board URL and keeps the human board URL', () => {+ expect(normalizePinterestFeedUrl('https://www.pinterest.com/jane/cyberpunk/')).toEqual({+ feedUrl: 'https://www.pinterest.com/jane/cyberpunk.rss',+ boardUrl: 'https://www.pinterest.com/jane/cyberpunk/',+ });+ });++ it('passes a .rss feed URL through (derives the board URL back)', () => {+ expect(normalizePinterestFeedUrl('https://www.pinterest.com/jane/cyberpunk.rss')).toEqual({+ feedUrl: 'https://www.pinterest.com/jane/cyberpunk.rss',+ boardUrl: 'https://www.pinterest.com/jane/cyberpunk/',+ });+ });++ it('forces https and tolerates a trailing slash', () => {+ expect(normalizePinterestFeedUrl('http://pinterest.com/jane/board').feedUrl)+ .toBe('https://pinterest.com/jane/board.rss');+ });++ it('accepts country-code Pinterest hosts', () => {+ expect(normalizePinterestFeedUrl('https://br.pinterest.com/jane/board/').feedUrl)+ .toBe('https://br.pinterest.com/jane/board.rss');+ });++ it.each([+ ['empty', ''],+ ['not a url', 'not a url'],+ ['non-pinterest host', 'https://example.com/jane/board'],+ ['pinterest look-alike', 'https://pinterest.com.evil.com/jane/board'],+ ['ftp scheme', 'ftp://pinterest.com/jane/board'],+ ['root path only', 'https://www.pinterest.com/'],+ ])('rejects %s with a 400', (_label, input) => {+ expect(() => normalizePinterestFeedUrl(input)).toThrow();+ try { normalizePinterestFeedUrl(input); } catch (e) {+ expect(e.status).toBe(400);+ expect(e.code).toBe('INVALID_PINTEREST_URL');+ }+ });+});++describe('parsePinterestRss', () => {+ const item = (inner) => `<item>${inner}</item>`;+ const wrap = (items) => `<rss><channel><title>Board</title>${items.join('')}</channel></rss>`;++ it('extracts the img from the description HTML and upgrades 236x → 736x', () => {+ const xml = wrap([item(`+ <title>Neon alley</title>+ <link>https://www.pinterest.com/pin/111/</link>+ <description><![CDATA[<a href="/pin/111/"><img src="https://i.pinimg.com/236x/aa/bb/cc.jpg"></a> a moody alley]]></description>+ <pubDate>Mon, 01 Jan 2026 00:00:00 GMT</pubDate>+ `)]);+ const pins = parsePinterestRss(xml);+ expect(pins).toHaveLength(1);+ expect(pins[0]).toMatchObject({+ pinUrl: 'https://www.pinterest.com/pin/111/',+ imageUrl: 'https://i.pinimg.com/736x/aa/bb/cc.jpg',+ imageUrlOriginal: 'https://i.pinimg.com/236x/aa/bb/cc.jpg',+ title: 'Neon alley',+ description: 'a moody alley',+ });+ });++ it('prefers <media:content> over an <img>, and decodes & in URLs', () => {+ const xml = wrap([item(`+ <link>https://www.pinterest.com/pin/222/</link>+ <media:content url="https://i.pinimg.com/736x/x.jpg?a=1&b=2" />+ <description><![CDATA[<img src="https://i.pinimg.com/236x/ignored.jpg">]]></description>+ `)]);+ const pins = parsePinterestRss(xml);+ expect(pins[0].imageUrl).toBe('https://i.pinimg.com/736x/x.jpg?a=1&b=2');+ });++ it('falls back to <enclosure> when there is no media:content or img', () => {+ const xml = wrap([item(`+ <link>https://www.pinterest.com/pin/333/</link>+ <enclosure url="https://i.pinimg.com/474x/e.jpg" type="image/jpeg" length="1" />+ <description><![CDATA[no img here]]></description>+ `)]);+ expect(parsePinterestRss(xml)[0].imageUrl).toBe('https://i.pinimg.com/736x/e.jpg');+ });++ it('skips items with no image or no permalink', () => {+ const xml = wrap([+ item(`<link>https://www.pinterest.com/pin/444/</link><description>no image</description>`),+ item(`<description><![CDATA[<img src="https://i.pinimg.com/236x/z.jpg">]]></description>`),+ ]);+ expect(parsePinterestRss(xml)).toEqual([]);+ });++ it('returns [] for non-string / empty input', () => {+ expect(parsePinterestRss('')).toEqual([]);+ expect(parsePinterestRss(null)).toEqual([]);+ });+});diff --git a/server/lib/safeUrlFetch.js b/server/lib/safeUrlFetch.jsnew file mode 100644index 0000000000..3f89f0b745--- /dev/null+++ b/server/lib/safeUrlFetch.js@@ -0,0 +1,99 @@+/**+ * Safe public-URL fetch — SSRF-guarded text/binary fetch for "go grab this+ * remote thing the user pointed us at" flows (RSS feeds, remote images, …).+ *+ * Centralizes the guard so new callers reuse ONE implementation instead of+ * copying the host-parsing logic a fourth time (it already lives, subtly+ * differently, in feeds.js `fetchFeedXml` and catalogIngestSources.js+ * `assertIngestUrlSafe`). The hard part — classifying a host literal as+ * loopback/link-local/cloud-metadata across IPv4 / IPv6 / IPv4-mapped forms —+ * is reused from `catalogValidation.isBlockedIngestHost`; this module adds the+ * DNS-resolve check and the redirect-revalidating fetch wrappers on top.+ *+ * Posture (matches the catalog ingest gate): block non-http(s) schemes,+ * loopback, link-local, and the cloud-metadata endpoint; ALLOW other+ * 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.+ */++import dns from 'dns/promises';+import { ServerError } from './errorHandler.js';+import { fetchWithTimeout } from './fetchWithTimeout.js';+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++/**+ * 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.+ */+export async function isPublicHttpUrlSafe(target) {+ if (!isSafeIngestUrl(target)) return false;+ const { hostname } = new URL(target);+ // Host literals were already classified by isSafeIngestUrl; only resolve names.+ 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;+}++/**+ * 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)) {+ throw new ServerError('refusing to fetch a non-http(s) or loopback/link-local URL', {+ status: 400,+ code: 'UNSAFE_URL',+ });+ }+}++// 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.+async function fetchGuarded(url, { timeoutMs = DEFAULT_TIMEOUT_MS, headers } = {}) {+ await assertPublicHttpUrl(url);+ const res = await fetchWithTimeout(url, { redirect: 'manual', headers }, timeoutMs).catch(() => null);+ 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);+ }+ return res;+}++/**+ * 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).+ */+export async function fetchPublicText(url, { timeoutMs, headers } = {}) {+ const res = await fetchGuarded(url, { timeoutMs, headers });+ if (!res?.ok) return null;+ return res.text();+}++/**+ * Fetch a URL's body as a Buffer. Returns `{ buffer, contentType }` on a 2xx+ * within the size cap, or null on any failure. The size cap is enforced first+ * via Content-Length (cheap early-out) and again after the body is read (a+ * server can lie about / omit the header).+ */+export async function fetchPublicBinary(url, { timeoutMs, headers, maxBytes = DEFAULT_MAX_BYTES } = {}) {+ const res = await fetchGuarded(url, { timeoutMs, headers });+ if (!res?.ok) return null;+ const declared = Number(res.headers.get('content-length'));+ if (maxBytes && Number.isFinite(declared) && declared > maxBytes) return null;+ const buffer = Buffer.from(await res.arrayBuffer());+ if (maxBytes && buffer.byteLength > maxBytes) return null;+ return { buffer, contentType: res.headers.get('content-type') || '' };+}diff --git a/server/lib/safeUrlFetch.test.js b/server/lib/safeUrlFetch.test.jsnew file mode 100644index 0000000000..7112fa3b61--- /dev/null+++ b/server/lib/safeUrlFetch.test.js@@ -0,0 +1,102 @@+/**+ * Tests for the SSRF-guarded public-URL fetch helpers. The DNS resolver and the+ * underlying fetchWithTimeout are mocked so the guard + redirect-revalidation+ * logic is exercised without a network.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const lookupMock = vi.fn();+vi.mock('dns/promises', () => ({+ default: { lookup: (...a) => lookupMock(...a) },+ lookup: (...a) => lookupMock(...a),+}));++const fetchMock = vi.fn();+vi.mock('./fetchWithTimeout.js', () => ({+ fetchWithTimeout: (...a) => fetchMock(...a),+}));++const {+ isPublicHttpUrlSafe, assertPublicHttpUrl, fetchPublicText, fetchPublicBinary,+} = await import('./safeUrlFetch.js');++const res = ({ ok = true, status = 200, headers = {}, text = '', body = new ArrayBuffer(0) } = {}) => ({+ ok,+ status,+ headers: new Map(Object.entries(headers)), // Headers-like: supports .get()+ text: async () => text,+ arrayBuffer: async () => body,+});++beforeEach(() => {+ lookupMock.mockReset();+ fetchMock.mockReset();+ lookupMock.mockResolvedValue({ address: '93.184.216.34' }); // public+});++describe('isPublicHttpUrlSafe', () => {+ it('accepts a public https URL', async () => {+ expect(await isPublicHttpUrlSafe('https://www.pinterest.com/x.rss')).toBe(true);+ });+ it('rejects non-http(s) schemes', async () => {+ expect(await isPublicHttpUrlSafe('file:///etc/passwd')).toBe(false);+ expect(await isPublicHttpUrlSafe('ftp://host/x')).toBe(false);+ });+ it('rejects loopback / metadata host literals without resolving', async () => {+ expect(await isPublicHttpUrlSafe('http://127.0.0.1/x')).toBe(false);+ expect(await isPublicHttpUrlSafe('http://169.254.169.254/latest/meta-data')).toBe(false);+ expect(lookupMock).not.toHaveBeenCalled();+ });+ it('rejects a hostname that RESOLVES to a blocked address', async () => {+ lookupMock.mockResolvedValue({ address: '127.0.0.1' });+ expect(await isPublicHttpUrlSafe('https://evil.example.com/x')).toBe(false);+ });+});++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' });+ });+ it('resolves for a safe target', async () => {+ await expect(assertPublicHttpUrl('https://example.com/x')).resolves.toBeUndefined();+ });+});++describe('fetchPublicText', () => {+ it('returns the body on a 2xx', async () => {+ fetchMock.mockResolvedValue(res({ text: '<rss/>' }));+ expect(await fetchPublicText('https://example.com/feed.rss')).toBe('<rss/>');+ });+ it('returns null on a non-ok status', async () => {+ fetchMock.mockResolvedValue(res({ ok: false, status: 404 }));+ expect(await fetchPublicText('https://example.com/feed.rss')).toBeNull();+ });+ it('follows a redirect only after revalidating the target', async () => {+ fetchMock+ .mockResolvedValueOnce(res({ status: 301, headers: { location: 'https://cdn.example.com/feed.rss' } }))+ .mockResolvedValueOnce(res({ text: 'ok' }));+ expect(await fetchPublicText('https://example.com/feed.rss')).toBe('ok');+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+ it('drops a redirect to a blocked host (fails closed)', async () => {+ fetchMock.mockResolvedValueOnce(res({ status: 302, headers: { location: 'http://169.254.169.254/x' } }));+ expect(await fetchPublicText('https://example.com/feed.rss')).toBeNull();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe('fetchPublicBinary', () => {+ it('returns the buffer + content-type within the cap', async () => {+ const bytes = new Uint8Array([1, 2, 3]).buffer;+ fetchMock.mockResolvedValue(res({ body: bytes, headers: { 'content-type': 'image/jpeg' } }));+ const out = await fetchPublicBinary('https://i.pinimg.com/736x/x.jpg');+ expect(out.contentType).toBe('image/jpeg');+ expect(out.buffer).toBeInstanceOf(Buffer);+ expect(out.buffer.length).toBe(3);+ });+ it('rejects a body over the declared Content-Length cap', async () => {+ fetchMock.mockResolvedValue(res({ headers: { 'content-length': String(99 * 1024 * 1024) } }));+ expect(await fetchPublicBinary('https://i.pinimg.com/x.jpg', { maxBytes: 1024 })).toBeNull();+ });+});diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.jsindex 19adeb4426..9f2b09e4be 100644--- a/server/routes/moodBoard.js+++ b/server/routes/moodBoard.js@@ -15,6 +15,7 @@ import {moodBoardUpdateSchema,moodBoardItemCreateSchema,moodBoardItemUpdateSchema,+ moodBoardPinterestLinkSchema,} from '../lib/validation.js';import {listBoards,@@ -25,6 +26,9 @@ import {addBoardItem,updateBoardItem,removeBoardItem,+ linkPinterestBoard,+ unlinkPinterestBoard,+ syncPinterestBoard,} from '../services/moodBoard/index.js';const router = Router();@@ -74,4 +78,22 @@ router.delete('/:id/items/:itemId', asyncHandler(async (req, res) => {res.json(board);}));+// Link the board to a public Pinterest board's RSS feed.+router.put('/:id/pinterest', asyncHandler(async (req, res) => {+ const data = validateRequest(moodBoardPinterestLinkSchema, req.body);+ const board = await linkPinterestBoard(req.params.id, data);+ res.json(board);+}));++router.delete('/:id/pinterest', asyncHandler(async (req, res) => {+ const board = await unlinkPinterestBoard(req.params.id);+ res.json(board);+}));++// Manual "Sync now" — pull new pins from the linked feed into the board.+router.post('/:id/pinterest/sync', asyncHandler(async (req, res) => {+ const result = await syncPinterestBoard(req.params.id);+ res.json(result);+}));+export default router;diff --git a/server/services/moodBoard/db.js b/server/services/moodBoard/db.jsindex a3c95aa543..32e880c7f3 100644--- a/server/services/moodBoard/db.js+++ b/server/services/moodBoard/db.js@@ -32,6 +32,9 @@ import {updateItem,removeItem,mergeBoardRecord,+ applyPinterestLink,+ clearPinterestLinkRecord,+ appendPinterestPins,} from './logic.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,@@ -230,6 +233,34 @@ export async function updateBoardItem(id, itemId, patch) {return result;}+// ─── Pinterest board link (mood-board importer) ──────────────────────────────++// Link (or re-link) the board to a Pinterest RSS feed.+export async function setPinterestLink(id, link) {+ const { board } = await withLockedBoard(id, (b) => ({ board: applyPinterestLink(b, link) }));+ return board;+}++// Unlink. Skips the write (and peer push) when the board wasn't linked.+export async function clearPinterestLink(id) {+ const { board } = await withLockedBoard(id, (b) => {+ const { board: next, changed } = clearPinterestLinkRecord(b);+ return { board: next, skipPersist: !changed };+ });+ return board;+}++// Append the freshly-downloaded pins in ONE locked write (rather than N+// addBoardItem round-trips) and stamp lastSyncedAt. Always persists so a+// zero-new sync still records the check. Returns { board, added }.+export async function appendPinterestItems(id, imported, opts = {}) {+ const { board, result } = await withLockedBoard(id, (b) => {+ const { board: next, added } = appendPinterestPins(b, imported, opts);+ return { board: next, result: { added } };+ });+ return { board, ...result };+}+export async function removeBoardItem(id, itemId) {// Unknown itemId → skip the write entirely (no-op, no updated_at bump). The// route still 200s — removing an already-gone item is idempotent.diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.jsindex 263087476d..c0f99a6975 100644--- a/server/services/moodBoard/index.js+++ b/server/services/moodBoard/index.js@@ -31,6 +31,11 @@ export {} from './db.js';export { imageUrlToAppAsset } from './logic.js';+// Pinterest importer (link + manual "Sync now"). Lives in its own module+// (network I/O + image download) but is surfaced here so routes import a single+// moodBoard entry. It fires its own federation emits after each store mutation.+export { linkPinterestBoard, unlinkPinterestBoard, syncPinterestBoard } from './pinterest.js';+// Announce a newly-created board to the per-record peer-sync pipeline: emit the// 'updated' event so any existing subscription pushes it, AND auto-subscribe// every moodBoards-enabled peer so brand-new boards (and their later tombstones)diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.jsindex efaf1315f1..ca3ba78969 100644--- a/server/services/moodBoard/logic.js+++ b/server/services/moodBoard/logic.js@@ -239,3 +239,68 @@ export function applyBoardRestore(board, patch) {next.updatedAt = nowIso();return next;}++// ─── Pinterest board link (mood-board importer) ──────────────────────────────+// A board can be linked to a public Pinterest board's RSS feed. The link is an+// additive `pinterest` sub-object on the board record — it rides through+// sanitizeBoardForSync's `...raw` spread, so it federates with the board (no+// schema-version bump: full-record LWW, and an older peer preserves the unknown+// key). `lastSyncedAt` tracks the most recent manual "Sync now".++// Set (or replace) the Pinterest link, preserving any prior sync timestamp so+// re-linking the SAME board doesn't lose "last synced" context.+export function applyPinterestLink(board, { feedUrl, boardUrl }) {+ const prior = board.pinterest || {};+ return {+ ...board,+ pinterest: {+ feedUrl,+ boardUrl: boardUrl ?? null,+ lastSyncedAt: prior.lastSyncedAt ?? null,+ },+ updatedAt: nowIso(),+ };+}++// Remove the Pinterest link. Returns changed:false (no write) when the board+// wasn't linked, so the db layer can skip a wasted row rewrite + peer push.+export function clearPinterestLinkRecord(board) {+ if (!board.pinterest) return { board, changed: false };+ const next = { ...board };+ delete next.pinterest;+ next.updatedAt = nowIso();+ return { board: next, changed: true };+}++/**+ * Append already-downloaded Pinterest pins as image items, then stamp the sync+ * timestamp. Each `imported` entry is `{ imageUrl, caption, source }` where+ * `source` is the pin permalink — the dedupe key. Skips pins whose `source`+ * already exists on the board (in-lock safety net; the service pre-dedupes+ * before downloading) and respects MAX_ITEMS_PER_BOARD by truncating to the+ * remaining capacity rather than throwing — a partial import beats a hard+ * mid-sync failure. Always re-stamps `pinterest.lastSyncedAt` (even on zero new)+ * so the UI reflects the check. Returns `{ board, added }`.+ */+export function appendPinterestPins(board, imported, { syncedAt = nowIso() } = {}) {+ const items = Array.isArray(board.items) ? board.items : [];+ const seen = new Set(items.map((it) => it && it.source).filter(Boolean));+ const capacity = Math.max(0, MAX_ITEMS_PER_BOARD - items.length);+ const fresh = [];+ for (const imp of Array.isArray(imported) ? imported : []) {+ if (fresh.length >= capacity) break;+ if (imp.source && seen.has(imp.source)) continue;+ if (imp.source) seen.add(imp.source);+ fresh.push(normalizeItem(+ { type: 'image', imageUrl: imp.imageUrl, caption: imp.caption ?? null, source: imp.source ?? null },+ { id: `mbi-${randomUUID()}`, now: syncedAt },+ ));+ }+ const next = {+ ...board,+ items: [...items, ...fresh],+ pinterest: { ...(board.pinterest || {}), lastSyncedAt: syncedAt },+ updatedAt: nowIso(),+ };+ return { board: next, added: fresh.length };+}diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.jsindex 859339caaf..4381877205 100644--- a/server/services/moodBoard/logic.test.js+++ b/server/services/moodBoard/logic.test.js@@ -16,6 +16,9 @@ import {mergeBoardRecord,imageUrlToAppAsset,MAX_ITEMS_PER_BOARD,+ applyPinterestLink,+ clearPinterestLinkRecord,+ appendPinterestPins,} from './logic.js';describe('buildBoardRecord', () => {@@ -231,3 +234,75 @@ describe('applyBoardRestore', () => {expect(applyBoardRestore(base, { items: 'nope' }).items).toEqual([{ id: 'x' }]);});});++describe('applyPinterestLink', () => {+ const base = () => buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });++ it('stores the feed + board URLs and seeds sync state', () => {+ const next = applyPinterestLink(base(), { feedUrl: 'https://www.pinterest.com/j/b.rss', boardUrl: 'https://www.pinterest.com/j/b/' });+ expect(next.pinterest).toEqual({+ feedUrl: 'https://www.pinterest.com/j/b.rss',+ boardUrl: 'https://www.pinterest.com/j/b/',+ lastSyncedAt: null,+ });+ expect(next.updatedAt).not.toBe('t0');+ });++ it('preserves the prior sync timestamp when re-linking', () => {+ const linked = { ...base(), pinterest: { feedUrl: 'old', boardUrl: 'oldb', lastSyncedAt: 's1' } };+ const next = applyPinterestLink(linked, { feedUrl: 'new', boardUrl: 'newb' });+ expect(next.pinterest).toMatchObject({ feedUrl: 'new', lastSyncedAt: 's1' });+ });+});++describe('clearPinterestLinkRecord', () => {+ it('removes the pinterest field and bumps updatedAt', () => {+ const linked = { ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), pinterest: { feedUrl: 'f' } };+ const { board, changed } = clearPinterestLinkRecord(linked);+ expect(changed).toBe(true);+ expect(board.pinterest).toBeUndefined();+ expect(board.updatedAt).not.toBe('t0');+ });++ it('is a no-op when not linked', () => {+ const board = buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });+ const out = clearPinterestLinkRecord(board);+ expect(out.changed).toBe(false);+ expect(out.board).toBe(board);+ });+});++describe('appendPinterestPins', () => {+ const linked = () => ({+ ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }),+ pinterest: { feedUrl: 'f', boardUrl: 'b', lastSyncedAt: null },+ });+ const imp = (n) => ({ imageUrl: `/data/images/p${n}.jpg`, caption: `c${n}`, source: `https://www.pinterest.com/pin/${n}/` });++ it('appends image items and stamps sync state', () => {+ const { board, added } = appendPinterestPins(linked(), [imp(1), imp(2)], { syncedAt: 's1' });+ expect(added).toBe(2);+ expect(board.items.map((it) => it.source)).toEqual(['https://www.pinterest.com/pin/1/', 'https://www.pinterest.com/pin/2/']);+ expect(board.items[0]).toMatchObject({ type: 'image', imageUrl: '/data/images/p1.jpg', caption: 'c1' });+ expect(board.pinterest).toMatchObject({ lastSyncedAt: 's1' });+ });++ it('dedupes against existing item sources', () => {+ const existing = { ...linked(), items: [{ id: 'mbi-x', type: 'image', source: 'https://www.pinterest.com/pin/1/' }] };+ const { added, board } = appendPinterestPins(existing, [imp(1), imp(2)], { syncedAt: 's1' });+ expect(added).toBe(1);+ expect(board.items).toHaveLength(2);+ });++ it('stamps lastSyncedAt even when nothing new was added', () => {+ const { board, added } = appendPinterestPins(linked(), [], { syncedAt: 's2' });+ expect(added).toBe(0);+ expect(board.pinterest).toMatchObject({ lastSyncedAt: 's2' });+ });++ it('truncates to MAX_ITEMS_PER_BOARD capacity', () => {+ const full = { ...linked(), items: Array.from({ length: MAX_ITEMS_PER_BOARD - 1 }, (_, i) => ({ id: `e${i}`, type: 'image', source: `e${i}` })) };+ const { added } = appendPinterestPins(full, [imp(1), imp(2), imp(3)], { syncedAt: 's1' });+ expect(added).toBe(1);+ });+});diff --git a/server/services/moodBoard/pinterest.js b/server/services/moodBoard/pinterest.jsnew file mode 100644index 0000000000..7e81bfde2e--- /dev/null+++ b/server/services/moodBoard/pinterest.js@@ -0,0 +1,123 @@+/**+ * Mood Board — Pinterest importer (link + manual sync).+ *+ * A mood board can be linked to a public Pinterest board's RSS feed. "Sync now"+ * fetches the feed, downloads each NEW pin's image into the local gallery+ * (`data/images/`, so it federates as a normal board-item asset and survives+ * Pinterest link rot), and appends it as an image item — deduping by the pin+ * permalink stored as the item's `source`. The very first sync on a freshly+ * linked board pulls everything the feed exposes; later syncs add only what's+ * new. NOTE: Pinterest's RSS returns the most-recent pins only (~25), NOT the+ * full board — the UI states this; we never claim a complete backfill.+ *+ * Network I/O (feed fetch + image downloads) runs OUTSIDE the board row lock;+ * the resulting items land in a single locked `appendPinterestItems` write.+ * Re-exported through index.js (the public moodBoard entry) so the route imports+ * one module; the federation emit is fired here after each store mutation.+ */++import { createHash } from 'crypto';+import { writeFile } from 'fs/promises';+import { join } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS, ensureDir, detectImageFormat } from '../../lib/fileUtils.js';+import { normalizePinterestFeedUrl, parsePinterestRss } from '../../lib/pinterestFeed.js';+import { fetchPublicText, fetchPublicBinary } from '../../lib/safeUrlFetch.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';+import { MAX_ITEMS_PER_BOARD } from './logic.js';+import * as store from './db.js';++const FEED_TIMEOUT_MS = 20000;+const IMAGE_TIMEOUT_MS = 20000;+const MAX_IMAGE_BYTES = 12 * 1024 * 1024;+// Pinterest 403s obviously-bot user-agents on its CDN; present a browsery one.+const PINTEREST_UA = 'Mozilla/5.0 (compatible; PortOS Mood Board/1.0; +https://github.com/atomantic/PortOS)';+const FEED_HEADERS = { 'User-Agent': PINTEREST_UA, Accept: 'application/rss+xml, application/xml, text/xml' };+const IMAGE_HEADERS = { 'User-Agent': PINTEREST_UA, Accept: 'image/*' };+// One origin (i.pinimg.com) serves every pin and 403s bot-ish traffic, so keep+// the download fan-out small — fast enough for a 25-pin first sync, polite enough+// to avoid rate-limiting. The caller ensures data/images/ exists once up front.+const DOWNLOAD_CONCURRENCY = 3;++/**+ * Download a pin's image into data/images/ and return its served path+ * (`/data/images/<file>`), or null on failure. Tries the upsized (736x) URL+ * first, falling back to the original feed URL if it 404s. The filename is keyed+ * on the pin permalink so re-downloading the same pin is idempotent. Format ++ * extension are sniffed from the actual bytes (via detectImageFormat), which+ * also rejects a non-image body (an error/HTML page served with 200) — more+ * trustworthy than Pinterest's Content-Type header.+ */+async function downloadPinImage({ pinUrl, imageUrl, imageUrlOriginal }) {+ let res = await fetchPublicBinary(imageUrl, { timeoutMs: IMAGE_TIMEOUT_MS, headers: IMAGE_HEADERS, maxBytes: MAX_IMAGE_BYTES });+ if (!res?.buffer?.length && imageUrlOriginal && imageUrlOriginal !== imageUrl) {+ res = await fetchPublicBinary(imageUrlOriginal, { timeoutMs: IMAGE_TIMEOUT_MS, headers: IMAGE_HEADERS, maxBytes: MAX_IMAGE_BYTES });+ }+ if (!res?.buffer?.length) return null;+ const fmt = detectImageFormat(res.buffer);+ if (!fmt) return null;+ const filename = `pinterest-${createHash('sha1').update(pinUrl).digest('hex').slice(0, 16)}${fmt.ext}`;+ await writeFile(join(PATHS.images, filename), res.buffer);+ return `/data/images/${filename}`;+}++/**+ * Link a board to a Pinterest board URL (or `.rss` feed URL). Validates ++ * normalizes the URL (throws 400 on a non-Pinterest host) and stores the link.+ */+export async function linkPinterestBoard(boardId, { url }) {+ const { feedUrl, boardUrl } = normalizePinterestFeedUrl(url);+ const board = await store.setPinterestLink(boardId, { feedUrl, boardUrl });+ emitRecordUpdated('moodBoard', boardId);+ console.log(`📌 Pinterest link set: board ${boardId} → ${feedUrl}`);+ return board;+}++export async function unlinkPinterestBoard(boardId) {+ const board = await store.clearPinterestLink(boardId);+ emitRecordUpdated('moodBoard', boardId);+ return board;+}++/**+ * Sync the linked Pinterest board: fetch the feed, download every NEW pin's+ * image, append them in one locked write. Returns `{ board, added, skipped,+ * feedCount }`. Throws 404 (no board), 400 (not linked), or 502 (feed+ * unreachable).+ */+export async function syncPinterestBoard(boardId) {+ const board = await store.getBoard(boardId);+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });+ const feedUrl = board.pinterest?.feedUrl;+ if (!feedUrl) throw new ServerError('This board is not linked to a Pinterest board', { status: 400, code: 'NOT_LINKED' });++ const xml = await fetchPublicText(feedUrl, { timeoutMs: FEED_TIMEOUT_MS, headers: FEED_HEADERS });+ if (!xml) throw new ServerError('Could not fetch the Pinterest feed (it may be private or rate-limited)', { status: 502, code: 'FEED_FETCH_FAILED' });++ const pins = parsePinterestRss(xml);+ const items = Array.isArray(board.items) ? board.items : [];+ const seen = new Set(items.map((it) => it?.source).filter(Boolean));+ const capacity = Math.max(0, MAX_ITEMS_PER_BOARD - items.length);+ // Pre-dedupe by pin permalink BEFORE downloading so we don't fetch images we'd+ // discard, and cap to remaining board capacity to avoid orphan downloads.+ const candidates = pins.filter((p) => p.pinUrl && !seen.has(p.pinUrl)).slice(0, capacity);++ // Download in small concurrent batches (preserving feed order) instead of one+ // at a time — the candidates are independent, sha1-named by permalink.+ await ensureDir(PATHS.images);+ const imported = [];+ for (let i = 0; i < candidates.length; i += DOWNLOAD_CONCURRENCY) {+ const batch = candidates.slice(i, i + DOWNLOAD_CONCURRENCY);+ const results = await Promise.all(batch.map(async (pin) => {+ const localUrl = await downloadPinImage(pin);+ return localUrl ? { imageUrl: localUrl, caption: pin.title || pin.description || null, source: pin.pinUrl } : null;+ }));+ for (const r of results) if (r) imported.push(r);+ }++ const syncedAt = new Date().toISOString();+ const { board: nextBoard, added } = await store.appendPinterestItems(boardId, imported, { syncedAt });+ emitRecordUpdated('moodBoard', boardId);+ console.log(`📌 Pinterest sync: board ${boardId} +${added} new (${pins.length} pins in feed)`);+ return { board: nextBoard, added, feedCount: pins.length };+}diff --git a/server/services/moodBoard/pinterest.test.js b/server/services/moodBoard/pinterest.test.jsnew file mode 100644index 0000000000..9dab055e6a--- /dev/null+++ b/server/services/moodBoard/pinterest.test.js@@ -0,0 +1,131 @@+/**+ * Pinterest importer orchestration tests. The network (safeUrlFetch), the board+ * store (db.js), disk (fs/promises + fileUtils), and the federation emit are+ * mocked; the real pure parser (pinterestFeed) runs so the feed→pin→item+ * pipeline is exercised end to end without a DB or network.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const store = {+ getBoard: vi.fn(),+ setPinterestLink: vi.fn(),+ clearPinterestLink: vi.fn(),+ appendPinterestItems: vi.fn(),+};+vi.mock('./db.js', () => store);++const net = { fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn() };+vi.mock('../../lib/safeUrlFetch.js', () => net);++const emitRecordUpdated = vi.fn();+vi.mock('../sharing/recordEvents.js', () => ({ emitRecordUpdated: (...a) => emitRecordUpdated(...a) }));++const writeFile = vi.fn();+vi.mock('fs/promises', () => ({ writeFile: (...a) => writeFile(...a) }));+// Keep the real detectImageFormat (byte-sniffing) — only override PATHS/ensureDir.+vi.mock('../../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ PATHS: { images: '/tmp/imgs' },+ ensureDir: vi.fn(),+}));++const { linkPinterestBoard, unlinkPinterestBoard, syncPinterestBoard } = await import('./pinterest.js');++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'log').mockImplementation(() => {});+});++const feedXml = (...pins) => `<rss><channel>${pins.map((p) => `+ <item>+ <title>${p.title}</title>+ <link>${p.link}</link>+ <description><![CDATA[<img src="${p.img}">]]></description>+ </item>`).join('')}</channel></rss>`;++const PIN1 = { title: 'one', link: 'https://www.pinterest.com/pin/1/', img: 'https://i.pinimg.com/236x/a.jpg' };+const PIN2 = { title: 'two', link: 'https://www.pinterest.com/pin/2/', img: 'https://i.pinimg.com/236x/b.jpg' };++describe('linkPinterestBoard', () => {+ 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/' });+ expect(store.setPinterestLink).toHaveBeenCalledWith('mb-1', {+ feedUrl: 'https://www.pinterest.com/jane/board.rss',+ boardUrl: 'https://www.pinterest.com/jane/board/',+ });+ expect(emitRecordUpdated).toHaveBeenCalledWith('moodBoard', 'mb-1');+ });++ it('rejects a non-Pinterest URL before touching the store', async () => {+ await expect(linkPinterestBoard('mb-1', { url: 'https://example.com/x' })).rejects.toMatchObject({ status: 400 });+ expect(store.setPinterestLink).not.toHaveBeenCalled();+ });+});++describe('unlinkPinterestBoard', () => {+ it('clears the link and emits', async () => {+ store.clearPinterestLink.mockResolvedValue({ id: 'mb-1' });+ await unlinkPinterestBoard('mb-1');+ expect(store.clearPinterestLink).toHaveBeenCalledWith('mb-1');+ expect(emitRecordUpdated).toHaveBeenCalledWith('moodBoard', 'mb-1');+ });+});++describe('syncPinterestBoard', () => {+ it('404s when the board is missing', async () => {+ store.getBoard.mockResolvedValue(null);+ await expect(syncPinterestBoard('mb-x')).rejects.toMatchObject({ status: 404 });+ });++ it('400s when the board is not linked', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [] });+ await expect(syncPinterestBoard('mb-1')).rejects.toMatchObject({ status: 400, code: 'NOT_LINKED' });+ });++ it('502s when the feed cannot be fetched', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [], pinterest: { feedUrl: 'https://www.pinterest.com/j/b.rss' } });+ net.fetchPublicText.mockResolvedValue(null);+ await expect(syncPinterestBoard('mb-1')).rejects.toMatchObject({ status: 502 });+ });++ it('downloads only NEW pins, persists images, and appends them', async () => {+ store.getBoard.mockResolvedValue({+ id: 'mb-1',+ // pin 1 already on the board → should be deduped out+ items: [{ id: 'mbi-old', type: 'image', source: 'https://www.pinterest.com/pin/1/' }],+ pinterest: { feedUrl: 'https://www.pinterest.com/j/b.rss' },+ });+ net.fetchPublicText.mockResolvedValue(feedXml(PIN1, PIN2));+ // Valid JPEG magic bytes — downloadPinImage sniffs the format from the bytes.+ net.fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from([0xff, 0xd8, 0xff, 0x00]), contentType: 'image/jpeg' });+ store.appendPinterestItems.mockImplementation(async (_id, imported) => ({ board: { id: 'mb-1' }, added: imported.length }));++ const result = await syncPinterestBoard('mb-1');++ // only pin 2 was downloaded (pin 1 deduped before fetching)+ expect(net.fetchPublicBinary).toHaveBeenCalledTimes(1);+ expect(net.fetchPublicBinary.mock.calls[0][0]).toBe('https://i.pinimg.com/736x/b.jpg');+ expect(writeFile).toHaveBeenCalledTimes(1);++ const [, imported] = store.appendPinterestItems.mock.calls[0];+ expect(imported).toHaveLength(1);+ expect(imported[0]).toMatchObject({ source: 'https://www.pinterest.com/pin/2/', caption: 'two' });+ expect(imported[0].imageUrl).toMatch(/^\/data\/images\/pinterest-[0-9a-f]{16}\.jpg$/);+ expect(result).toMatchObject({ added: 1, feedCount: 2 });+ expect(emitRecordUpdated).toHaveBeenCalledWith('moodBoard', 'mb-1');+ });++ it('skips a pin whose download returns a non-image body', async () => {+ store.getBoard.mockResolvedValue({ id: 'mb-1', items: [], pinterest: { feedUrl: 'https://www.pinterest.com/j/b.rss' } });+ net.fetchPublicText.mockResolvedValue(feedXml(PIN1));+ net.fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from('<html>'), contentType: 'text/html' });+ store.appendPinterestItems.mockImplementation(async (_id, imported) => ({ board: { id: 'mb-1' }, added: imported.length }));++ const result = await syncPinterestBoard('mb-1');+ expect(writeFile).not.toHaveBeenCalled();+ expect(store.appendPinterestItems.mock.calls[0][1]).toEqual([]); // nothing imported+ expect(result.added).toBe(0);+ });+});