Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: import single Pinterest Pins and align mobile mood board tools

[._.]/ Adam Eivy950106a7b480
diff --git a/client/src/components/ui/TabPills.jsx b/client/src/components/ui/TabPills.jsx
index 5e45a1723f..dd1a1badbc 100644
--- a/client/src/components/ui/TabPills.jsx
+++ b/client/src/components/ui/TabPills.jsx
@@ -258,7 +258,7 @@ export default function TabPills({
disabled={t.disabled}
onClick={() => onChange(t.id)}
onKeyDown={!isFilter ? (event) => handleTabKeyDown(event, index) : undefined}
- className={`flex items-center ${iconRow ? 'max-sm:min-w-[44px] max-sm:min-h-[44px]' : ''} ${sz.gap} ${sz.padding} rounded ${sz.text} transition-colors whitespace-nowrap ${
+ className={`flex items-center ${stretch ? 'flex-1 min-w-0 justify-center' : 'shrink-0'} ${iconRow ? 'max-sm:justify-center max-sm:min-w-[44px] max-sm:min-h-[44px]' : ''} ${sz.gap} ${sz.padding} rounded ${sz.text} transition-colors whitespace-nowrap ${
active
? 'bg-port-accent/20 text-port-accent border border-port-accent/40'
: 'text-gray-300 hover:bg-port-bg border border-transparent'
@@ -267,7 +267,7 @@ export default function TabPills({
{running
? <Loader2 size={sz.icon} className="animate-spin shrink-0" />
: (Icon && <Icon size={sz.icon} aria-hidden="true" className="shrink-0" />)}
- {renderLabel(t.label)}
+ {renderLabel(t.label, stretch)}
{t.count != null && t.count > 0 && (
<span className={`text-[10px] ${active ? 'text-port-accent/70' : 'text-gray-500'}`}>
{t.count}
diff --git a/client/src/pages/MoodBoardDetail.browser.test.js b/client/src/pages/MoodBoardDetail.browser.test.js
index be1431dd4f..63d817542a 100644
--- a/client/src/pages/MoodBoardDetail.browser.test.js
+++ b/client/src/pages/MoodBoardDetail.browser.test.js
@@ -18,7 +18,7 @@ const savedVideo = { id: 'upload-video', filename: 'upload-video.mp4', thumbnail
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=', 'base64');
// Every request is contained by this fixture; no live API, catalog or provider.
-async function openBoard(fixture, viewport) {
+async function openBoard(fixture, viewport, containerWidth) {
const page = await fixture.browser.newPage({ viewport });
page.setDefaultTimeout(10000);
const boards = { a: { id: 'a', name: 'Example A', items: [] }, b: { id: 'b', name: 'Example B', items: [] } };
@@ -35,6 +35,12 @@ async function openBoard(fixture, viewport) {
if (state.hold) await state.hold;
return route.fulfill({ json: path === '/image-gen/upload' ? savedImage : savedVideo });
}
+ if (path === '/mood-boards/a/pinterest/import') {
+ const { url } = route.request().postDataJSON();
+ const item = { id: 'pinterest-pin', type: 'image', source: url, imageUrl: '/data/images/pinterest-pin.jpg' };
+ boards.a.items.push(item);
+ return route.fulfill({ json: { board: boards.a, added: 1, found: 1 } });
+ }
const match = path.match(/^\/mood-boards\/([ab])(?:\/(items))?$/);
if (!match) { state.errors.push(`Unexpected API: ${path}`); return route.abort(); }
const board = boards[match[1]];
@@ -46,7 +52,9 @@ async function openBoard(fixture, viewport) {
return route.fulfill({ json: item });
});
await page.goto(`${fixture.origin}board-test`);
- if (viewport.width < 896) await page.getByRole('navigation', { name: 'Board tools' }).getByRole('button', { name: 'Add', exact: true }).click();
+ if (containerWidth) await page.locator('main').evaluate((main, width) => { main.style.width = `${width}px`; }, containerWidth);
+ await page.getByLabel('Name', { exact: true }).waitFor();
+ if (viewport.width < 896 || containerWidth < 896) await page.getByRole('navigation', { name: 'Board tools' }).getByRole('button', { name: 'Add', exact: true }).click();
await page.getByLabel('Upload', { exact: true }).waitFor();
return { page, boards, state };
}
@@ -80,7 +88,13 @@ describe.skipIf(!chrome)('direct mood board upload in Chromium', () => {
import { createRoot } from 'react-dom/client';
import { MemoryRouter, Routes, Route, Link } from 'react-router';
import MoodBoardDetail from '/src/pages/MoodBoardDetail.jsx';
+ import { THEMES } from '/src/themes/portosThemes.js';
import '/src/index.css';
+ document.documentElement.dataset.portTheme = 'lumen-glass-day';
+ document.documentElement.dataset.portThemeFamily = 'glass';
+ for (const [name, value] of Object.entries({ ...THEMES['lumen-glass-day'].colors, ...THEMES['lumen-glass-day'].tokens })) {
+ document.documentElement.style.setProperty(name, value);
+ }
const h = React.createElement;
createRoot(document.getElementById('root')).render(
h(MemoryRouter, { initialEntries: ['/mood-boards/a'] },
@@ -102,6 +116,55 @@ describe.skipIf(!chrome)('direct mood board upload in Chromium', () => {
}, BROWSER_FIXTURE_STARTUP_MS);
afterAll(() => fixture?.close());
+ it.each([
+ { width: 320, height: 740 },
+ { width: 390, height: 844 },
+ { width: 1440, height: 900, containerWidth: 640 },
+ { width: 1440, height: 900 },
+ ])('keeps import controls and evenly centered tool tabs usable at $width px', async ({ containerWidth, ...viewport }) => {
+ const { page, boards, state } = await openBoard(fixture, viewport, containerWidth);
+ try {
+ await page.getByRole('tab', { name: 'Import', exact: true }).click();
+ await page.getByLabel('Pin or board URL', { exact: true }).waitFor();
+ const tabs = page.getByRole('tablist', { name: 'Board tool' });
+ const geometry = await tabs.evaluate(strip => {
+ const rect = strip.getBoundingClientRect();
+ return {
+ left: rect.left, right: rect.right, width: strip.clientWidth, scrollWidth: strip.scrollWidth,
+ tabs: [...strip.querySelectorAll('[role="tab"]')].map(tab => {
+ const box = tab.getBoundingClientRect();
+ const icon = tab.querySelector('svg').getBoundingClientRect();
+ return { left: box.left, right: box.right, width: box.width, height: box.height,
+ iconOffset: Math.abs((box.left + box.right) / 2 - (icon.left + icon.right) / 2) };
+ }),
+ };
+ });
+ expect(geometry.scrollWidth).toBeLessThanOrEqual(geometry.width + 1);
+ expect(Math.max(...geometry.tabs.map(tab => tab.width)) - Math.min(...geometry.tabs.map(tab => tab.width))).toBeLessThan(1);
+ for (const tab of geometry.tabs) {
+ expect(tab.left).toBeGreaterThanOrEqual(geometry.left);
+ expect(tab.right).toBeLessThanOrEqual(geometry.right);
+ if (viewport.width < 640) {
+ expect(tab.height).toBeGreaterThanOrEqual(44);
+ expect(tab.width).toBeGreaterThanOrEqual(44);
+ expect(tab.iconOffset).toBeLessThan(1);
+ }
+ }
+ for (const label of ['Pin or board URL', 'Post URL']) {
+ const field = page.getByLabel(label, { exact: true });
+ const bounds = await field.boundingBox();
+ expect(bounds.x).toBeGreaterThanOrEqual(0);
+ expect(bounds.x + bounds.width).toBeLessThanOrEqual(viewport.width);
+ }
+ const pinUrl = 'https://www.pinterest.com/pin/9999999999999999999/';
+ await page.getByLabel('Pin or board URL', { exact: true }).fill(pinUrl);
+ await page.getByRole('button', { name: 'Import pins', exact: true }).click();
+ await vi.waitFor(() => expect(boards.a.items).toHaveLength(1));
+ expect(boards.a.items[0].source).toBe(pinUrl);
+ expect(state.errors).toEqual([]);
+ } finally { await page.close(); }
+ });
+
it.each([{ width: 390, height: 844 }, { width: 1440, height: 900 }])('imports a mixed batch, rejects repeated actions and retries assignment at $width px', async viewport => {
const { page, boards, state } = await openBoard(fixture, viewport);
try {
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsx
index 551cdc43e5..b7acdd47a1 100644
--- a/client/src/pages/MoodBoardDetail.jsx
+++ b/client/src/pages/MoodBoardDetail.jsx
@@ -494,19 +494,19 @@ function MoodBoardEditor({ id }) {
};
const handleImportPinterest = async () => {
- if (!mountedRef.current) return;
- if (!pinUrl.trim()) { toast.error('Enter a Pinterest board URL'); return; }
+ if (!mountedRef.current || importingPinterest) return;
+ if (!pinUrl.trim()) { toast.error('Enter a Pinterest Pin or board URL'); return; }
setImportingPinterest(true);
const result = await importMoodBoardPinterest(id, pinUrl.trim(), { silent: true }).catch(() => null);
if (!mountedRef.current) return;
setImportingPinterest(false);
if (!result?.board) {
- toast.error('Could not import that board — check that Pinterest is signed in to the PortOS browser');
+ toast.error('Could not import that Pin or board — check the URL and sign in to Pinterest in the PortOS browser');
return;
}
setBoard(result.board);
toast.success(result.added > 0
- ? `Added ${result.added} of ${result.found} Pinterest pins`
+ ? `Added ${formatCount(result.added)} of ${formatCount(result.found)} Pinterest pin${result.found === 1 ? '' : 's'}`
: result.found > 0 ? 'No new Pinterest pins were added' : 'The Pinterest board has no pins');
};
@@ -555,39 +555,40 @@ function MoodBoardEditor({ id }) {
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) => (
+ const renderPinUrlForm = (buttonText) => (
<div>
- <label htmlFor="pinterest-url" className="block text-xs text-gray-400 mb-1">{label}</label>
- <div className="flex flex-wrap gap-2">
+ <label htmlFor="pinterest-url" className="block text-xs text-gray-400 mb-1">Pin or board URL</label>
+ <div className="space-y-2">
<input
id="pinterest-url"
- type="text"
+ type="url"
+ autoCapitalize="none"
+ autoCorrect="off"
value={pinUrl}
maxLength={2048}
- placeholder="https://www.pinterest.com/user/board/"
+ placeholder="https://www.pinterest.com/pin/1234567890/"
onChange={(e) => setPinUrl(e.target.value)}
- className="flex-[1_1_12rem] 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"
+ className="block w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm focus:border-port-accent outline-none"
/>
- <button
- type="button"
- onClick={handleLinkPinterest}
- disabled={linking || importingPinterest || !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>
- <button
- type="button"
- onClick={handleImportPinterest}
- disabled={importingPinterest || linking || syncing || !pinUrl.trim()}
- 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"
- >
- <Download className={`w-4 h-4 ${importingPinterest ? 'animate-pulse' : ''}`} aria-hidden="true" />
- {importingPinterest ? 'Importing…' : 'Import pins'}
- </button>
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={handleImportPinterest}
+ disabled={importingPinterest || linking || syncing || !pinUrl.trim()}
+ className="min-h-[44px] flex items-center justify-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"
+ >
+ <Download className={`w-4 h-4 shrink-0 ${importingPinterest ? 'animate-pulse' : ''}`} aria-hidden="true" />
+ {importingPinterest ? 'Importing…' : 'Import pins'}
+ </button>
+ <button
+ type="button"
+ onClick={handleLinkPinterest}
+ disabled={linking || importingPinterest || !pinUrl.trim() || (isLinked && !pinDirty)}
+ className="min-h-[44px] px-3 py-1.5 text-sm rounded bg-port-bg border border-port-border text-white hover:bg-port-border disabled:opacity-50 transition-colors"
+ >
+ {linking ? 'Linking…' : buttonText}
+ </button>
+ </div>
</div>
</div>
);
@@ -714,7 +715,7 @@ function MoodBoardEditor({ id }) {
<div className="bg-port-card border border-port-border rounded-md p-4">
<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>
+ <h2 className="text-sm font-medium text-white">Import from Pinterest</h2>
</div>
{linkedFeedUrl ? (
<div className="space-y-3">
@@ -765,13 +766,14 @@ function MoodBoardEditor({ id }) {
</button>
)}
</div>
- {renderPinUrlForm('Change board URL', 'Update')}
+ {renderPinUrlForm('Update board link')}
+ <p className="text-[11px] text-gray-500">Import a single Pin or a full board. Importing a Pin keeps your linked board unchanged.</p>
</div>
) : (
<div>
- {renderPinUrlForm('Board URL', 'Link')}
+ {renderPinUrlForm('Link board')}
<p className="text-[11px] text-gray-500 mt-2">
- Link a public board to sync its newest ~25 pins. “Import pins” reads the full board from your signed-in PortOS browser and saves the images here.
+ Paste a Pin, board or pin.it share link. “Import pins” saves the images from your signed-in PortOS browser. “Link board” connects a public board to sync its newest ~25 pins.
</p>
</div>
)}
@@ -785,21 +787,23 @@ function MoodBoardEditor({ id }) {
</div>
<div>
<label htmlFor="x-post-url" className="block text-xs text-gray-400 mb-1">Post URL</label>
- <div className="flex flex-wrap gap-2">
+ <div className="@container/post-import flex flex-wrap gap-2">
<input
id="x-post-url"
- type="text"
+ type="url"
+ autoCapitalize="none"
+ autoCorrect="off"
value={xPostUrl}
maxLength={2048}
placeholder="https://x.com/user/status/1234567890"
onChange={(e) => setXPostUrl(e.target.value)}
- className="flex-[1_1_12rem] 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"
+ className="w-full @sm/post-import:flex-1 min-w-0 bg-port-bg border border-port-border rounded px-2 py-2 text-white text-sm focus:border-port-accent outline-none"
/>
<button
type="button"
onClick={handleImportXPost}
disabled={importingXPost || !xPostUrl.trim()}
- className="px-3 py-1.5 text-sm rounded bg-port-success text-white hover:bg-port-success/80 disabled:opacity-50 transition-colors"
+ className="min-h-[44px] px-3 py-1.5 text-sm rounded bg-port-success text-white hover:bg-port-success/80 disabled:opacity-50 transition-colors"
>
{importingXPost ? 'Importing…' : 'Import'}
</button>
diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsx
index 2e2b2aca43..b72945cf89 100644
--- a/client/src/pages/MoodBoardDetail.test.jsx
+++ b/client/src/pages/MoodBoardDetail.test.jsx
@@ -300,8 +300,8 @@ describe('MoodBoardDetail stale-response guards', () => {
});
describe('MoodBoardDetail private Pinterest import', () => {
- it('imports a board directly through the signed-in PortOS browser action', async () => {
- const boardUrl = 'https://www.pinterest.com/example-user/example-board/';
+ it('imports a single Pin through the signed-in PortOS browser action', async () => {
+ const boardUrl = 'https://www.pinterest.com/pin/9999999999999999999/';
const importedBoard = {
id: 'a',
name: 'Board A',
@@ -319,10 +319,10 @@ describe('MoodBoardDetail private Pinterest import', () => {
await waitFor(() => expect(boardNameValue()).toBe('Board A'));
openTool('Import');
- fireEvent.change(screen.getByLabelText('Board URL'), { target: { value: boardUrl } });
+ fireEvent.change(screen.getByLabelText('Pin or board URL'), { target: { value: boardUrl } });
fireEvent.click(screen.getByRole('button', { name: 'Import pins' }));
- await waitFor(() => expect(mockToastSuccess).toHaveBeenCalledWith('Added 1 of 1 Pinterest pins'));
+ await waitFor(() => expect(mockToastSuccess).toHaveBeenCalledWith('Added 1 of 1 Pinterest pin'));
expect(mockImportMoodBoardPinterest).toHaveBeenCalledWith('a', boardUrl, { silent: true });
expect(screen.getByAltText('Example pin')).toHaveAttribute('src', '/data/images/pinterest-example.jpg');
});
@@ -666,7 +666,7 @@ describe('MoodBoardDetail layout', () => {
expect(tools).toContainElement(screen.getByRole('button', { name: 'Pin to board' }));
expect(screen.queryByRole('button', { name: 'Import pins' })).toBeNull();
openTool('Import');
- expect(screen.getByRole('heading', { name: 'Pinterest board' })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Import from Pinterest' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Import from an X post' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Pin to board' })).toBeNull();
expect(screen.getByTestId('generate-more-panel')).toBeInTheDocument();
@@ -719,7 +719,7 @@ describe('MoodBoardDetail phone tool sheet', () => {
const row = screen.getByRole('navigation', { name: 'Board tools' });
fireEvent.click(within(row).getByRole('button', { name: 'Import' }));
const sheet = screen.getByRole('dialog', { name: 'Board tools' });
- expect(sheet).toContainElement(screen.getByRole('heading', { name: 'Pinterest board' }));
+ expect(sheet).toContainElement(screen.getByRole('heading', { name: 'Import from Pinterest' }));
// Switching tools inside the sheet keeps it open on the same entry.
fireEvent.click(screen.getByRole('tab', { name: 'Add' }));
diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.js
index 8680f0501b..ebcb1271db 100644
--- a/client/src/services/apiMoodBoard.js
+++ b/client/src/services/apiMoodBoard.js
@@ -104,7 +104,7 @@ export const syncMoodBoardPinterest = (id, options) =>
...options,
});
-// One-shot import through the signed-in PortOS CDP browser. Resolves
+// One-shot Pin or board import through the signed-in PortOS CDP browser. Resolves
// `{ board, added, found, skipped }`; no credentials or recurring link stored.
export const importMoodBoardPinterest = (id, url, options) =>
request(`/mood-boards/${encodeURIComponent(id)}/pinterest/import`, {
diff --git a/server/services/moodBoard/pinterestUrl.js b/server/services/moodBoard/pinterestUrl.js
index e900fffbb4..becbd3d209 100644
--- a/server/services/moodBoard/pinterestUrl.js
+++ b/server/services/moodBoard/pinterestUrl.js
@@ -2,11 +2,11 @@ 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) {
+// Only share links need network I/O; board linking and one-shot imports share
+// the same bounded, SSRF-checked redirect policy.
+async function resolvePinterestUrl(input) {
const url = typeof input === 'string' && URL.canParse(input.trim()) ? new URL(input.trim()) : null;
- if (url?.hostname !== 'pin.it') return normalizePinterestFeedUrl(input);
+ if (url?.hostname !== 'pin.it') return 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' });
}
@@ -19,9 +19,25 @@ export async function resolvePinterestBoardUrl(input) {
&& (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', {
+ throw new ServerError('Could not resolve this Pinterest share link; try its full Pinterest URL', {
status: 400, code: 'INVALID_PINTEREST_URL',
});
}
- return normalizePinterestFeedUrl(resolved);
+ return resolved;
+}
+
+export async function resolvePinterestBoardUrl(input) {
+ return normalizePinterestFeedUrl(await resolvePinterestUrl(input));
+}
+
+export async function resolvePinterestImportUrl(input) {
+ const resolved = await resolvePinterestUrl(input);
+ const url = typeof resolved === 'string' && URL.canParse(resolved.trim()) ? new URL(resolved.trim()) : null;
+ if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.port
+ || !isPinterestHost(url.hostname)) {
+ throw new ServerError('Use a Pinterest Pin or board URL', { status: 400, code: 'INVALID_PINTEREST_URL' });
+ }
+ const pinId = url.pathname.match(/^\/pin\/(\d+)\/?$/)?.[1];
+ if (pinId) return { pinUrl: `https://www.pinterest.com/pin/${pinId}/` };
+ return normalizePinterestFeedUrl(url.href);
}
diff --git a/server/services/moodBoard/privatePinterest.js b/server/services/moodBoard/privatePinterest.js
index a56a50fbd1..8128e19d1b 100644
--- a/server/services/moodBoard/privatePinterest.js
+++ b/server/services/moodBoard/privatePinterest.js
@@ -1,5 +1,5 @@
/**
- * One-shot import for Pinterest boards that are visible only to the signed-in
+ * One-shot import for Pinterest Pins and boards visible to the signed-in
* PortOS browser profile. The page read is pinned through the browser service's
* CDP SSRF guard; only Pinterest pin permalinks and i.pinimg.com image URLs
* leave the page, and the images are re-hosted into the normal mood-board asset
@@ -10,13 +10,12 @@ import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, ensureDir } from '../../lib/fileUtils.js';
import { isBlockedIngestHost } from '../../lib/catalogValidation.js';
import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
-import { normalizePinterestFeedUrl } from '../../lib/pinterestFeed.js';
import { getHealthStatus, navigateToUrlPinned } from '../browserService.js';
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';
+import { resolvePinterestImportUrl } from './pinterestUrl.js';
const PINTEREST_PAGE_SETTLE_MS = 2500;
// The pinned DOM scan can take up to roughly 58 seconds: a 32 × 250 ms
@@ -24,6 +23,38 @@ const PINTEREST_PAGE_SETTLE_MS = 2500;
const PINTEREST_PAGE_READ_TIMEOUT_MS = 70000;
const DOWNLOAD_CONCURRENCY = 3;
+// Read only the requested Pin's closeup or page metadata, never the related-pin
+// grid. The server independently validates the landed URL and every image URL.
+function pinSnapshotExpression(pinUrl) {
+ return `(() => new Promise(async (resolve) => {
+ const source = ${JSON.stringify(pinUrl)};
+ const read = () => {
+ const loginRequired = /^\\/(?:login|session\\/login)(?:\\/|$)/i.test(location.pathname)
+ || Boolean(document.querySelector('input[type="password"]'));
+ const closeup = document.querySelector('[data-test-id="pin-closeup-image"]');
+ const img = closeup?.matches('img') ? closeup : closeup?.querySelector('img');
+ const candidates = [
+ ...(img?.getAttribute('srcset') || '').split(',').map((entry) => entry.trim().split(/\\s+/)[0]).reverse(),
+ img?.currentSrc, img?.src,
+ document.querySelector('meta[property="og:image"]')?.content,
+ ];
+ const imageUrl = candidates.find((raw) => {
+ try {
+ const url = new URL(raw);
+ return url.protocol === 'https:' && url.hostname === 'i.pinimg.com' && !url.username && !url.password && !url.port;
+ } catch { return false; }
+ });
+ return { loginRequired, expectedCount: 1, pins: imageUrl ? [{ source, imageUrl }] : [] };
+ };
+ let snapshot = read();
+ for (let i = 0; i < 32 && !snapshot.loginRequired && !snapshot.pins.length; i++) {
+ await new Promise((done) => setTimeout(done, 250));
+ snapshot = read();
+ }
+ resolve(snapshot);
+ }))()`;
+}
+
// Runs only on the user-triggered import path. The page is opened in a fresh
// tab in the PortOS browser's existing profile, and the bounded scroll loop
// collects only the board's pin grid (never recommendation carousels).
@@ -131,15 +162,22 @@ function sameBoardPath(left, right) {
return leftPath === rightPath;
}
+function isPinterestImageUrl(raw) {
+ if (typeof raw !== 'string' || !URL.canParse(raw)) return false;
+ const image = new URL(raw);
+ return image.protocol === 'https:' && image.hostname === 'i.pinimg.com' && !image.username && !image.password && !image.port;
+}
+
/**
- * Import the visible pins from a private Pinterest board using the signed-in
+ * Import a single Pin or the visible pins from a Pinterest board using the signed-in
* PortOS CDP browser. Images download outside the mood-board row lock, then the
* store performs a locked, source-deduplicated append.
*
* @returns {Promise<{ board: object, added: number, found: number, skipped: number }>}
*/
export async function importPrivatePinterestBoard(boardId, { url }) {
- const { boardUrl } = await resolvePinterestBoardUrl(url);
+ const { boardUrl, pinUrl } = await resolvePinterestImportUrl(url);
+ const targetUrl = pinUrl || boardUrl;
const board = await store.getBoard(boardId);
if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
@@ -148,13 +186,13 @@ export async function importPrivatePinterestBoard(boardId, { url }) {
throw new ServerError('The PortOS browser is not running', { status: 503, code: 'BROWSER_UNAVAILABLE' });
}
- const page = await navigateToUrlPinned(boardUrl, {
+ const page = await navigateToUrlPinned(targetUrl, {
verifyRemoteIp: (ip) => !isBlockedIngestHost(ip),
settleMs: PINTEREST_PAGE_SETTLE_MS,
- evaluateExpression: PINTEREST_BOARD_SNAPSHOT_EXPRESSION,
+ evaluateExpression: pinUrl ? pinSnapshotExpression(pinUrl) : PINTEREST_BOARD_SNAPSHOT_EXPRESSION,
evaluateTimeoutMs: PINTEREST_PAGE_READ_TIMEOUT_MS,
}).catch(() => {
- throw new ServerError('Could not read the Pinterest board in the PortOS browser', {
+ throw new ServerError('Could not read Pinterest in the PortOS browser', {
status: 502,
code: 'PINTEREST_BROWSER_READ_FAILED',
});
@@ -170,22 +208,27 @@ export async function importPrivatePinterestBoard(boardId, { url }) {
code: 'PINTEREST_LOGIN_REQUIRED',
});
}
- if (!snapshot.boardTitle) {
+ if (!pinUrl && !snapshot.boardTitle) {
throw new ServerError('Pinterest did not show this board in the PortOS browser', {
status: 403,
code: 'PINTEREST_BOARD_UNAVAILABLE',
});
}
- const landedBoardUrl = normalizePinterestFeedUrl(page.url).boardUrl;
- if (!sameBoardPath(landedBoardUrl, boardUrl)) {
- throw new ServerError('Pinterest opened a different board than the one requested', {
+ const landed = await resolvePinterestImportUrl(page.url);
+ if (pinUrl ? landed.pinUrl !== pinUrl : !landed.boardUrl || !sameBoardPath(landed.boardUrl, boardUrl)) {
+ throw new ServerError('Pinterest opened a different Pin or board than the one requested', {
status: 502,
code: 'PINTEREST_BOARD_REDIRECTED',
});
}
const pins = Array.isArray(snapshot.pins) ? snapshot.pins : [];
+ if (pinUrl && (pins.length !== 1 || pins[0]?.source !== pinUrl || !isPinterestImageUrl(pins[0]?.imageUrl))) {
+ throw new ServerError('Pinterest did not show an image for this Pin', {
+ status: 502, code: 'PINTEREST_PIN_UNAVAILABLE',
+ });
+ }
const expectedCount = Number.isInteger(snapshot.expectedCount) && snapshot.expectedCount >= 0
? snapshot.expectedCount
: null;
@@ -207,7 +250,9 @@ export async function importPrivatePinterestBoard(boardId, { url }) {
const items = Array.isArray(board.items) ? board.items : [];
const seen = new Set(items.map((item) => item?.source).filter(Boolean));
const capacity = Math.max(0, MAX_ITEMS_PER_BOARD - items.length);
- const candidates = pins.filter((pin) => pin?.source && pin?.imageUrl && !seen.has(pin.source)).slice(0, capacity);
+ const candidates = pins.filter((pin) => /^https:\/\/www\.pinterest\.com\/pin\/\d+\/$/.test(pin?.source)
+ && isPinterestImageUrl(pin?.imageUrl) && !seen.has(pin.source)
+ && (!pin.imageUrlOriginal || isPinterestImageUrl(pin.imageUrlOriginal))).slice(0, capacity);
if (!candidates.length) return { board, added: 0, found, skipped: found };
await ensureDir(PATHS.images);
diff --git a/server/services/moodBoard/privatePinterest.test.js b/server/services/moodBoard/privatePinterest.test.js
index 258554ead7..15accb237b 100644
--- a/server/services/moodBoard/privatePinterest.test.js
+++ b/server/services/moodBoard/privatePinterest.test.js
@@ -75,8 +75,8 @@ describe('importPrivatePinterestBoard', () => {
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) => {
+ it.each(['https://www.pinterest.com/example-user/', 'https://example.com/example/board/', 'https://www.pinterest.com/pin/invalid/'])
+ ('rejects an unsupported 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' });
@@ -84,6 +84,52 @@ describe('importPrivatePinterestBoard', () => {
expect(store.appendImportedItems).not.toHaveBeenCalled();
});
+ it.each([
+ 'https://www.pinterest.com/pin/9999999999999999999/?tracking=example',
+ 'https://pin.it/example-pin',
+ 'http://pinterest.co.uk/pin/9999999999999999999/',
+ ])('imports only the requested single Pin without changing the linked board: %s', async (url) => {
+ resolvePublicUrl.mockResolvedValue(firstPin.source);
+ store.getBoard.mockResolvedValue({ id: 'mb-example', items: [], pinterest: { boardUrl: BOARD_URL } });
+ browser.getHealthStatus.mockResolvedValue({ connected: true });
+ browser.navigateToUrlPinned.mockResolvedValue({ url: firstPin.source, evalResult: { expectedCount: 1, pins: [firstPin] } });
+
+ expect(await importPrivatePinterestBoard('mb-example', { url })).toMatchObject({ added: 1, found: 1, skipped: 0 });
+ expect(browser.navigateToUrlPinned).toHaveBeenCalledWith(firstPin.source, expect.objectContaining({ evaluateExpression: expect.any(String) }));
+ expect(store.appendImportedItems).toHaveBeenCalledWith('mb-example', [{ imageUrl: '/data/images/pinterest-example.jpg', source: firstPin.source }]);
+ });
+
+ it('deduplicates a single Pin before downloading its image', async () => {
+ store.getBoard.mockResolvedValue({ id: 'mb-example', items: [{ source: firstPin.source }] });
+ browser.getHealthStatus.mockResolvedValue({ connected: true });
+ browser.navigateToUrlPinned.mockResolvedValue({ url: firstPin.source, evalResult: { expectedCount: 1, pins: [firstPin] } });
+
+ expect(await importPrivatePinterestBoard('mb-example', { url: firstPin.source })).toMatchObject({ added: 0, found: 1, skipped: 1 });
+ expect(downloadPinImage).not.toHaveBeenCalled();
+ expect(store.appendImportedItems).not.toHaveBeenCalled();
+ });
+
+ it('refuses a Pin page redirected to a different Pin before downloading', async () => {
+ browser.getHealthStatus.mockResolvedValue({ connected: true });
+ browser.navigateToUrlPinned.mockResolvedValue({ url: secondPin.source, evalResult: { expectedCount: 1, pins: [firstPin] } });
+ await expect(importPrivatePinterestBoard('mb-example', { url: firstPin.source }))
+ .rejects.toMatchObject({ code: 'PINTEREST_BOARD_REDIRECTED' });
+ expect(downloadPinImage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [],
+ [secondPin],
+ [{ ...firstPin, imageUrl: 'https://example.com/unrelated.jpg' }],
+ ])('refuses missing or unrelated single-Pin media: %j', async (pins) => {
+ browser.getHealthStatus.mockResolvedValue({ connected: true });
+ browser.navigateToUrlPinned.mockResolvedValue({ url: firstPin.source, evalResult: { expectedCount: 1, pins } });
+ await expect(importPrivatePinterestBoard('mb-example', { url: firstPin.source }))
+ .rejects.toMatchObject({ code: 'PINTEREST_PIN_UNAVAILABLE' });
+ expect(downloadPinImage).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',