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

fix: bound Suno downloads and verify audio before import (#9525)

Adam Eivyd1d72fbeb420
diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.js
index 1a7ae9af08..242fe4c25b 100644
--- a/server/services/musicVideo/autonomousSuno.js
+++ b/server/services/musicVideo/autonomousSuno.js
@@ -9,8 +9,8 @@
* Two deliberate choices keep this robust to Suno's UI churn:
* - The page is only used to FILL the custom-song form, press Create, and
* read back the new `/song/<id>` links. Everything after that — waiting for
- * the song and fetching the audio — happens over HTTP against the CDN, so a
- * redesigned player or download menu cannot break it.
+ * audio — happens over HTTP against the CDN. This transport does not yet
+ * provide a verified generation-completion signal; import fails closed.
* - Every page interaction goes through `step()`, so a failure names the
* control that was missing ("Suno: fill the lyrics (...)") and a signed-out
* page is reported as PUBLISH_LOGIN_REQUIRED, which the run surfaces as a
@@ -23,8 +23,12 @@
import { mkdtemp, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
+import { promisify } from 'util';
+import { execFile } from '../../lib/childProcess.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
+import { withAbortTimeout } from '../../lib/abortTimeout.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { sunoAudioUrl, sunoSongIdsFromHrefs, sunoSongUrl } from '../../lib/musicVideoAutonomous.js';
+import { sunoAudioUrl, sunoSongIdsFromHrefs } from '../../lib/musicVideoAutonomous.js';
import { sleep as defaultSleep } from '../../lib/fileCore.js';
import { PUBLISH_STEP_TIMEOUT_MS as T, connectPortosBrowser, loginRequired, serializeBrowserOperation as serialize, step } from './publish/browser.js';
@@ -178,28 +182,105 @@ async function submitSunoSong(page, fields, { sleep = defaultSleep, now = Date.n
}
}
+// Decoding is a separate boundary from generation completion: a partial MP3
+// can decode perfectly. Never expose ffmpeg stderr (it contains local paths).
+async function validateSunoAudio(bytes, { signal, timeoutMs }) {
+ const { findFfmpeg } = await import('../../lib/ffmpeg.js');
+ const bin = await findFfmpeg();
+ if (!bin) throw new ServerError('Suno: audio validation requires ffmpeg', {
+ status: 503, code: 'SUNO_AUDIO_VALIDATION_UNAVAILABLE', context: { platform: LABEL },
+ });
+ signal.throwIfAborted();
+ const dir = await mkdtemp(join(tmpdir(), 'portos-suno-validation-'));
+ try {
+ const file = join(dir, 'candidate.mp3');
+ await writeFile(file, bytes, { signal });
+ // Force an audio stream and decode the entire candidate; neither MIME nor
+ // a readable container header proves that its audio frames are decodable.
+ const { stdout } = await promisify(execFile)(bin, [
+ '-nostdin', '-v', 'error', '-xerror', '-err_detect', 'explode',
+ '-protocol_whitelist', 'file', '-format_whitelist', 'mp3,wav', '-i', file,
+ '-map', '0:a:0', '-progress', 'pipe:1', '-stats_period', '600', '-f', 'null', '-',
+ ], safeChildProcessOptions({ signal, timeout: timeoutMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 }));
+ if (![...stdout.matchAll(/^out_time_us=(\d+)$/gm)].some((match) => Number(match[1]) > 0)) {
+ throw new Error('No decoded audio frames');
+ }
+ return true;
+ } catch (error) {
+ if (signal.aborted) throw signal.reason;
+ throw new ServerError('Suno: downloaded content is not decodable audio', {
+ status: 502, code: 'SUNO_AUDIO_INVALID', context: { platform: LABEL, reason: 'decode_failed' },
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
/**
- * Wait for a song's audio to be fetchable and fully written, then return its
- * bytes. "Fully written" = a 200 whose size is at least MIN_AUDIO_BYTES and
- * unchanged across two polls (Suno streams a partial file while it renders).
+ * Stable sizes are only a polling heuristic. The CDN integration currently
+ * has no verified completion signal, so its default remains explicitly
+ * unknown. A future verified adapter must check this exact song and return
+ * 'complete'; playable audio, a duration, or a 200 response are not evidence.
*/
async function downloadSunoAudio(songId, {
fetchImpl = fetch, sleep = defaultSleep, timeoutMs = SUNO_AUDIO_TIMEOUT_MS, intervalMs = SUNO_POLL_INTERVAL_MS, now = Date.now,
+ checkCompletion = async () => 'unknown', validateAudio = validateSunoAudio,
} = {}) {
const deadline = now() + timeoutMs;
let lastSize = -1;
+ let reason = 'not_available';
+ let httpStatus = null;
+ const timeout = () => new ServerError('Suno: audio download did not complete within its time budget', {
+ status: 504, code: 'SUNO_AUDIO_TIMEOUT', context: { platform: LABEL, reason, httpStatus },
+ });
for (;;) {
- const res = await fetchImpl(sunoAudioUrl(songId)).catch(() => null);
- if (res?.ok) {
- const bytes = Buffer.from(await res.arrayBuffer());
- if (bytes.length >= MIN_AUDIO_BYTES && bytes.length === lastSize) return bytes;
- lastSize = bytes.length;
- }
- if (now() + intervalMs > deadline) {
- throw new ServerError(`Suno: the song ${songId} did not finish rendering in time`, {
- status: 504, code: 'SUNO_AUDIO_TIMEOUT', context: { platform: LABEL, songId, url: sunoSongUrl(songId) },
- });
- }
+ const remaining = deadline - now();
+ if (remaining <= 0) throw timeout();
+ const candidate = await withAbortTimeout(remaining, async (signal) => {
+ let res;
+ try {
+ res = await fetchImpl(sunoAudioUrl(songId), { signal });
+ signal.throwIfAborted();
+ httpStatus = Number.isInteger(res.status) && res.status >= 100 && res.status <= 599 ? res.status : null;
+ if (!res.ok) { reason = 'http_status'; return null; }
+ const mime = res.headers?.get('content-type')?.split(';')[0].trim().toLowerCase();
+ if (mime?.startsWith('text/') || /(?:json|xml|html)/.test(mime || '')) {
+ throw new ServerError('Suno: downloaded content is not audio', {
+ status: 502, code: 'SUNO_AUDIO_INVALID', context: { platform: LABEL, reason: 'non_audio_content', httpStatus },
+ });
+ }
+ const bytes = Buffer.from(await res.arrayBuffer());
+ signal.throwIfAborted();
+ const stable = bytes.length >= MIN_AUDIO_BYTES && bytes.length === lastSize;
+ lastSize = bytes.length;
+ if (!stable) { reason = 'size_unstable'; return null; }
+ const valid = await validateAudio(bytes, { signal, timeoutMs: Math.max(1, deadline - now()) });
+ signal.throwIfAborted();
+ if (valid !== true) throw new ServerError('Suno: downloaded content is not decodable audio', {
+ status: 502, code: 'SUNO_AUDIO_INVALID', context: { platform: LABEL, reason: 'decode_failed' },
+ });
+ const completion = await checkCompletion(songId, { signal });
+ signal.throwIfAborted();
+ if (completion === 'complete') return bytes;
+ if (completion === 'pending') { reason = 'generation_pending'; return null; }
+ throw new ServerError('Suno: audio is decodable, but generation completion is unverified; existing song IDs are retained for retry', {
+ status: 502, code: 'SUNO_AUDIO_COMPLETION_UNVERIFIED', context: { platform: LABEL, reason: 'completion_unknown' },
+ });
+ } catch (error) {
+ if (signal.aborted) { reason = 'deadline_exceeded'; throw timeout(); }
+ if (error instanceof ServerError) throw error;
+ reason = 'transport_failed';
+ return null;
+ } finally {
+ // Cancel unconsumed error bodies too. A locked body is owned by the
+ // fetch consumer, which receives the same abort signal. Cancellation
+ // starts immediately; its acknowledgment cannot extend our deadline.
+ if (res?.body && !res.bodyUsed) void res.body.cancel().catch(() => {});
+ }
+ });
+ if (now() >= deadline) throw timeout();
+ if (candidate) return candidate;
+ if (now() + intervalMs >= deadline) throw timeout();
await sleep(intervalMs);
}
}
@@ -217,8 +298,12 @@ export async function generateSunoSong(fields, deps = {}) {
const { importUploadedTrack } = await import('../pipeline/musicLibrary.js');
const dir = await mkdtemp(join(tmpdir(), 'portos-suno-'));
const tmp = join(dir, 'song.mp3');
- await writeFile(tmp, bytes);
- return importUploadedTrack(tmp, 'song.mp3').finally(() => rm(dir, { recursive: true, force: true }).catch(() => {}));
+ try {
+ await writeFile(tmp, bytes);
+ return await importUploadedTrack(tmp, 'song.mp3');
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
});
// A retry after a failed download reuses the songs already submitted rather
// than spending more Suno credits on a second generation.
@@ -237,7 +322,7 @@ export async function generateSunoSong(fields, deps = {}) {
const [songId] = songIds;
const bytes = await downloadSunoAudio(songId, deps);
const { filename, sizeBytes } = await importAudio(bytes);
- console.log(`🎵 Suno song ${songId.slice(0, 8)} imported as ${filename} (${Math.round(sizeBytes / 1024)} KB)`);
+ console.log(`🎵 Suno audio imported (${Math.round(sizeBytes / 1024)} KB)`);
return { songId, songIds, filename, sizeBytes };
}
diff --git a/server/services/musicVideo/autonomousSuno.test.js b/server/services/musicVideo/autonomousSuno.test.js
index 84c931a599..a639645fe5 100644
--- a/server/services/musicVideo/autonomousSuno.test.js
+++ b/server/services/musicVideo/autonomousSuno.test.js
@@ -2,13 +2,22 @@
* The Suno step with a fake browser page and a fake CDN. Pins what only this
* layer knows: a signed-out page is a login-required park (not a generic
* failure), songs already in the workspace are never mistaken for ours, audio
- * is accepted only once it stops growing, and a retry reuses submitted songs.
+ * requires decoding and verified completion, and a retry reuses submitted songs.
*/
import { EventEmitter } from 'node:events';
-import { describe, it, expect, vi } from 'vitest';
+import { mkdtemp, access } from 'fs/promises';
+import { findFfmpeg } from '../../lib/ffmpeg.js';
+import { describe, it, expect, vi, afterEach } from 'vitest';
import { __testing, generateSunoSong } from './autonomousSuno.js';
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, mkdtemp: vi.fn(actual.mkdtemp) };
+});
+const ffmpegAvailable = Boolean(await findFfmpeg());
+const completed = { checkCompletion: async () => 'complete', validateAudio: async () => true };
+
const { downloadSunoAudio, submitSunoSong } = __testing;
const OLD = '11111111-1111-1111-1111-111111111111';
@@ -127,27 +136,100 @@ describe('submitSunoSong', () => {
});
describe('downloadSunoAudio', () => {
+ afterEach(() => vi.useRealTimers());
const body = (size) => ({ ok: true, arrayBuffer: async () => new ArrayBuffer(size) });
- it('waits out a partial file: returns only once the size is stable and real', async () => {
+ it('selects stable candidates for decoding and verified completion', async () => {
const fetchImpl = vi.fn()
.mockResolvedValueOnce({ ok: false })
.mockResolvedValueOnce(body(1000)) // too small — a stub
.mockResolvedValueOnce(body(300 * 1024)) // growing
.mockResolvedValueOnce(body(400 * 1024))
.mockResolvedValueOnce(body(400 * 1024)); // stable
- const bytes = await downloadSunoAudio(NEW_A, { fetchImpl, sleep: noSleep, now: () => 0 });
+ const bytes = await downloadSunoAudio(NEW_A, { ...completed, fetchImpl, sleep: noSleep, now: () => 0 });
expect(bytes.length).toBe(400 * 1024);
expect(fetchImpl).toHaveBeenCalledTimes(5);
- expect(fetchImpl).toHaveBeenCalledWith(`https://cdn1.suno.ai/${NEW_A}.mp3`);
+ expect(fetchImpl).toHaveBeenCalledWith(`https://cdn1.suno.ai/${NEW_A}.mp3`, { signal: expect.any(AbortSignal) });
});
- it('gives up with a clear timeout naming the song when it never finishes', async () => {
+ it('times out with bounded diagnostics when it never finishes', async () => {
let t = 0;
await expect(downloadSunoAudio(NEW_A, {
fetchImpl: async () => ({ ok: false }), sleep: noSleep, intervalMs: 10, timeoutMs: 25, now: () => (t += 10),
- })).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: expect.objectContaining({ songId: NEW_A }) });
+ })).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: expect.objectContaining({ platform: 'Suno' }) });
+ });
+ it.each(['headers', 'body'])('aborts stalled %s at the overall deadline without leaking timers', async (phase) => {
+ vi.useFakeTimers();
+ let requestSignal;
+ let bodyAborted = false;
+ const fetchImpl = async (_url, { signal }) => {
+ requestSignal = signal;
+ const hang = () => new Promise((_resolve, reject) => signal.addEventListener('abort', () => {
+ bodyAborted = phase === 'body';
+ reject(signal.reason);
+ }, { once: true }));
+ if (phase === 'headers') return hang();
+ return { ok: true, status: 200, bodyUsed: true, arrayBuffer: hang };
+ };
+ const assertion = expect(downloadSunoAudio(NEW_A, { fetchImpl, timeoutMs: 100 })).rejects.toMatchObject({
+ code: 'SUNO_AUDIO_TIMEOUT', context: { reason: 'deadline_exceeded' },
+ });
+ await vi.advanceTimersByTimeAsync(100);
+ await assertion;
+ expect(requestSignal.aborted).toBe(true);
+ expect(bodyAborted).toBe(phase === 'body');
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('cancels unread HTTP error bodies before retrying', async () => {
+ let time = 0;
+ const cancel = vi.fn(async () => {});
+ await expect(downloadSunoAudio(NEW_A, {
+ fetchImpl: async () => ({ ok: false, status: 503, body: { cancel } }),
+ now: () => time, sleep: async (ms) => { time += ms; }, timeoutMs: 25, intervalMs: 10,
+ })).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: { httpStatus: 503 } });
+ expect(cancel).toHaveBeenCalledTimes(3);
+ });
+
+ it('never imports stable, decodable audio while generation is pending', async () => {
+ let time = 0;
+ const importAudio = vi.fn();
+ await expect(generateSunoSong({}, {
+ ...completed, checkCompletion: async () => 'pending', songIds: [NEW_A], importAudio,
+ fetchImpl: async () => body(200 * 1024), now: () => time,
+ sleep: async (ms) => { time += ms; }, timeoutMs: 25, intervalMs: 10,
+ })).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: { reason: 'generation_pending' } });
+ expect(importAudio).not.toHaveBeenCalled();
+ });
+
+ it('preserves unknown completion explicitly and never resubmits on retry', async () => {
+ const connect = vi.fn();
+ const importAudio = vi.fn();
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ await expect(generateSunoSong({}, {
+ songIds: [NEW_A], connect, importAudio, validateAudio: completed.validateAudio,
+ fetchImpl: async () => body(200 * 1024), sleep: noSleep,
+ })).rejects.toMatchObject({ code: 'SUNO_AUDIO_COMPLETION_UNVERIFIED' });
+ }
+ expect(connect).not.toHaveBeenCalled();
+ expect(importAudio).not.toHaveBeenCalled();
});
+
+ it('rejects large HTML responses and cancels unread content without importing', async () => {
+ const importAudio = vi.fn();
+ const cancel = vi.fn(async () => {});
+ const arrayBuffer = vi.fn(async () => Buffer.alloc(200 * 1024, '<'));
+ const error = await generateSunoSong({}, {
+ ...completed, songIds: [NEW_A], importAudio,
+ fetchImpl: async () => ({ ok: true, status: 200, headers: new Headers({ 'content-type': 'text/html' }), arrayBuffer, body: { cancel } }),
+ }).catch(error => error);
+ expect(error).toMatchObject({ code: 'SUNO_AUDIO_INVALID', context: { reason: 'non_audio_content' } });
+ expect(importAudio).not.toHaveBeenCalled();
+ expect(arrayBuffer).not.toHaveBeenCalled();
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(JSON.stringify({ message: error.message, context: error.context })).not.toContain(NEW_A);
+ });
+
});
describe('generateSunoSong', () => {
@@ -158,7 +240,7 @@ describe('generateSunoSong', () => {
it('submits once, downloads the first take and imports it', async () => {
const importAudio = vi.fn(async () => ({ filename: 'music-x.mp3', sizeBytes: 204800 }));
const onSubmitted = vi.fn();
- const out = await generateSunoSong(fields, { connect, importAudio, onSubmitted, fetchImpl: async () => audio, sleep: noSleep, intervalMs: 0 });
+ const out = await generateSunoSong(fields, { ...completed, connect, importAudio, onSubmitted, fetchImpl: async () => audio, sleep: noSleep, intervalMs: 0 });
expect(out).toMatchObject({ songId: NEW_A, songIds: [NEW_A, NEW_B], filename: 'music-x.mp3' });
expect(onSubmitted).toHaveBeenCalledWith([NEW_A, NEW_B]);
});
@@ -166,10 +248,47 @@ describe('generateSunoSong', () => {
it('with songs already submitted, never opens the browser — a retry spends no new credits', async () => {
const connectSpy = vi.fn(connect);
const out = await generateSunoSong(fields, {
- connect: connectSpy, importAudio: async () => ({ filename: 'm.mp3', sizeBytes: 1 }), songIds: [NEW_B],
+ ...completed, connect: connectSpy, importAudio: async () => ({ filename: 'm.mp3', sizeBytes: 1 }), songIds: [NEW_B],
fetchImpl: async () => audio, sleep: noSleep, intervalMs: 0,
});
expect(connectSpy).not.toHaveBeenCalled();
expect(out.songId).toBe(NEW_B);
});
});
+
+// Real decoder contract: synthetic PCM WAV avoids network calls and credits.
+describe.skipIf(!ffmpegAvailable)('Suno audio decoding', () => {
+ function wav() {
+ const frames = 96_000;
+ const bytes = Buffer.alloc(44 + frames * 2);
+ bytes.write('RIFF'); bytes.writeUInt32LE(bytes.length - 8, 4); bytes.write('WAVEfmt ', 8);
+ bytes.writeUInt32LE(16, 16); bytes.writeUInt16LE(1, 20); bytes.writeUInt16LE(1, 22);
+ bytes.writeUInt32LE(48_000, 24); bytes.writeUInt32LE(96_000, 28);
+ bytes.writeUInt16LE(2, 32); bytes.writeUInt16LE(16, 34);
+ bytes.write('data', 36); bytes.writeUInt32LE(frames * 2, 40);
+ for (let i = 0; i < frames; i++) bytes.writeInt16LE(Math.round(8000 * Math.sin(i * Math.PI / 60)), 44 + i * 2);
+ return bytes;
+ }
+
+ it.each(['valid', 'malformed', 'disguised-html'])('validates %s bytes before import and removes temporary artifacts', async (kind) => {
+ const bytes = kind === 'valid' ? wav() : Buffer.alloc(200 * 1024, kind === 'malformed' ? 0 : '<html>private-body');
+ const importAudio = vi.fn(async () => ({ filename: 'test.mp3', sizeBytes: bytes.length }));
+ const firstTemp = mkdtemp.mock.results.length;
+ const result = generateSunoSong({}, {
+ songIds: [NEW_A], importAudio, checkCompletion: async () => 'complete',
+ fetchImpl: async () => new Response(bytes, { headers: { 'content-type': 'audio/mpeg' } }), sleep: noSleep,
+ });
+ if (kind === 'valid') {
+ await expect(result).resolves.toMatchObject({ filename: 'test.mp3' });
+ expect(importAudio).toHaveBeenCalledWith(bytes);
+ } else {
+ const error = await result.catch(error => error);
+ expect(error).toMatchObject({ code: 'SUNO_AUDIO_INVALID', context: { reason: 'decode_failed' } });
+ expect(JSON.stringify({ message: error.message, context: error.context })).not.toMatch(/private-body|candidate|portos-suno-validation/);
+ expect(importAudio).not.toHaveBeenCalled();
+ }
+ const temps = mkdtemp.mock.results.slice(firstTemp);
+ expect(temps).toHaveLength(1);
+ for (const temp of temps) await expect(access(await temp.value)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+});