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

Import Suno songs whose audio file Suno withholds

Claudeaa28d64f2a7f
diff --git a/server/lib/README.md b/server/lib/README.md
index 2414896c55..784e788509 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -679,7 +679,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `dispatchLabels.js` | slashdo dispatch-hint contract: the `model:` capability and `effort:` reasoning-budget label vocabulary (the tiers themselves live in this module and are deliberately not re-enumerated here — a catalog copy of them is what drifted a tier behind), prescribed forge colors, validation (`normalizeDispatchModel` / `normalizeDispatchEffort`), the read-side inverse (`dispatchHintFromLabels` — recovers `{model, effort}` from a raw label-name list, used by branch-reconcile's per-branch routing hint), the per-forge label separator (`labelSeparator` / `forgeLabelName` — GitLab spells every prefixed label with its native scoped `::`, GitHub keeps `:`, and the read side accepts both; applied once at the `forgeIssueLabels` / `dispatchLabelSpec` boundary so the axis builders stay canonical; Jira keeps the hyphen form), optional contributor labels (`good first issue` / `help wanted`, never implied by `model:light`, and released at claim time by `formatContributorLabelReleaseCommands` — one best-effort command per label, since a forge fails the whole edit when a named label is absent), the one shared volunteer-claim policy (`volunteerClaimLabels` / `formatVolunteerClaimCommands` — a human comment claiming an unassigned issue is resolved by BOTH issueWatcher.js's deterministic pass and the claim prompt's Phase 1 handoff, so both stamp `in-progress` and retire the invitations rather than writing opposite state), the open-ended planner-attribution axis (`planner:<model>`, `normalizePlannerId` / `resolvePlannerId` / `formatPlannerLabelGuidance` — records WHICH model wrote the plan, prefix-matched by `dispatchLabelSpec` so it lazily creates like the fixed labels; a filing agent takes the value from its prompt, never from self-identification), the workflow-state markers (`EPIC_LABEL`/`EPIC_DECOMPOSED_LABEL` and `IN_PROGRESS_LABEL` — state, not hints: shared with perpetualWork.js#isActionableIssue, issueReconcile.js's zombie scan, issueWatcher.js's volunteer assignment, and the claim prompts), lazy-create command text, the optional `--label` slots a rendered `issue create` example offers (`OPTIONAL_ISSUE_LABEL_FLAG_SLOTS` / `formatOptionalIssueLabelFlags` — one list so a new axis reaches every prompt template's copy-pasteable command, not just its prose), and shared dispatch plus issue-quality guidance (`ISSUE_QUALITY_GUIDANCE`, `DISPATCH_HINT_GUIDANCE`, `MANDATORY_DISPATCH_HINT_GUIDANCE`, `JIRA_DISPATCH_HINT_GUIDANCE`, `MANDATORY_JIRA_DISPATCH_HINT_GUIDANCE`, `REFERENCE_WATCH_LABEL_CONTRACT`, plus the consumer-side pair `DISPATCH_HINT_READING_GUIDANCE` / `DISPATCH_HINT_FANOUT_GUIDANCE` — what the labels mean to an agent that RECEIVES them (the preloaded `open-issues` task data input) and, for an orchestrator only, how to route each sub-agent by its own issue (the swarm block); the fan-out form is the reading form plus one line, never a second copy of the vocabulary). All forge filing callers require both dispatch axes and verify labels after creation; help wanted requires specific hardware validation or valuable input from real users; never invent `medium`; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts. |
| `distrokidForm.js` | The in-page steps of the DistroKid upload recipe (#10337): `fillDistrokidFields` (genre, language, store profiles, credits, preview start, the track's normal answers), `discloseDistrokidAi` (inline AI checkboxes, gate then parts) and `untickDistrokidExtras` (paid extras). Self-contained so `page.evaluate` can ship them, and tested against a fixture form in the client's DOM tests. |
| `sunoPage.js` | The in-page step of the Suno publish recipe: `markSunoSongMenu(songId)` tags the song page's OWN "More options" button with `data-portos-song-menu` (false when there is none), skipping the menus of other songs the page shows: the "Cover of" card of the song a cover was made from, the Similar / By-artist lists, the playbar. Runs inside the page via `page.evaluate`, so it reads only `document`; fixture tests live in `client/src/lib/sunoPage.test.js`. |
-| `sunoSong.js` | Suno song links and pages for the track import: `SUNO_SONG_URL_RE` / `isSunoSongUrl` (a `suno.com/song/<uuid>` page or `suno.com/s/<code>` share link), `sunoSongIdFromUrl`, `isSunoHost`, `sunoCdnAudioUrl`, and `parseSunoSongPage(html, songId)` → `{ title, lyrics, style, audioUrl, imageUrl }` read from the page's Next.js flight payload (long-text rows resolved) with og: tags as fallback. Pure leaf the client also imports. |
+| `sunoSong.js` | Suno song links and pages for the track import: `SUNO_SONG_URL_RE` / `isSunoSongUrl` (a `suno.com/song/<uuid>` page or `suno.com/s/<code>` share link), `sunoSongIdFromUrl`, `isSunoHost`, `sunoCdnAudioUrl`, `sunoCdnVideoUrl` (the public fallback when Suno withholds the audio file), and `parseSunoSongPage(html, songId)` → `{ title, lyrics, style, audioUrl (CDN media only), imageUrl }` read from the page's Next.js flight payload (long-text rows resolved) with og: tags as fallback. Pure leaf the client also imports. |
| `sunoSongPicker.js` | `pickSongRow(rows, { songId, durationSec, title })`: which Suno Hook picker row is the project song: by id when a row carries it, else the one row with the song's length, else the only row; -1 when rows cannot be told apart. |
| `distrokidGenres.js` | DistroKid's store genre list (`DISTROKID_GENRES`) and `suggestDistrokidGenres(project)`, a first primary/secondary genre guess from the song's own style words. Shared by the DistroKid publish payload and the publish panel's genre pickers. |
| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. |
diff --git a/server/lib/sunoSong.js b/server/lib/sunoSong.js
index 25f94bd155..0a959fba9a 100644
--- a/server/lib/sunoSong.js
+++ b/server/lib/sunoSong.js
@@ -36,6 +36,17 @@ export function isSunoHost(hostname) {
/** Suno's CDN copy of a song's audio, used when the page names none. */
export const sunoCdnAudioUrl = (songId) => `https://cdn1.suno.ai/${encodeURIComponent(songId)}.mp3`;
+/** Suno's CDN copy of a song's video, which stays public when Suno withholds the audio file. */
+export const sunoCdnVideoUrl = (songId) => `https://cdn1.suno.ai/${encodeURIComponent(songId)}.mp4`;
+
+// Media lives on Suno's CDN hosts (cdn1.suno.ai, …). A page can name an API
+// placeholder such as studio-api…/api/forbidden instead, which is no media at all.
+const isSunoCdnUrl = (value) => {
+ if (typeof value !== 'string' || !URL.canParse(value)) return false;
+ const url = new URL(value);
+ return url.protocol === 'https:' && /^cdn\d*\.suno\.(?:ai|com)$/i.test(url.hostname);
+};
+
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'", '#x27': "'" };
const decodeEntities = (s) => s.replace(/&(amp|lt|gt|quot|apos|#39|#x27);/gi, (m, name) => ENTITIES[name.toLowerCase()] ?? m);
@@ -138,7 +149,7 @@ export function parseSunoSongPage(html, songId) {
return (ref ? texts.get(ref.toLowerCase()) ?? '' : value).trim();
};
const title = text(song.title) || metaContent(page, 'og:title').replace(/\s*\|\s*Suno\s*$/i, '').trim();
- const audioUrl = [song.audio_url, metaContent(page, 'og:audio')].find(isSunoUrl) || null;
+ const audioUrl = [song.audio_url, metaContent(page, 'og:audio')].find(isSunoCdnUrl) || null;
const imageUrl = [song.image_large_url, song.image_url, metaContent(page, 'og:image')].find(isSunoUrl) || null;
return {
title,
diff --git a/server/lib/sunoSong.test.js b/server/lib/sunoSong.test.js
index 76eabad0d0..c803cbfca5 100644
--- a/server/lib/sunoSong.test.js
+++ b/server/lib/sunoSong.test.js
@@ -58,6 +58,11 @@ describe('parseSunoSongPage', () => {
expect(parseSunoSongPage(html, ID)).toMatchObject({ title: 'Full', lyrics: 'words', style: 'rock' });
});
+ it('ignores an audio_url that is an API placeholder rather than CDN media', () => {
+ const html = page([`6:${JSON.stringify({ song: { id: ID, title: 'T', audio_url: 'https://studio-api.prod.suno.com/api/forbidden', metadata: {} } })}\n`]);
+ expect(parseSunoSongPage(html, ID).audioUrl).toBeNull();
+ });
+
it('falls back to og: tags and refuses media URLs off Suno', () => {
const head = '<meta property="og:title" content="Rock &amp; Roll | Suno"><meta property="og:image" content="https://evil.example/x.jpg">'
+ `<meta property="og:audio" content="https://cdn1.suno.ai/${ID}.mp3">`;
diff --git a/server/services/trackSunoImport.js b/server/services/trackSunoImport.js
index 9622f7d711..b994575e89 100644
--- a/server/services/trackSunoImport.js
+++ b/server/services/trackSunoImport.js
@@ -16,11 +16,11 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { shortId } from '../lib/fileUtils.js';
-import { probeVideoDuration } from '../lib/ffmpeg.js';
+import { findFfmpeg, probeVideoDuration, runFfmpegProcess } from '../lib/ffmpeg.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';
import { fetchPublicBinary, fetchPublicText, resolvePublicUrl } from '../lib/safeUrlFetch.js';
import {
- isSunoSongUrl, isSunoHost, sunoSongIdFromUrl, sunoCdnAudioUrl, parseSunoSongPage, SUNO_URL_INVALID_MESSAGE,
+ isSunoSongUrl, isSunoHost, sunoSongIdFromUrl, sunoCdnAudioUrl, sunoCdnVideoUrl, parseSunoSongPage, SUNO_URL_INVALID_MESSAGE,
} from '../lib/sunoSong.js';
import { importUploadedTrack, MUSIC_UPLOAD_MAX_BYTES } from './pipeline/musicLibrary.js';
import { createTrack } from './tracks/index.js';
@@ -29,6 +29,8 @@ import { RENDER_SOURCES } from './tracks/logic.js';
const PAGE_TIMEOUT_MS = 20_000;
const PAGE_MAX_BYTES = 5 * 1024 * 1024;
const AUDIO_TIMEOUT_MS = 5 * 60 * 1000;
+// The song's video carries a picture track too, so it may run well past the audio cap.
+const VIDEO_MAX_BYTES = 250 * 1024 * 1024;
// Suno serves its pages to browsers; a bare fetch user agent can get a challenge page instead.
const HEADERS = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0 Safari/537.36' };
@@ -38,6 +40,34 @@ const isAudioResponse = (contentType) => {
return !type || type.startsWith('audio/') || type === 'video/mp4' || type === 'application/octet-stream';
};
+const isVideoResponse = (contentType) => {
+ const type = String(contentType || '').split(';')[0].trim().toLowerCase();
+ return !type || type === 'video/mp4' || type === 'application/octet-stream';
+};
+
+// The first source that answers with audio, or null when Suno refuses them all.
+async function fetchSongAudio(urls) {
+ for (const url of [...new Set(urls.filter(Boolean))]) {
+ const res = await fetchPublicBinary(url, {
+ timeoutMs: AUDIO_TIMEOUT_MS, headers: HEADERS, maxBytes: MUSIC_UPLOAD_MAX_BYTES, throwOnUnsafe: false,
+ });
+ if (res?.buffer?.byteLength && isAudioResponse(res.contentType)) return res;
+ }
+ return null;
+}
+
+// Copy the video's audio track out (Suno's is AAC); transcode only if a copy fails.
+async function extractAudio(videoPath, outPath) {
+ const bin = await findFfmpeg();
+ if (!bin) throw new Error('Suno only offers this song as a video, and ffmpeg is needed to take its audio out');
+ for (const codec of [['-c:a', 'copy'], ['-c:a', 'aac', '-b:a', '256k']]) {
+ const res = await runFfmpegProcess({ bin, args: ['-y', '-i', videoPath, '-vn', '-map', '0:a:0', ...codec, outPath] });
+ if (res.ok) return;
+ console.warn(`⚠️ Suno audio extract (${codec[1]}) failed: ${res.reason}`);
+ }
+ throw new Error('Could not take the audio out of the video Suno offers for this song');
+}
+
// jobId -> { clients, lastPayload, status, canceled }
const importJobs = new Map();
@@ -96,24 +126,34 @@ export async function startSunoImport(url) {
if (abortIfCanceled()) return;
broadcastSse(job, { type: 'progress', percent: 20, stage: 'downloading' });
- const audio = await fetchPublicBinary(song.audioUrl || sunoCdnAudioUrl(songId), {
- timeoutMs: AUDIO_TIMEOUT_MS, headers: HEADERS, maxBytes: MUSIC_UPLOAD_MAX_BYTES, throwOnUnsafe: false,
- });
+ const audio = await fetchSongAudio([song.audioUrl, sunoCdnAudioUrl(songId)]);
if (abortIfCanceled()) return;
- if (!audio?.buffer?.byteLength) {
- throw new Error('Could not download the song audio from Suno (is the song public or unlisted?)');
- }
- // An error or interstitial page can come back with a 200; only audio becomes a track.
- if (!isAudioResponse(audio.contentType)) {
- throw new Error('Suno sent back something other than audio for this song (has it finished generating?)');
+ dir = await mkdtemp(join(tmpdir(), 'portos-sunoimport-'));
+ let tempPath;
+ if (audio) {
+ 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);
+ tempPath = join(dir, 'song.m4a');
+ await extractAudio(videoPath, tempPath);
+ if (abortIfCanceled()) return;
}
broadcastSse(job, { type: 'progress', percent: 90, stage: 'importing' });
const title = song.title || 'Suno song';
- const ext = /mp4|m4a|aac/i.test(audio.contentType) ? 'm4a' : 'mp3';
- dir = await mkdtemp(join(tmpdir(), 'portos-sunoimport-'));
- const tempPath = join(dir, `song.${ext}`);
- await writeFile(tempPath, audio.buffer);
+ const ext = tempPath.endsWith('.m4a') ? 'm4a' : 'mp3';
// Probe before the library import so a file ffprobe can't read never lands there.
const durationSec = await probeVideoDuration(tempPath).catch(() => null);
if (!durationSec) throw new Error('The file Suno sent back is not playable audio');
diff --git a/server/services/trackSunoImport.test.js b/server/services/trackSunoImport.test.js
index 9d2ce108ba..2dcad70af6 100644
--- a/server/services/trackSunoImport.test.js
+++ b/server/services/trackSunoImport.test.js
@@ -1,6 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-vi.mock('../lib/ffmpeg.js', () => ({ probeVideoDuration: vi.fn(async () => 200) }));
+vi.mock('../lib/ffmpeg.js', () => ({
+ probeVideoDuration: vi.fn(async () => 200),
+ findFfmpeg: vi.fn(async () => '/usr/local/bin/ffmpeg'),
+ runFfmpegProcess: vi.fn(async () => ({ ok: true })),
+}));
vi.mock('./pipeline/musicLibrary.js', () => ({
importUploadedTrack: vi.fn(async () => ({ filename: 'music-suno.mp3', sizeBytes: 10 })),
MUSIC_UPLOAD_MAX_BYTES: 50 * 1024 * 1024,
@@ -10,7 +14,7 @@ vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: v
vi.mock('../lib/safeUrlFetch.js', () => ({ fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn(), resolvePublicUrl: vi.fn() }));
const { broadcastSse } = await import('../lib/sseUtils.js');
-const { probeVideoDuration } = await import('../lib/ffmpeg.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 { createTrack } = await import('./tracks/index.js');
@@ -29,6 +33,7 @@ const terminal = () => vi.waitFor(() => {
beforeEach(() => {
vi.clearAllMocks();
probeVideoDuration.mockResolvedValue(200);
+ runFfmpegProcess.mockResolvedValue({ ok: true });
fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from('ID3audio'), contentType: 'audio/mpeg' });
});
@@ -71,22 +76,57 @@ describe('startSunoImport', () => {
fetchPublicText.mockResolvedValue(null);
fetchPublicBinary.mockResolvedValue(null);
await startSunoImport(`https://suno.com/song/${ID}`);
- expect(await terminal()).toMatchObject({ type: 'error', error: expect.stringMatching(/Could not download/) });
+ expect(await terminal()).toMatchObject({ type: 'error', error: expect.stringMatching(/would not hand over/) });
expect(createTrack).not.toHaveBeenCalled();
});
it.each([
- ['an HTML page', { buffer: Buffer.from('<html>Just a moment…</html>'), contentType: 'text/html; charset=utf-8' }, /other than audio/],
+ ['an HTML page', { buffer: Buffer.from('<html>Just a moment…</html>'), contentType: 'text/html; charset=utf-8' }, /would not hand over/],
['an unplayable file', { buffer: Buffer.from('garbage'), contentType: 'audio/mpeg' }, /not playable audio/],
])('refuses %s as the song audio, creating no track', async (_label, body, message) => {
fetchPublicText.mockResolvedValue(null);
fetchPublicBinary.mockResolvedValue(body);
- probeVideoDuration.mockResolvedValueOnce(null);
+ probeVideoDuration.mockResolvedValue(null);
await startSunoImport(`https://suno.com/song/${ID}`);
expect(await terminal()).toMatchObject({ type: 'error', error: expect.stringMatching(message) });
expect(importUploadedTrack).not.toHaveBeenCalled();
});
+ 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({
+ id: ID, title: 'Airplane Mode', audio_url: 'https://studio-api.prod.suno.com/api/forbidden',
+ metadata: { prompt: '[Verse]\nno signal', tags: 'dream pop' },
+ }));
+ fetchPublicBinary.mockImplementation(async (url) => (url.endsWith('.mp4')
+ ? { buffer: Buffer.from('mp4bytes'), contentType: 'video/mp4' }
+ : null));
+ await startSunoImport(`https://suno.com/song/${ID}`);
+ expect(await terminal()).toMatchObject({ type: 'complete' });
+ expect(fetchPublicBinary.mock.calls.map(([url]) => url)).toEqual([
+ `https://cdn1.suno.ai/${ID}.mp3`, `https://cdn1.suno.ai/${ID}.mp4`,
+ ]);
+ expect(runFfmpegProcess).toHaveBeenCalledWith({ bin: '/usr/local/bin/ffmpeg', args: expect.arrayContaining(['-vn', '-c:a', 'copy']) });
+ expect(importUploadedTrack).toHaveBeenCalledWith(expect.stringMatching(/song\.m4a$/), 'Airplane Mode.m4a');
+ expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({ title: 'Airplane Mode', lyrics: '[Verse]\nno signal' }));
+ });
+
+ it('transcodes when the video\'s audio track will not copy, and fails when nothing will', async () => {
+ fetchPublicText.mockResolvedValue(null);
+ fetchPublicBinary.mockImplementation(async (url) => (url.endsWith('.mp4') ? { buffer: Buffer.from('v'), contentType: 'video/mp4' } : null));
+ runFfmpegProcess.mockResolvedValueOnce({ ok: false, reason: 'copy failed' });
+ await startSunoImport(`https://suno.com/song/${ID}`);
+ expect(await terminal()).toMatchObject({ type: 'complete' });
+ expect(runFfmpegProcess.mock.calls[1][0].args).toEqual(expect.arrayContaining(['-c:a', 'aac']));
+
+ vi.clearAllMocks();
+ probeVideoDuration.mockResolvedValue(200);
+ runFfmpegProcess.mockResolvedValue({ ok: false, reason: 'no audio stream' });
+ await startSunoImport(`https://suno.com/song/${ID}`);
+ expect(await terminal()).toMatchObject({ type: 'error', error: expect.stringMatching(/take the audio out/) });
+ expect(createTrack).not.toHaveBeenCalled();
+ });
+
it('ends as cancelled, creating no track, when cancelled mid-download', async () => {
fetchPublicText.mockResolvedValue(null);
let release;