Skip to content

Commit 51c41c2

Browse files
steipetePeter Steinberger
andauthored
fix(minimax): validate complete generated audio at producer owners (#117195)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 0a146d5 commit 51c41c2

4 files changed

Lines changed: 233 additions & 29 deletions

File tree

‎extensions/minimax/media-provider-runtime.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,14 @@ export function assertMinimaxBaseResp(
3737
}
3838
}
3939

40+
export function normalizeMinimaxHexAudio(data: string, label: string): string {
41+
const normalized = data.trim();
42+
if (!/^[0-9a-f]+$/iu.test(normalized) || normalized.length % 2 !== 0) {
43+
throw new Error(`${label} returned malformed hex audio`);
44+
}
45+
return normalized;
46+
}
47+
4048
export function resolveMinimaxGuardedRequestOptions(
4149
policy: MinimaxRequestPolicy,
4250
): Parameters<typeof fetchWithTimeoutGuarded>[4] | undefined {

‎extensions/minimax/music-generation-provider.ts‎

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runti
2424
import {
2525
assertMinimaxBaseResp,
2626
DEFAULT_MINIMAX_MEDIA_BASE_URL,
27+
normalizeMinimaxHexAudio,
2728
resolveMinimaxGuardedRequestOptions,
2829
resolveMinimaxMediaBaseUrl,
2930
type MinimaxBaseResp,
@@ -58,10 +59,7 @@ type MinimaxMusicStreamFrame = {
5859
};
5960

6061
function decodeHexAudioWithLimit(data: string, maxBytes: number): Buffer {
61-
const trimmed = data.trim();
62-
if (!/^[0-9a-f]+$/iu.test(trimmed) || trimmed.length % 2 !== 0) {
63-
throw new Error("MiniMax music generation returned malformed hex audio");
64-
}
62+
const trimmed = normalizeMinimaxHexAudio(data, "MiniMax music generation");
6563
if (trimmed.length / 2 > maxBytes) {
6664
throw createGeneratedMusicTooLargeError(maxBytes);
6765
}
@@ -196,6 +194,7 @@ async function readStreamingTrack(
196194
}
197195
const chunks: Buffer[] = [];
198196
let decodedBytes = 0;
197+
let completed = false;
199198
const text = new TextDecoder().decode(
200199
await readResponseBufferWithDeadline(
201200
response,
@@ -214,20 +213,22 @@ async function readStreamingTrack(
214213
}
215214
const frame = JSON.parse(json) as MinimaxMusicStreamFrame;
216215
assertMinimaxBaseResp(frame.base_resp, "MiniMax music generation failed");
217-
const audio = normalizeOptionalString(frame.data?.audio);
218-
if (audio) {
219-
if (String(frame.data?.status ?? "") === "2" && chunks.length > 0) {
216+
if (String(frame.data?.status ?? "") === "2") {
217+
completed = true;
218+
if (chunks.length > 0) {
220219
continue;
221220
}
221+
}
222+
const audio = normalizeOptionalString(frame.data?.audio);
223+
if (audio) {
222224
const chunk = decodeHexAudioWithLimit(audio, maxBytes - decodedBytes);
223-
const nextDecodedBytes = decodedBytes + chunk.byteLength;
224-
if (nextDecodedBytes > maxBytes) {
225-
throw createGeneratedMusicTooLargeError(maxBytes);
226-
}
227225
chunks.push(chunk);
228-
decodedBytes = nextDecodedBytes;
226+
decodedBytes += chunk.byteLength;
229227
}
230228
}
229+
if (!completed) {
230+
throw new Error("MiniMax music generation stream ended without completion");
231+
}
231232
const buffer = Buffer.concat(chunks);
232233
if (buffer.byteLength === 0) {
233234
throw new Error("MiniMax music generation response missing audio output");
@@ -400,10 +401,6 @@ function buildMinimaxMusicProvider(providerId: string): MusicGenerationProvider
400401
};
401402
})()
402403
: await readStreamingTrack(res, deadline, maxGeneratedMusicBytes);
403-
if (!track) {
404-
throw new Error("MiniMax music generation response missing audio output");
405-
}
406-
407404
return {
408405
tracks: [track],
409406
...(responseLyrics ? { lyrics: [responseLyrics] } : {}),

‎extensions/minimax/tts.test.ts‎

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
// Minimax tests cover tts plugin behavior.
2+
import { createServer } from "node:http";
3+
import type { AddressInfo } from "node:net";
24
import { MAX_TIMER_TIMEOUT_MS } from "openclaw/plugin-sdk/number-runtime";
35
import { afterEach, describe, expect, it, vi } from "vitest";
46

@@ -12,6 +14,11 @@ vi.mock("openclaw/plugin-sdk/ssrf-runtime", async (importOriginal) => {
1214
};
1315
});
1416

17+
import {
18+
buildMinimaxMusicGenerationProvider,
19+
buildMinimaxPortalMusicGenerationProvider,
20+
} from "./music-generation-provider.js";
21+
import { buildMinimaxSpeechProvider } from "./speech-provider.js";
1522
import { minimaxTTS } from "./tts.js";
1623

1724
describe("minimaxTTS", () => {
@@ -120,3 +127,205 @@ describe("minimaxTTS", () => {
120127
expect(audio.toString()).toBe("real-audio");
121128
});
122129
});
130+
131+
type MinimaxWireFixture = {
132+
entryPoint: "tts" | "speech" | "music";
133+
provider?: "minimax" | "minimax-portal";
134+
audio?: string;
135+
frames?: Array<{ status?: number | string; audio?: string } | "[DONE]">;
136+
mediaMaxMb?: number;
137+
};
138+
139+
async function runMinimaxLoopbackFixture(fixture: MinimaxWireFixture): Promise<Buffer> {
140+
const originalFetch = globalThis.fetch;
141+
const server = createServer((request, response) => {
142+
request.resume();
143+
if (fixture.entryPoint === "music") {
144+
response.writeHead(200, { "content-type": "text/event-stream" });
145+
response.end(
146+
fixture.frames
147+
?.map((frame) =>
148+
frame === "[DONE]"
149+
? "data: [DONE]"
150+
: `data: ${JSON.stringify({
151+
data: frame,
152+
base_resp: { status_code: 0, status_msg: "success" },
153+
})}`,
154+
)
155+
.join("\n\n") + "\n\n",
156+
);
157+
return;
158+
}
159+
response.writeHead(200, { "content-type": "application/json" });
160+
response.end(
161+
JSON.stringify({
162+
data: { audio: fixture.audio, status: 2 },
163+
base_resp: { status_code: 0, status_msg: "success" },
164+
}),
165+
);
166+
});
167+
await new Promise<void>((resolve, reject) => {
168+
server.once("error", reject);
169+
server.listen(0, "127.0.0.1", resolve);
170+
});
171+
const { port } = server.address() as AddressInfo;
172+
const pathname = fixture.entryPoint === "music" ? "/v1/music_generation" : "/v1/t2a_v2";
173+
174+
vi.stubEnv("MINIMAX_API_KEY", "fixture-provider-key");
175+
vi.spyOn(globalThis, "fetch").mockImplementation(async (_input, init) => {
176+
const { dispatcher: _dispatcher, ...forwardedInit } = (init ?? {}) as RequestInit & {
177+
dispatcher?: unknown;
178+
};
179+
return originalFetch(`http://127.0.0.1:${port}${pathname}`, forwardedInit);
180+
});
181+
fetchWithSsrFGuardMock.mockImplementation(async ({ url, init }) => ({
182+
response: await fetch(url, init),
183+
release: async () => {},
184+
}));
185+
186+
try {
187+
if (fixture.entryPoint === "tts") {
188+
return await minimaxTTS({
189+
text: "loopback fixture",
190+
apiKey: "fixture-provider-key",
191+
baseUrl: "https://api.minimax.io",
192+
model: "speech-2.8-hd",
193+
voiceId: "English_expressive_narrator",
194+
timeoutMs: 1_000,
195+
});
196+
}
197+
if (fixture.entryPoint === "speech") {
198+
const result = await buildMinimaxSpeechProvider().synthesize({
199+
text: "loopback fixture",
200+
cfg: {},
201+
providerConfig: { apiKey: "fixture-provider-key", baseUrl: "https://api.minimax.io" },
202+
target: "audio-file",
203+
timeoutMs: 1_000,
204+
});
205+
return result.audioBuffer;
206+
}
207+
208+
const providerId = fixture.provider ?? "minimax";
209+
const provider =
210+
providerId === "minimax-portal"
211+
? buildMinimaxPortalMusicGenerationProvider()
212+
: buildMinimaxMusicGenerationProvider();
213+
const result = await provider.generateMusic({
214+
provider: providerId,
215+
model: "music-2.6",
216+
prompt: "loopback fixture",
217+
cfg:
218+
fixture.mediaMaxMb === undefined
219+
? {}
220+
: { agents: { defaults: { mediaMaxMb: fixture.mediaMaxMb } } },
221+
});
222+
const track = result.tracks[0];
223+
if (!track) {
224+
throw new Error("Music provider returned no track");
225+
}
226+
return track.buffer;
227+
} finally {
228+
await new Promise<void>((resolve, reject) => {
229+
server.close((error) => {
230+
if (error) {
231+
reject(error);
232+
return;
233+
}
234+
resolve();
235+
});
236+
});
237+
fetchWithSsrFGuardMock.mockReset();
238+
vi.unstubAllEnvs();
239+
vi.restoreAllMocks();
240+
}
241+
}
242+
243+
describe("MiniMax media producers through real localhost HTTP", () => {
244+
it.each([
245+
{ name: "trailing non-hex", audio: "666f6fZZ" },
246+
{ name: "odd-length hex", audio: "666f6" },
247+
{ name: "entirely non-hex", audio: "ZZ" },
248+
])("rejects $name TTS audio without truncating it", async ({ audio }) => {
249+
await expect(runMinimaxLoopbackFixture({ entryPoint: "tts", audio })).rejects.toThrow(
250+
"MiniMax TTS API returned malformed hex audio",
251+
);
252+
});
253+
254+
it("reports malformed audio through the user-facing speech provider", async () => {
255+
await expect(
256+
runMinimaxLoopbackFixture({ entryPoint: "speech", audio: "666f6fZZ" }),
257+
).rejects.toThrow("MiniMax TTS API returned malformed hex audio");
258+
});
259+
260+
it.each([
261+
{ provider: "minimax" as const, done: false },
262+
{ provider: "minimax-portal" as const, done: true },
263+
])(
264+
"rejects incomplete $provider music after its HTTP stream closes",
265+
async ({ provider, done }) => {
266+
const frames: MinimaxWireFixture["frames"] = [
267+
{ status: 1, audio: Buffer.from("partial-audio").toString("hex") },
268+
...(done ? (["[DONE]"] as const) : []),
269+
];
270+
await expect(
271+
runMinimaxLoopbackFixture({ entryPoint: "music", provider, frames }),
272+
).rejects.toThrow("MiniMax music generation stream ended without completion");
273+
},
274+
);
275+
276+
it.each([{ status: 2 }, { status: "2" }])(
277+
"accepts a terminal music frame with status $status",
278+
async ({ status }) => {
279+
const audio = Buffer.from("complete-audio");
280+
await expect(
281+
runMinimaxLoopbackFixture({
282+
entryPoint: "music",
283+
frames: [{ status, audio: audio.toString("hex") }],
284+
}),
285+
).resolves.toEqual(audio);
286+
},
287+
);
288+
289+
it("preserves progressive audio when its terminal frame repeats the aggregate", async () => {
290+
const first = Buffer.from("first-");
291+
const second = Buffer.from("second");
292+
await expect(
293+
runMinimaxLoopbackFixture({
294+
entryPoint: "music",
295+
provider: "minimax-portal",
296+
frames: [
297+
{ status: 1, audio: first.toString("hex") },
298+
{ status: 1, audio: second.toString("hex") },
299+
{ status: 2, audio: Buffer.concat([first, second]).toString("hex") },
300+
],
301+
}),
302+
).resolves.toEqual(Buffer.concat([first, second]));
303+
});
304+
305+
it("accepts a terminal status without audio after progressive audio", async () => {
306+
const audio = Buffer.from("complete-progress");
307+
await expect(
308+
runMinimaxLoopbackFixture({
309+
entryPoint: "music",
310+
frames: [{ status: 1, audio: audio.toString("hex") }, { status: 2 }, "[DONE]"],
311+
}),
312+
).resolves.toEqual(audio);
313+
});
314+
315+
it("keeps the configured music byte limit before decoding terminal audio", async () => {
316+
await expect(
317+
runMinimaxLoopbackFixture({
318+
entryPoint: "music",
319+
frames: [{ status: 2, audio: Buffer.from("oversized").toString("hex") }],
320+
mediaMaxMb: 0.000_001,
321+
}),
322+
).rejects.toThrow("MiniMax generated music download exceeds 1 bytes");
323+
});
324+
325+
it("keeps valid speech-provider audio unchanged", async () => {
326+
const audio = Buffer.from("complete-audio");
327+
await expect(
328+
runMinimaxLoopbackFixture({ entryPoint: "speech", audio: audio.toString("hex") }),
329+
).resolves.toEqual(audio);
330+
});
331+
});

‎extensions/minimax/tts.ts‎

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
fetchWithSsrFGuard,
99
ssrfPolicyFromHttpBaseUrlAllowedHostname,
1010
} from "openclaw/plugin-sdk/ssrf-runtime";
11+
import { assertMinimaxBaseResp, normalizeMinimaxHexAudio } from "./media-provider-runtime.js";
1112

1213
export const DEFAULT_MINIMAX_TTS_BASE_URL = "https://api.minimax.io";
1314

@@ -112,24 +113,13 @@ export async function minimaxTTS(params: {
112113
base_resp?: { status_code?: number; status_msg?: string };
113114
}>(response, "minimax.tts");
114115

115-
// Check base_resp for envelope errors (HTTP 200 with non-zero status_code).
116-
// Other MiniMax providers (image, video, music, web-search) already check this.
117-
// Without this check, quota/billing errors with placeholder audio are silently accepted.
118-
if (
119-
body.base_resp &&
120-
typeof body.base_resp.status_code === "number" &&
121-
body.base_resp.status_code !== 0
122-
) {
123-
const msg = body.base_resp.status_msg ?? "unknown error";
124-
throw new Error(`MiniMax TTS API error (${body.base_resp.status_code}): ${msg}`);
125-
}
126-
116+
assertMinimaxBaseResp(body.base_resp, "MiniMax TTS API error");
127117
const hexAudio = body?.data?.audio;
128118
if (!hexAudio) {
129119
throw new Error("MiniMax TTS API returned no audio data");
130120
}
131121

132-
return Buffer.from(hexAudio, "hex");
122+
return Buffer.from(normalizeMinimaxHexAudio(hexAudio, "MiniMax TTS API"), "hex");
133123
} finally {
134124
await release();
135125
}

0 commit comments

Comments
 (0)