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
Import private Suno songs through the signed-in PortOS Browser
Claude9c238a8c9ea5
diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.jsindex 5b933a50ff..1cef991c06 100644--- a/server/services/musicVideo/autonomousSuno.js+++ b/server/services/musicVideo/autonomousSuno.js@@ -303,7 +303,7 @@ async function watchDownloadsDir(listDownloads, baseline, signal, pollMs) {/** One bounded export, including waiting for the browser to finish saving. */async function downloadSunoAudio(page, songId, path, {timeoutMs = SUNO_AUDIO_TIMEOUT_MS, signal, validateAudio = validateSunoAudio,- listDownloads = defaultListDownloads, downloadPollMs = DOWNLOAD_POLL_MS, onProgress,+ listDownloads = defaultListDownloads, downloadPollMs = DOWNLOAD_POLL_MS, onProgress, onSongPage,} = {}) {const controller = new AbortController();const deadline = Date.now() + timeoutMs;@@ -340,6 +340,12 @@ async function downloadSunoAudio(page, songId, path, {try {await bounded('open-song', () => page.goto(sunoSongUrl(songId), { waitUntil: 'domcontentloaded', timeout: remaining() }));if (/sign-?in|login|accounts\./i.test(page.url())) throw loginRequired(LABEL, SUNO_CREATE_URL);+ // The signed-in page also carries a private song's title and lyrics; a+ // caller that wants them gets the HTML. Advisory: it never fails the export.+ if (onSongPage) {+ const html = await bounded('read-page', () => page.content()).catch(() => null);+ if (html) { try { onSongPage(html); } catch { /* advisory */ } }+ }await bounded('open-options', () => page.getByRole('button', { name: 'More options', exact: true }).first().click({ timeout: remaining() }));await bounded('open-download', () => page.getByRole('menuitem', { name: 'Download', exact: true }).click({ timeout: remaining() }));for (const name of ['M4A', 'MP3', 'WAV', 'MP4 video asset']) {diff --git a/server/services/musicVideo/autonomousSuno.test.js b/server/services/musicVideo/autonomousSuno.test.jsindex 3063b00202..69a66e223f 100644--- a/server/services/musicVideo/autonomousSuno.test.js+++ b/server/services/musicVideo/autonomousSuno.test.js@@ -348,6 +348,18 @@ describe('generateSunoSong M4A export', () => {expect(out.songId).toBe(NEW_B);});+ it('hands the signed-in song page to onSongPage, and a failing page read never fails the export', async () => {+ const w = workflow();+ w.page.content = vi.fn(async () => '<html>song page</html>');+ const onSongPage = vi.fn();+ await generateSunoSong(fields, { ...w, songIds: [NEW_B], onSongPage });+ expect(onSongPage).toHaveBeenCalledWith('<html>song page</html>');++ const broken = workflow();+ broken.page.content = vi.fn(async () => { throw new Error('page gone'); });+ await expect(generateSunoSong(fields, { ...broken, songIds: [NEW_B], onSongPage: vi.fn() })).resolves.toMatchObject({ songId: NEW_B });+ });+it.each(['event', 'save'])('bounds a stalled download %s and cleans up without importing or retrying the click', async (stalled) => {vi.useFakeTimers();const w = workflow({ stalled });diff --git a/server/services/trackSunoImport.js b/server/services/trackSunoImport.jsindex e4eb7843ee..03a775b8a7 100644--- a/server/services/trackSunoImport.js+++ b/server/services/trackSunoImport.js@@ -11,7 +11,7 @@*/import { randomUUID } from 'crypto';-import { mkdtemp, rm, writeFile } from 'fs/promises';+import { copyFile, mkdtemp, rm, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';import { ServerError } from '../lib/errorHandler.js';@@ -68,6 +68,21 @@ async function extractAudio(videoPath, outPath, signal) {throw new Error('Could not take the audio out of the video Suno offers for this song');}+// Export the song through the signed-in PortOS Browser, the same export the+// autopilot uses, so a private or unpublished song in the user's own Suno+// library imports too. Resolves the page HTML it saw (for title and lyrics).+async function exportThroughBrowser(songId, outPath, signal) {+ const { generateSunoSong } = await import('./musicVideo/autonomousSuno.js');+ let html = '';+ await generateSunoSong({}, {+ songIds: [songId], signal,+ onSongPage: (pageHtml) => { html = pageHtml; },+ // Keep the export out of the library until it passes this import's checks.+ importAudio: async (path) => { await copyFile(path, outPath); return { filename: null, sizeBytes: 0 }; },+ });+ return html;+}+// jobId -> { clients, lastPayload, status, canceled }const importJobs = new Map();@@ -123,10 +138,10 @@ export async function startSunoImport(url) {const html = await fetchPublicText(`https://suno.com/song/${songId}`, {timeoutMs: PAGE_TIMEOUT_MS, headers: HEADERS, maxBytes: PAGE_MAX_BYTES, throwOnUnsafe: false,}).catch(() => null);- const song = parseSunoSongPage(html || '', songId);if (abortIfCanceled()) return;broadcastSse(job, { type: 'progress', percent: 20, stage: 'downloading' });+ let song = parseSunoSongPage(html || '', songId);const audio = await fetchSongAudio([song.audioUrl, sunoCdnAudioUrl(songId)]);if (abortIfCanceled()) return;dir = await mkdtemp(join(tmpdir(), 'portos-sunoimport-'));@@ -135,21 +150,33 @@ export async function startSunoImport(url) {tempPath = join(dir, `song.${/mp4|m4a|aac/i.test(audio.contentType) ? 'm4a' : 'mp3'}`);await writeFile(tempPath, audio.buffer);} else {- // Suno can withhold the audio file even for a public song while its- // video stays public; the video carries the same audio track.- const video = await fetchPublicBinary(sunoCdnVideoUrl(songId), {- timeoutMs: AUDIO_TIMEOUT_MS, headers: HEADERS, maxBytes: VIDEO_MAX_BYTES, throwOnUnsafe: false,- });- if (abortIfCanceled()) return;- if (!video?.buffer?.byteLength || !isVideoResponse(video.contentType)) {- throw new Error('Suno would not hand over this song\'s audio or video (is the song public or unlisted, and finished generating?)');- }- broadcastSse(job, { type: 'progress', percent: 70, stage: 'extracting' });- const videoPath = join(dir, 'song.mp4');- await writeFile(videoPath, video.buffer);+ // Suno withholds the audio file from anonymous requests (always for a+ // private or unpublished song). The signed-in browser can export it.+ broadcastSse(job, { type: 'progress', percent: 30, stage: 'exporting' });tempPath = join(dir, 'song.m4a');- await extractAudio(videoPath, tempPath, job.abort.signal);+ const browserError = await exportThroughBrowser(songId, tempPath, job.abort.signal).then((pageHtml) => {+ // Fill only what the anonymous page lacked: a private song shows nothing there.+ const signedIn = parseSunoSongPage(pageHtml, songId);+ song = { ...song, title: song.title || signedIn.title, lyrics: song.lyrics || signedIn.lyrics, style: song.style || signedIn.style };+ return null;+ }, (err) => err);if (abortIfCanceled()) return;+ if (browserError) {+ console.warn(`⚠️ Suno import ${shortId(jobId)}: browser export failed (${browserError.message}); trying the public video`);+ // A public song's video stays downloadable without signing in, and carries the same audio.+ const video = await fetchPublicBinary(sunoCdnVideoUrl(songId), {+ timeoutMs: AUDIO_TIMEOUT_MS, headers: HEADERS, maxBytes: VIDEO_MAX_BYTES, throwOnUnsafe: false,+ });+ if (abortIfCanceled()) return;+ if (!video?.buffer?.byteLength || !isVideoResponse(video.contentType)) {+ throw new Error(`Suno would not hand over this song's audio. For a private or unpublished song, sign in to Suno in the PortOS Browser and try again (${browserError.message})`);+ }+ broadcastSse(job, { type: 'progress', percent: 70, stage: 'extracting' });+ const videoPath = join(dir, 'song.mp4');+ await writeFile(videoPath, video.buffer);+ await extractAudio(videoPath, tempPath, job.abort.signal);+ if (abortIfCanceled()) return;+ }}broadcastSse(job, { type: 'progress', percent: 90, stage: 'importing' });diff --git a/server/services/trackSunoImport.test.js b/server/services/trackSunoImport.test.jsindex 05a9d42c09..5e885f2eb9 100644--- a/server/services/trackSunoImport.test.js+++ b/server/services/trackSunoImport.test.js@@ -11,12 +11,14 @@ vi.mock('./pipeline/musicLibrary.js', () => ({}));vi.mock('./tracks/index.js', () => ({ createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })) }));vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: vi.fn(() => true), closeJobAfterDelay: vi.fn() }));+vi.mock('./musicVideo/autonomousSuno.js', () => ({ generateSunoSong: vi.fn() }));vi.mock('../lib/safeUrlFetch.js', () => ({ fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn(), resolvePublicUrl: vi.fn() }));const { broadcastSse } = await import('../lib/sseUtils.js');const { probeVideoDuration, runFfmpegProcess } = await import('../lib/ffmpeg.js');const { fetchPublicText, fetchPublicBinary, resolvePublicUrl } = await import('../lib/safeUrlFetch.js');const { importUploadedTrack } = await import('./pipeline/musicLibrary.js');+const { generateSunoSong } = await import('./musicVideo/autonomousSuno.js');const { createTrack } = await import('./tracks/index.js');const { startSunoImport, cancelSunoImport } = await import('./trackSunoImport.js');@@ -34,6 +36,7 @@ beforeEach(() => {vi.clearAllMocks();probeVideoDuration.mockResolvedValue(200);runFfmpegProcess.mockResolvedValue({ ok: true });+ generateSunoSong.mockRejectedValue(new Error('Sign in to Suno in the PortOS Browser'));fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from('ID3audio'), contentType: 'audio/mpeg' });});@@ -92,6 +95,25 @@ describe('startSunoImport', () => {expect(importUploadedTrack).not.toHaveBeenCalled();});+ it('exports a private song through the signed-in browser, taking its title and lyrics from that page', async () => {+ fetchPublicText.mockResolvedValue(null); // the anonymous page shows nothing for a private song+ fetchPublicBinary.mockResolvedValue(null);+ generateSunoSong.mockImplementation(async (_fields, deps) => {+ deps.onSongPage(songPage({ id: ID, title: 'Unreleased', metadata: { prompt: 'draft words', tags: 'lo-fi' } }));+ const { mkdtemp, writeFile, rm } = await import('fs/promises');+ const srcDir = await mkdtemp(`${(await import('os')).tmpdir()}/suno-test-`);+ await writeFile(`${srcDir}/song.m4a`, 'm4a');+ await deps.importAudio(`${srcDir}/song.m4a`, 'song.m4a').finally(() => rm(srcDir, { recursive: true, force: true }));+ return { songId: ID };+ });+ await startSunoImport(`https://suno.com/song/${ID}`);+ expect(await terminal()).toMatchObject({ type: 'complete' });+ expect(generateSunoSong).toHaveBeenCalledWith({}, expect.objectContaining({ songIds: [ID], signal: expect.any(AbortSignal) }));+ expect(fetchPublicBinary.mock.calls.map(([url]) => url)).not.toContain(`https://cdn1.suno.ai/${ID}.mp4`);+ expect(importUploadedTrack).toHaveBeenCalledWith(expect.stringMatching(/song\.m4a$/), 'Unreleased.m4a');+ expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({ title: 'Unreleased', lyrics: 'draft words', prompt: 'lo-fi' }));+ });+it('takes the audio out of the public video when Suno withholds the audio file', async () => {// Suno's live page names an API placeholder rather than media, and the mp3 403s.fetchPublicText.mockResolvedValue(songPage({