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 Spotify history through managed browser

[._.]/ Adam Eivy478527e70f24
diff --git a/client/src/components/digital-twin/tabs/ImportTab.jsx b/client/src/components/digital-twin/tabs/ImportTab.jsx
index 8bf2822389..d30aab114a 100644
--- a/client/src/components/digital-twin/tabs/ImportTab.jsx
+++ b/client/src/components/digital-twin/tabs/ImportTab.jsx
@@ -5,6 +5,8 @@ import {
Music,
Film,
Calendar,
+ Globe2,
+ Loader2,
RefreshCw,
Check,
FileText,
@@ -41,6 +43,9 @@ export default function ImportTab() {
const [analyzing, setAnalyzing] = useState(false);
const [analysisResult, setAnalysisResult] = useState(null);
const [saving, setSaving] = useState(false);
+ const [spotifyBrowserState, setSpotifyBrowserState] = useState(null);
+ const [openingSpotifyBrowser, setOpeningSpotifyBrowser] = useState(false);
+ const [importingSpotifyBrowser, setImportingSpotifyBrowser] = useState(false);
useEffect(() => {
loadSources();
@@ -100,6 +105,47 @@ export default function ImportTab() {
setAnalyzing(false);
};
+ const handleOpenSpotifyBrowser = async () => {
+ setOpeningSpotifyBrowser(true);
+ const result = await api.openDigitalTwinSpotifyBrowser({ silent: true })
+ .catch(e => ({ status: 'error', error: e.message }));
+ setSpotifyBrowserState(result);
+ if (result.status === 'error' || result.status === 'unavailable') {
+ toast.error(result.error || result.message || 'Could not open Spotify in the managed browser');
+ } else if (result.status === 'auth-required') {
+ toast.warning(result.message);
+ } else if (result.status === 'ready') {
+ toast.success('Spotify privacy page is ready in the PortOS browser');
+ }
+ setOpeningSpotifyBrowser(false);
+ };
+
+ const handleImportSpotifyBrowser = async () => {
+ if (!selectedProvider) {
+ toast.error('Choose an analysis provider first');
+ return;
+ }
+
+ setImportingSpotifyBrowser(true);
+ const result = await api.importDigitalTwinSpotifyBrowser(
+ selectedProvider.providerId,
+ selectedProvider.model,
+ { silent: true },
+ ).catch(e => ({ status: 'error', error: e.message }));
+ setSpotifyBrowserState(result);
+ if (result.status === 'complete') {
+ setAnalysisResult(result);
+ toast.success('Spotify history imported and analyzed');
+ } else if (result.status === 'pending') {
+ toast.warning(result.message);
+ } else if (result.status === 'auth-required') {
+ toast.warning(result.message);
+ } else {
+ toast.error(result.error || result.message || 'Spotify import failed');
+ }
+ setImportingSpotifyBrowser(false);
+ };
+
const handleSaveDocument = async (suggestedDoc) => {
setSaving(true);
@@ -127,6 +173,7 @@ export default function ImportTab() {
setSelectedSource(null);
setFileContent('');
setAnalysisResult(null);
+ setSpotifyBrowserState(null);
};
return (
@@ -192,7 +239,9 @@ export default function ImportTab() {
})()}
<div>
<h3 className="font-semibold text-white">{selectedSource.name}</h3>
- <span className="text-xs text-gray-500">{selectedSource.format} file</span>
+ <span className="text-xs text-gray-500">
+ {selectedSource.id === 'spotify' ? 'Managed browser or JSON file' : `${selectedSource.format} file`}
+ </span>
</div>
</div>
<button
@@ -203,16 +252,64 @@ export default function ImportTab() {
</button>
</div>
- {/* Instructions */}
- <div className="mb-6 p-4 bg-port-bg rounded-lg border border-port-border">
- <h4 className="text-sm font-medium text-white mb-2">How to export your data</h4>
- <p className="text-sm text-gray-400">{selectedSource.instructions}</p>
- </div>
+ {/* Spotify's privacy export can be linked through the persistent CDP browser. */}
+ {selectedSource.id === 'spotify' && (
+ <div className="mb-6 p-4 bg-port-bg rounded-lg border border-port-border">
+ <div className="flex items-start gap-3">
+ <Globe2 className="w-5 h-5 text-port-accent shrink-0 mt-0.5" />
+ <div className="flex-1">
+ <h4 className="text-sm font-medium text-white mb-2">Import from the PortOS browser</h4>
+ <p className="text-sm text-gray-400 mb-4">
+ PortOS opens Spotify&apos;s privacy page in its managed browser, where you can sign in once.
+ It never receives your Spotify password or API credentials. The downloaded archive is processed
+ locally and removed after analysis.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={handleOpenSpotifyBrowser}
+ disabled={openingSpotifyBrowser}
+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-40"
+ >
+ {openingSpotifyBrowser ? <Loader2 className="w-4 h-4 animate-spin" /> : <Globe2 className="w-4 h-4" />}
+ {openingSpotifyBrowser ? 'Opening Spotify...' : 'Open Spotify in PortOS'}
+ </button>
+ <button
+ type="button"
+ onClick={handleImportSpotifyBrowser}
+ disabled={importingSpotifyBrowser || !selectedProvider || spotifyBrowserState?.status === 'auth-required'}
+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40"
+ title={!selectedProvider ? 'Choose an analysis provider first' : undefined}
+ >
+ {importingSpotifyBrowser ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
+ {importingSpotifyBrowser ? 'Checking Spotify...' : 'Request and import history'}
+ </button>
+ </div>
+ {spotifyBrowserState && (
+ <div className="mt-4 text-sm text-gray-400" role="status">
+ <span className={spotifyBrowserState.status === 'ready' ? 'text-port-success' : 'text-port-warning'}>
+ {spotifyBrowserState.status === 'ready' ? '● Ready' : `● ${spotifyBrowserState.status}`}
+ </span>{' '}
+ {spotifyBrowserState.message}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Instructions for the manual sources, plus Spotify's explicit fallback. */}
+ {selectedSource.id !== 'spotify' && (
+ <div className="mb-6 p-4 bg-port-bg rounded-lg border border-port-border">
+ <h4 className="text-sm font-medium text-white mb-2">How to export your data</h4>
+ <p className="text-sm text-gray-400">{selectedSource.instructions}</p>
+ </div>
+ )}
{/* File Upload */}
- <div className="mb-6">
+ <div className={`mb-6 ${selectedSource.id === 'spotify' ? 'p-4 bg-port-bg rounded-lg border border-port-border' : ''}`}>
<span className="block text-sm font-medium text-gray-400 mb-2">
- Upload {selectedSource.format} File
+ {selectedSource.id === 'spotify' ? 'Manual fallback — upload a Spotify JSON file' : `Upload ${selectedSource.format} File`}
</span>
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
<FilePickerButton
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index 537d435ecc..7e3c94585b 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -197,6 +197,15 @@ export const getDigitalTwinGaps = () => request('/digital-twin/gaps');
// Digital Twin External Import
export const getDigitalTwinImportSources = () => request('/digital-twin/import/sources');
+export const openDigitalTwinSpotifyBrowser = (options = {}) => request('/digital-twin/import/spotify/browser/open', {
+ method: 'POST',
+ ...options
+});
+export const importDigitalTwinSpotifyBrowser = (providerId, model, options = {}) => request('/digital-twin/import/spotify/browser/import', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model }),
+ ...options
+});
export const analyzeDigitalTwinImport = (source, data, providerId, model, options = {}) => request('/digital-twin/import/analyze', {
method: 'POST',
body: JSON.stringify({ source, data, providerId, model }),
diff --git a/client/src/services/apiDigitalTwin.test.js b/client/src/services/apiDigitalTwin.test.js
index 738b14e40d..73857d57ae 100644
--- a/client/src/services/apiDigitalTwin.test.js
+++ b/client/src/services/apiDigitalTwin.test.js
@@ -6,11 +6,13 @@ vi.mock('./apiCore.js', () => ({
let request;
let detectDigitalTwinContradictions;
+let openDigitalTwinSpotifyBrowser;
+let importDigitalTwinSpotifyBrowser;
beforeEach(async () => {
vi.resetModules();
({ request } = await import('./apiCore.js'));
- ({ detectDigitalTwinContradictions } = await import('./apiDigitalTwin.js'));
+ ({ detectDigitalTwinContradictions, openDigitalTwinSpotifyBrowser, importDigitalTwinSpotifyBrowser } = await import('./apiDigitalTwin.js'));
request.mockReset();
});
@@ -40,3 +42,27 @@ describe('detectDigitalTwinContradictions', () => {
expect(options.method).toBe('POST');
});
});
+
+describe('interactive Spotify import wrappers', () => {
+ it('opens the managed browser without accepting a caller URL', async () => {
+ request.mockResolvedValue({ status: 'ready' });
+
+ await openDigitalTwinSpotifyBrowser({ silent: true });
+
+ const [path, options] = request.mock.calls[0];
+ expect(path).toBe('/digital-twin/import/spotify/browser/open');
+ expect(options).toMatchObject({ method: 'POST', silent: true });
+ expect(options.body).toBeUndefined();
+ });
+
+ it('sends only the selected provider and model for browser analysis', async () => {
+ request.mockResolvedValue({ status: 'complete' });
+
+ await importDigitalTwinSpotifyBrowser('local', 'example-model', { silent: true });
+
+ const [path, options] = request.mock.calls[0];
+ expect(path).toBe('/digital-twin/import/spotify/browser/import');
+ expect(options).toMatchObject({ method: 'POST', silent: true });
+ expect(JSON.parse(options.body)).toEqual({ providerId: 'local', model: 'example-model' });
+ });
+});
diff --git a/docs/API.md b/docs/API.md
index e8f88ba749..c67d2170c0 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -345,6 +345,8 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| GET | `/digital-twin/gaps` | Get enrichment recommendations |
| GET | `/digital-twin/completeness` | Get completeness validation |
| POST | `/digital-twin/contradictions` | Detect contradictions |
+| POST | `/digital-twin/import/spotify/browser/open` | Open Spotify privacy page in the managed browser |
+| POST | `/digital-twin/import/spotify/browser/import` | Request/read the Spotify browser export and analyze it |
| POST | `/digital-twin/import/analyze` | Analyze external data import |
| POST | `/digital-twin/import/save` | Save analyzed import as document |
diff --git a/docs/features/digital-twin.md b/docs/features/digital-twin.md
index e78d5db862..c85f4940ad 100644
--- a/docs/features/digital-twin.md
+++ b/docs/features/digital-twin.md
@@ -52,7 +52,18 @@ Gap recommendations identify the lowest-confidence aspects, generate specific qu
- **Letterboxd** film export
- **iCal** calendar files — event categorization and recurring-pattern analysis (routines)
-Routes: `GET /import/sources`, `POST /import/analyze`, `POST /import/save`.
+Spotify can also be imported interactively from the Digital Twin Import tab.
+PortOS opens Spotify's fixed Account Privacy page in the persistent managed CDP
+browser, preserves the browser's own login session, and requests the extended
+history package when the page exposes the matching controls. A completed ZIP or
+JSON download is parsed locally, sent through the existing analysis path, and
+removed from the browser download cache afterward. The flow never accepts an
+arbitrary destination or Spotify password/API credential; if Spotify requires a
+login, confirmation, or time to prepare the package, the UI reports that state
+and can be retried. Manual JSON upload remains available as a fallback.
+
+Routes: `GET /import/sources`, `POST /import/analyze`, `POST /import/save`,
+`POST /import/spotify/browser/open`, and `POST /import/spotify/browser/import`.
## Transcript & Image Analysis
diff --git a/server/routes/digital-twin/import.js b/server/routes/digital-twin/import.js
index f2b3e891fa..87cb5594c5 100644
--- a/server/routes/digital-twin/import.js
+++ b/server/routes/digital-twin/import.js
@@ -9,6 +9,7 @@ import * as digitalTwinService from '../../services/digital-twin.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
import { validateRequest } from '../../lib/validation.js';
import { importDataInputSchema } from '../../lib/digitalTwinValidation.js';
+import * as spotifyBrowserImport from '../../services/spotifyBrowserImport.js';
const importSaveSchema = z.object({
source: z.string().min(1),
@@ -31,6 +32,32 @@ router.get('/import/sources', asyncHandler(async (req, res) => {
res.json({ sources });
}));
+/**
+ * POST /api/digital-twin/import/spotify/browser/open
+ * Open Spotify's fixed privacy page in the PortOS managed browser.
+ *
+ * The browser keeps its own session, so this endpoint never accepts a URL or
+ * Spotify credential. A signed-out browser returns an auth-required state for
+ * the UI to render rather than turning the login page into an API error.
+ */
+router.post('/import/spotify/browser/open', asyncHandler(async (req, res) => {
+ res.json(await spotifyBrowserImport.openSpotifyBrowser());
+}));
+
+const spotifyBrowserImportSchema = z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1),
+});
+
+/**
+ * POST /api/digital-twin/import/spotify/browser/import
+ * Request/read the Spotify browser export and analyze it without a file upload.
+ */
+router.post('/import/spotify/browser/import', asyncHandler(async (req, res) => {
+ const { providerId, model } = validateRequest(spotifyBrowserImportSchema, req.body);
+ res.json(await spotifyBrowserImport.importSpotifyFromBrowser(providerId, model));
+}));
+
/**
* POST /api/digital-twin/import/analyze
* Analyze imported external data
diff --git a/server/routes/digital-twin/index.test.js b/server/routes/digital-twin/index.test.js
index 6793006f9b..d8041e1398 100644
--- a/server/routes/digital-twin/index.test.js
+++ b/server/routes/digital-twin/index.test.js
@@ -35,9 +35,13 @@ vi.mock('../../services/feedbackLoop.js', () => fnMap([
vi.mock('../../services/timeCapsule.js', () => fnMap([
'createSnapshot', 'listSnapshots', 'getSnapshot', 'deleteSnapshot', 'compareSnapshots',
]));
+vi.mock('../../services/spotifyBrowserImport.js', () => fnMap([
+ 'openSpotifyBrowser', 'importSpotifyFromBrowser',
+]));
import digitalTwinRoutes from './index.js';
import * as digitalTwinService from '../../services/digital-twin.js';
+import * as spotifyBrowserImport from '../../services/spotifyBrowserImport.js';
const VALID_UUID = '11111111-1111-1111-1111-111111111111';
@@ -197,6 +201,33 @@ describe('Digital Twin Routes', () => {
});
});
+ describe('interactive Spotify import', () => {
+ it('opens the managed Spotify privacy page and returns its browser state', async () => {
+ spotifyBrowserImport.openSpotifyBrowser.mockResolvedValue({ status: 'auth-required', pageId: 'tab-1' });
+ const res = await request(app).post('/api/digital-twin/import/spotify/browser/open').send({});
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ status: 'auth-required', pageId: 'tab-1' });
+ });
+
+ it('validates the provider before running the browser import', async () => {
+ const res = await request(app)
+ .post('/api/digital-twin/import/spotify/browser/import')
+ .send({ providerId: 'local' });
+ expect(res.status).toBe(400);
+ expect(spotifyBrowserImport.importSpotifyFromBrowser).not.toHaveBeenCalled();
+ });
+
+ it('runs the browser import with the selected provider and model', async () => {
+ spotifyBrowserImport.importSpotifyFromBrowser.mockResolvedValue({ status: 'complete', itemCount: 4 });
+ const res = await request(app)
+ .post('/api/digital-twin/import/spotify/browser/import')
+ .send({ providerId: 'local', model: 'example-model' });
+ expect(res.status).toBe(200);
+ expect(res.body.status).toBe('complete');
+ expect(spotifyBrowserImport.importSpotifyFromBrowser).toHaveBeenCalledWith('local', 'example-model');
+ });
+ });
+
describe('personas', () => {
it('GET /personas lists personas', async () => {
digitalTwinService.getPersonas.mockResolvedValue([{ id: VALID_UUID, name: 'Formal' }]);
diff --git a/server/services/digital-twin-import.js b/server/services/digital-twin-import.js
index 5279a3f4c6..86f20b9985 100644
--- a/server/services/digital-twin-import.js
+++ b/server/services/digital-twin-import.js
@@ -464,7 +464,8 @@ export function getImportSources() {
name: 'Spotify',
description: 'Import listening history to analyze music preferences and emotional patterns',
format: 'JSON',
- instructions: 'Go to Account > Privacy Settings > Download your data. Request "Extended streaming history". Extract the JSON files.'
+ interactive: true,
+ instructions: 'Use the PortOS managed browser to sign in and request Extended Streaming History, or upload the JSON export manually.'
},
{
id: 'letterboxd',
diff --git a/server/services/spotifyBrowserImport.js b/server/services/spotifyBrowserImport.js
new file mode 100644
index 0000000000..a1512ce6cf
--- /dev/null
+++ b/server/services/spotifyBrowserImport.js
@@ -0,0 +1,301 @@
+/**
+ * Spotify extended-history import through the PortOS-managed browser.
+ *
+ * Spotify's privacy export is an authenticated, user-facing flow rather than
+ * a public API. Keep the integration deliberately narrow: the destination is
+ * fixed to Spotify's privacy page, the CDP page is opened in the user's
+ * persistent browser profile, and only the page's fixed controls are clicked.
+ * No Spotify password, API credential, or arbitrary URL crosses this service.
+ */
+
+import { isPrivateAddress } from '../lib/safeUrlFetch.js';
+import { sleep } from '../lib/fileUtils.js';
+import { analyzeImportedData } from './digital-twin-import.js';
+import { readSpotifyRecords } from './spotifyImport.js';
+import {
+ closeCdpPage,
+ deleteDownload,
+ evaluateOnPage,
+ getDownloads,
+ listCdpPages,
+ navigateToUrlPinned,
+ resolveDownload,
+} from './browserService.js';
+
+export const SPOTIFY_PRIVACY_URL = 'https://www.spotify.com/account/privacy/';
+
+const SPOTIFY_WEB_ORIGIN = 'https://www.spotify.com';
+const SPOTIFY_ACCOUNTS_ORIGIN = 'https://accounts.spotify.com';
+const PAGE_SETTLE_MS = 1200;
+const DOWNLOAD_WAIT_MS = 10000;
+const DOWNLOAD_POLL_MS = 500;
+
+const SPOTIFY_PAGE_STATE_EXPRESSION = `(() => {
+ const normalize = (value) => String(value || '').replace(/\\s+/g, ' ').trim().toLowerCase();
+ const controls = [...document.querySelectorAll('button, a, [role="button"], label, input[type="checkbox"], input[type="radio"], [role="checkbox"], [role="radio"]')];
+ const labels = controls.map((node) => normalize(node.innerText || node.textContent || node.getAttribute('aria-label')));
+ const bodyText = normalize(document.body?.innerText);
+ const hasExtendedHistory = labels.some((label) => label.includes('extended streaming history'));
+ const hasDownloadAction = labels.some((label) => (
+ label.includes('request data')
+ || label.includes('request your data')
+ || label.includes('request my data')
+ || label.includes('request extended streaming history')
+ || label === 'request'
+ || label.includes('download your data')
+ || label.includes('download extended streaming history')
+ ));
+ return {
+ privacyPage: /\\/account\\/privacy(?:\\/|$)/i.test(location.pathname),
+ loginForm: Boolean(document.querySelector('input[type="password"], form[action*="login"]')),
+ hasExtendedHistory,
+ hasDownloadAction,
+ requestPending: /request(?:ed|ing)|being prepared|we(?:'|’)ll email you/.test(bodyText),
+ };
+})()`;
+
+// This expression is intentionally closed over no caller data. It only clicks
+// the named Extended Streaming History option and one of the known data-request
+// controls on Spotify's privacy page. The action is still user-triggered from
+// the Digital Twin UI, so a provider call never starts in the background.
+const SPOTIFY_REQUEST_DOWNLOAD_EXPRESSION = `(() => {
+ const normalize = (value) => String(value || '').replace(/\\s+/g, ' ').trim().toLowerCase();
+ const controls = () => [...document.querySelectorAll('button, a, [role="button"], label, input[type="checkbox"], input[type="radio"], [role="checkbox"], [role="radio"]')];
+ const bodyText = normalize(document.body?.innerText);
+ if (/request(?:ed|ing)|being prepared|we(?:'|’)ll email you/.test(bodyText)) {
+ return { clicked: false, requestPending: true, extendedSelected: false };
+ }
+ const extended = controls().find((node) => normalize(node.innerText || node.textContent || node.getAttribute('aria-label')).includes('extended streaming history'));
+ if (!extended) return { clicked: false, optionMissing: true, extendedSelected: false };
+ let selected = false;
+ if (extended) {
+ const input = extended.matches('input')
+ ? extended
+ : (extended.querySelector('input[type="checkbox"], input[type="radio"]')
+ || (extended.htmlFor ? document.getElementById(extended.htmlFor) : null));
+ if (input) {
+ if (!input.checked) input.click();
+ selected = Boolean(input.checked);
+ } else if (extended.getAttribute('aria-checked') !== 'true') {
+ extended.click();
+ selected = true;
+ } else {
+ selected = true;
+ }
+ }
+ return new Promise((resolve) => setTimeout(() => {
+ const action = controls().find((node) => {
+ const label = normalize(node.innerText || node.textContent || node.getAttribute('aria-label'));
+ return label.includes('request data')
+ || label.includes('request your data')
+ || label.includes('request my data')
+ || label === 'request'
+ || label.includes('request extended streaming history')
+ || label.includes('download your data')
+ || label.includes('download extended streaming history');
+ });
+ if (!action) return resolve({ clicked: false, extendedSelected: selected });
+ const actionLabel = normalize(action.innerText || action.textContent || action.getAttribute('aria-label'));
+ if (!selected && !actionLabel.includes('extended streaming history')) {
+ return resolve({ clicked: false, extendedSelected: selected });
+ }
+ action.click();
+ resolve({ clicked: true, extendedSelected: selected });
+ }, 250));
+})()`;
+
+const isSpotifyWebPage = (page) => typeof page?.url === 'string'
+ && page.url.startsWith(`${SPOTIFY_WEB_ORIGIN}/`);
+
+export const isSpotifyLoginPage = (page) => typeof page?.url === 'string'
+ && page.url.startsWith(`${SPOTIFY_ACCOUNTS_ORIGIN}/`);
+
+export const isSpotifyPrivacyPage = (page) => isSpotifyWebPage(page)
+ && /\/account\/privacy(?:\/|$)/i.test(page.url);
+
+const isAllowedSpotifyPage = (page) => isSpotifyWebPage(page) || isSpotifyLoginPage(page);
+
+export const isSpotifyDownloadName = (name) => typeof name === 'string'
+ && /\.(?:zip|json)$/i.test(name)
+ && /(spotify|streaming[ _-]?history|my[ _-]?spotify)/i.test(name);
+
+async function findSpotifyPage() {
+ const pages = await listCdpPages();
+ return pages.find(isSpotifyPrivacyPage) || pages.find(isSpotifyLoginPage) || null;
+}
+
+async function ensureSpotifyPrivacyPage() {
+ const existing = await findSpotifyPage();
+ if (existing) return existing;
+
+ // A new page is navigated through the pinned CDP path so Spotify's fixed
+ // origin is checked against Chrome's actual network connections before the
+ // page is handed to the user for authentication.
+ const page = await navigateToUrlPinned(SPOTIFY_PRIVACY_URL, {
+ verifyRemoteIp: (ip) => !isPrivateAddress(ip),
+ settleMs: PAGE_SETTLE_MS,
+ closeAfterRead: false,
+ }).catch(() => null);
+ if (page && !isAllowedSpotifyPage(page)) {
+ await closeCdpPage(page.id).catch((err) => {
+ console.error(`⚠️ Failed to close unexpected Spotify browser tab: ${err?.message || String(err)}`);
+ });
+ return null;
+ }
+ return page;
+}
+
+async function inspectSpotifyPage(page) {
+ if (!page) {
+ return {
+ status: 'no-browser',
+ message: 'The PortOS managed browser is not available. Start it from Dev Tools → Browser.',
+ };
+ }
+
+ if (isSpotifyLoginPage(page)) {
+ return {
+ status: 'auth-required',
+ pageId: page.id,
+ url: page.url,
+ message: 'Sign in to Spotify in the PortOS managed browser, then check the connection again.',
+ };
+ }
+
+ const state = await evaluateOnPage(page, SPOTIFY_PAGE_STATE_EXPRESSION);
+ if (!state) {
+ return {
+ status: 'unavailable',
+ pageId: page.id,
+ url: page.url,
+ message: 'Spotify privacy page could not be read. Leave the tab open and try again.',
+ };
+ }
+
+ if (state.loginForm) {
+ return {
+ status: 'auth-required',
+ pageId: page.id,
+ url: page.url,
+ message: 'Sign in to Spotify in the PortOS managed browser, then check the connection again.',
+ };
+ }
+
+ return {
+ status: state.privacyPage ? 'ready' : 'loading',
+ pageId: page.id,
+ url: page.url,
+ hasExtendedHistory: Boolean(state.hasExtendedHistory),
+ hasDownloadAction: Boolean(state.hasDownloadAction),
+ requestPending: Boolean(state.requestPending),
+ message: state.privacyPage
+ ? 'Spotify privacy page is ready in the PortOS managed browser.'
+ : 'Spotify is still loading. Check the connection again in a moment.',
+ };
+}
+
+export async function openSpotifyBrowser() {
+ const page = await ensureSpotifyPrivacyPage();
+ return inspectSpotifyPage(page);
+}
+
+const downloadSnapshot = async () => {
+ const result = await getDownloads();
+ return new Map((result.files || []).map((file) => [file.name, file.modified]));
+};
+
+const changedSince = (file, before, startedAt) => {
+ if (!isSpotifyDownloadName(file?.name)) return false;
+ const modifiedAt = Date.parse(file.modified || '');
+ if (!Number.isFinite(modifiedAt) || modifiedAt < startedAt - 1000) return false;
+ const previous = before.get(file.name);
+ return !previous || file.modified !== previous;
+};
+
+async function findDownload(before = new Map(), startedAt = 0) {
+ const result = await getDownloads();
+ const files = (result.files || []).filter((file) => changedSince(file, before, startedAt));
+ for (const file of files) {
+ const resolved = await resolveDownload(file.name);
+ if (!resolved) continue;
+ const records = await readSpotifyRecords({
+ path: resolved.absPath,
+ originalname: resolved.name,
+ mimetype: resolved.mime,
+ }).catch(() => null);
+ if (Array.isArray(records) && records.length > 0) return { file: resolved, records };
+ }
+ return null;
+}
+
+async function waitForDownload(before, startedAt, waitMs = DOWNLOAD_WAIT_MS) {
+ const deadline = Date.now() + waitMs;
+ while (Date.now() < deadline) {
+ const found = await findDownload(before, startedAt);
+ if (found) return found;
+ await sleep(DOWNLOAD_POLL_MS);
+ }
+ return findDownload(before, startedAt);
+}
+
+const resultForPage = (page, result) => ({
+ ...result,
+ pageId: page?.id,
+ url: page?.url,
+});
+
+let importInFlight = null;
+
+async function doImportSpotifyFromBrowser(providerId, model, { waitMs = DOWNLOAD_WAIT_MS } = {}) {
+ const page = await ensureSpotifyPrivacyPage();
+ const state = await inspectSpotifyPage(page);
+ if (state.status !== 'ready') return state;
+
+ const startedAt = Date.now();
+ const before = await downloadSnapshot();
+ const action = await evaluateOnPage(page, SPOTIFY_REQUEST_DOWNLOAD_EXPRESSION);
+
+ // A direct browser download can close the CDP evaluation socket before it
+ // returns its `{ clicked: true }` value. Keep watching the download directory
+ // in that case instead of reporting a false action-required state.
+ const downloadWaitMs = action?.clicked || action?.requestPending || action == null || state.requestPending ? waitMs : 0;
+ const found = await waitForDownload(before, startedAt, downloadWaitMs);
+ if (!found) {
+ const pending = Boolean(action?.clicked || action?.requestPending || action == null || state.requestPending);
+ return resultForPage(page, {
+ status: pending ? 'pending' : 'action-required',
+ message: pending
+ ? 'Spotify is preparing or confirming the data package. Complete any confirmation/download step in the managed browser, then check again.'
+ : 'Spotify privacy page is open. Select Extended Streaming History and start the download there, then check again.',
+ downloadTriggered: Boolean(action?.clicked),
+ });
+ }
+
+ const analysis = await analyzeImportedData(
+ 'spotify',
+ JSON.stringify(found.records),
+ providerId,
+ model,
+ ).finally(() => deleteDownload(found.file.name).catch((err) => {
+ console.error(`⚠️ Spotify browser import cleanup failed: ${err?.message || String(err)}`);
+ }));
+ return resultForPage(page, {
+ status: analysis.error ? 'error' : 'complete',
+ ...analysis,
+ downloaded: true,
+ });
+}
+
+export async function importSpotifyFromBrowser(providerId, model, options = {}) {
+ if (importInFlight) return importInFlight;
+ importInFlight = doImportSpotifyFromBrowser(providerId, model, options).finally(() => {
+ importInFlight = null;
+ });
+ return importInFlight;
+}
+
+export const spotifyBrowserImportInternals = Object.freeze({
+ SPOTIFY_PAGE_STATE_EXPRESSION,
+ SPOTIFY_REQUEST_DOWNLOAD_EXPRESSION,
+ changedSince,
+});
diff --git a/server/services/spotifyBrowserImport.test.js b/server/services/spotifyBrowserImport.test.js
new file mode 100644
index 0000000000..a5e810da10
--- /dev/null
+++ b/server/services/spotifyBrowserImport.test.js
@@ -0,0 +1,158 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const browser = vi.hoisted(() => ({
+ closeCdpPage: vi.fn(),
+ deleteDownload: vi.fn(),
+ evaluateOnPage: vi.fn(),
+ getDownloads: vi.fn(),
+ listCdpPages: vi.fn(),
+ navigateToUrlPinned: vi.fn(),
+ resolveDownload: vi.fn(),
+}));
+const spotify = vi.hoisted(() => ({ readSpotifyRecords: vi.fn() }));
+const digitalTwin = vi.hoisted(() => ({ analyzeImportedData: vi.fn() }));
+
+vi.mock('./browserService.js', () => browser);
+vi.mock('./spotifyImport.js', () => spotify);
+vi.mock('./digital-twin-import.js', () => digitalTwin);
+
+import {
+ importSpotifyFromBrowser,
+ isSpotifyDownloadName,
+ isSpotifyLoginPage,
+ isSpotifyPrivacyPage,
+ openSpotifyBrowser,
+ SPOTIFY_PRIVACY_URL,
+} from './spotifyBrowserImport.js';
+
+const PRIVACY_PAGE = {
+ id: 'tab-1',
+ url: 'https://www.spotify.com/us/account/privacy/',
+};
+
+describe('Spotify browser import', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ browser.closeCdpPage.mockResolvedValue(undefined);
+ browser.deleteDownload.mockResolvedValue(true);
+ });
+
+ it('recognizes only fixed Spotify page states and export names', () => {
+ expect(isSpotifyPrivacyPage(PRIVACY_PAGE)).toBe(true);
+ expect(isSpotifyPrivacyPage({ url: 'https://evil.example/account/privacy/' })).toBe(false);
+ expect(isSpotifyLoginPage({ url: 'https://accounts.spotify.com/login' })).toBe(true);
+ expect(isSpotifyLoginPage({ url: 'https://accounts.spotify.com.evil.example/login' })).toBe(false);
+ expect(isSpotifyDownloadName('my_spotify_data.zip')).toBe(true);
+ expect(isSpotifyDownloadName('Spotify Extended Streaming History.json')).toBe(true);
+ expect(isSpotifyDownloadName('unrelated.json')).toBe(false);
+ expect(isSpotifyDownloadName('spotify-data.exe')).toBe(false);
+ });
+
+ it('opens the fixed privacy page through pinned CDP navigation when no Spotify tab exists', async () => {
+ browser.listCdpPages.mockResolvedValue([]);
+ browser.navigateToUrlPinned.mockResolvedValue(PRIVACY_PAGE);
+ browser.evaluateOnPage.mockResolvedValue({
+ privacyPage: true,
+ loginForm: false,
+ hasExtendedHistory: true,
+ hasDownloadAction: true,
+ requestPending: false,
+ });
+
+ const result = await openSpotifyBrowser();
+
+ expect(browser.navigateToUrlPinned).toHaveBeenCalledWith(
+ SPOTIFY_PRIVACY_URL,
+ expect.objectContaining({ closeAfterRead: false, settleMs: expect.any(Number) }),
+ );
+ const verifyRemoteIp = browser.navigateToUrlPinned.mock.calls[0][1].verifyRemoteIp;
+ expect(verifyRemoteIp('93.184.216.34')).toBe(true);
+ expect(verifyRemoteIp('127.0.0.1')).toBe(false);
+ expect(result).toMatchObject({ status: 'ready', pageId: 'tab-1' });
+ });
+
+ it('returns auth-required without evaluating a Spotify login page', async () => {
+ const loginPage = { id: 'tab-login', url: 'https://accounts.spotify.com/login' };
+ browser.listCdpPages.mockResolvedValue([loginPage]);
+
+ const result = await openSpotifyBrowser();
+
+ expect(result).toMatchObject({ status: 'auth-required', pageId: 'tab-login' });
+ expect(browser.evaluateOnPage).not.toHaveBeenCalled();
+ expect(browser.navigateToUrlPinned).not.toHaveBeenCalled();
+ });
+
+ it('closes a pinned navigation that leaves Spotify before exposing it', async () => {
+ const unexpectedPage = { id: 'tab-evil', url: 'https://example.com/redirected' };
+ browser.listCdpPages.mockResolvedValue([]);
+ browser.navigateToUrlPinned.mockResolvedValue(unexpectedPage);
+
+ const result = await openSpotifyBrowser();
+
+ expect(browser.closeCdpPage).toHaveBeenCalledWith('tab-evil');
+ expect(result.status).toBe('no-browser');
+ });
+
+ it('analyzes a newly downloaded Spotify archive and removes the raw file', async () => {
+ browser.listCdpPages.mockResolvedValue([PRIVACY_PAGE]);
+ browser.evaluateOnPage
+ .mockResolvedValueOnce({
+ privacyPage: true,
+ loginForm: false,
+ hasExtendedHistory: true,
+ hasDownloadAction: true,
+ requestPending: false,
+ })
+ .mockResolvedValueOnce({ clicked: true, extendedSelected: true });
+ browser.getDownloads
+ .mockResolvedValueOnce({ files: [] })
+ .mockResolvedValueOnce({ files: [{ name: 'my_spotify_data.zip', modified: new Date().toISOString() }] });
+ browser.resolveDownload.mockResolvedValue({
+ absPath: '/safe/browser-downloads/my_spotify_data.zip',
+ name: 'my_spotify_data.zip',
+ mime: 'application/zip',
+ });
+ spotify.readSpotifyRecords.mockResolvedValue([
+ { ts: '2026-01-01T00:00:00Z', master_metadata_track_name: 'Example Track' },
+ ]);
+ digitalTwin.analyzeImportedData.mockResolvedValue({
+ source: 'spotify',
+ itemCount: 1,
+ rawSummary: 'Example summary',
+ });
+
+ const result = await importSpotifyFromBrowser('local', 'example-model', { waitMs: 0 });
+
+ expect(spotify.readSpotifyRecords).toHaveBeenCalledWith(expect.objectContaining({
+ path: '/safe/browser-downloads/my_spotify_data.zip',
+ originalname: 'my_spotify_data.zip',
+ }));
+ expect(digitalTwin.analyzeImportedData).toHaveBeenCalledWith(
+ 'spotify',
+ expect.stringContaining('Example Track'),
+ 'local',
+ 'example-model',
+ );
+ expect(browser.deleteDownload).toHaveBeenCalledWith('my_spotify_data.zip');
+ expect(result).toMatchObject({ status: 'complete', downloaded: true, itemCount: 1 });
+ });
+
+ it('keeps an already-requested package in the pending state', async () => {
+ browser.listCdpPages.mockResolvedValue([PRIVACY_PAGE]);
+ browser.evaluateOnPage
+ .mockResolvedValueOnce({
+ privacyPage: true,
+ loginForm: false,
+ hasExtendedHistory: true,
+ hasDownloadAction: true,
+ requestPending: false,
+ })
+ .mockResolvedValueOnce({ clicked: false, requestPending: true, extendedSelected: false });
+ browser.getDownloads.mockResolvedValue({ files: [] });
+
+ const result = await importSpotifyFromBrowser('local', 'example-model', { waitMs: 0 });
+
+ expect(result).toMatchObject({ status: 'pending', downloadTriggered: false });
+ expect(digitalTwin.analyzeImportedData).not.toHaveBeenCalled();
+ });
+});