Skip to content

Commit 65d6481

Browse files
Yigtwxxsteipete
andauthored
fix(tts): reject non-audio speech synthesis responses (#117345)
* fix(tts): reject non-audio speech synthesis responses A successful HTTP 200 carrying a JSON error, an HTML sign-in page, or a zero-byte body was returned as an audio buffer and written out as a playable attachment. Route the xAI, Gradium, and Azure Speech synthesizers through the shared binary-response contract that the OpenAI-compatible speech provider already uses, so the media kind is validated before the body is read and the unread body is canceled when it is rejected. Each provider keeps its own overflow wording, so operator-facing messages are unchanged apart from the new malformed-response rejection. * test(azure-speech): prove the audio guard closes a real upstream socket Adds a loopback node:http server that answers 200 with a JSON content type and then never ends the body, driven through the real azureSpeechTTS path with the real global fetch and no stubbed transport. Without the guard the synthesis hangs to its timeout with the socket still open; with it the response is rejected immediately and the server observes the close. * fix(openai): reject malformed binary speech responses --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent dc7a752 commit 65d6481

8 files changed

Lines changed: 233 additions & 5 deletions

File tree

‎extensions/azure-speech/tts.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
// Azure Speech tests cover tts plugin behavior.
2+
import { createServer } from "node:http";
3+
import type { AddressInfo } from "node:net";
24
import { installPinnedHostnameTestHooks } from "openclaw/plugin-sdk/test-media-understanding";
35
import { afterEach, describe, expect, it, vi } from "vitest";
46
import {
@@ -226,4 +228,73 @@ describe("azure speech tts", () => {
226228
},
227229
]);
228230
});
231+
it.each([
232+
{ name: "JSON error", contentType: "application/json", body: '{"error":"denied"}' },
233+
{ name: "problem JSON", contentType: "application/problem+json", body: '{"title":"denied"}' },
234+
{ name: "HTML", contentType: "text/html; charset=utf-8", body: "<html>sign in</html>" },
235+
{ name: "empty audio", contentType: "audio/mpeg", body: "" },
236+
])("rejects a successful $name response as synthesized audio", async ({ contentType, body }) => {
237+
const fetchMock = vi
238+
.fn()
239+
.mockResolvedValue(
240+
new Response(body, { status: 200, headers: { "content-type": contentType } }),
241+
);
242+
vi.stubGlobal("fetch", fetchMock);
243+
244+
await expect(
245+
azureSpeechTTS({
246+
text: "hello",
247+
apiKey: "fixture-value",
248+
region: "eastus",
249+
voice: "en-US-JennyNeural",
250+
lang: "en-US",
251+
outputFormat: "audio-24khz-48kbitrate-mono-mp3",
252+
timeoutMs: 5_000,
253+
}),
254+
).rejects.toThrow("Azure Speech TTS API error: malformed audio response");
255+
});
256+
257+
it("closes the upstream socket for a never-ending malformed response over a real connection", async () => {
258+
let notifySocketClosed: ((closed: boolean) => void) | undefined;
259+
const socketClosed = new Promise<boolean>((resolve) => {
260+
notifySocketClosed = resolve;
261+
});
262+
const server = createServer((request, response) => {
263+
request.socket.once("close", () => notifySocketClosed?.(true));
264+
response.writeHead(200, { "content-type": "application/json" });
265+
// Headers land, then the body never ends: only an explicit cancel closes this.
266+
response.write('{"error":"still streaming');
267+
});
268+
await new Promise<void>((resolve) => {
269+
server.listen(0, "127.0.0.1", resolve);
270+
});
271+
272+
try {
273+
const { port } = server.address() as AddressInfo;
274+
await expect(
275+
azureSpeechTTS({
276+
text: "hello",
277+
apiKey: "fixture-value",
278+
endpoint: `http://127.0.0.1:${port}`,
279+
voice: "en-US-JennyNeural",
280+
lang: "en-US",
281+
timeoutMs: 5_000,
282+
}),
283+
).rejects.toThrow("Azure Speech TTS API error: malformed audio response");
284+
285+
await expect(
286+
Promise.race([
287+
socketClosed,
288+
new Promise<boolean>((resolve) => {
289+
setTimeout(() => resolve(false), 250);
290+
}),
291+
]),
292+
).resolves.toBe(true);
293+
} finally {
294+
server.closeAllConnections();
295+
await new Promise<void>((resolve, reject) => {
296+
server.close((error) => (error ? reject(error) : resolve()));
297+
});
298+
}
299+
});
229300
});

‎extensions/azure-speech/tts.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*/
55
import {
66
assertOkOrThrowProviderError,
7+
assertProviderBinaryResponseContent,
78
readProviderJsonResponse,
89
} from "openclaw/plugin-sdk/provider-http";
910
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
@@ -221,14 +222,26 @@ export async function azureSpeechTTS(params: {
221222

222223
try {
223224
await assertOkOrThrowProviderError(response, "Azure Speech TTS API error");
224-
return await readResponseWithLimit(
225+
try {
226+
assertProviderBinaryResponseContent(response, "Azure Speech TTS API error", "audio");
227+
} catch (error) {
228+
// A debug-capture clone can keep the tee open, so waiting for cancel would hang
229+
// before the rejected response and its dispatcher can be released.
230+
void response.body?.cancel().catch(() => undefined);
231+
throw error;
232+
}
233+
const audio = await readResponseWithLimit(
225234
response,
226235
params.maxBytes ?? DEFAULT_AZURE_SPEECH_MAX_BYTES,
227236
{
228237
onOverflow: ({ maxBytes }) =>
229238
new Error(`Azure Speech TTS audio response exceeds ${maxBytes} bytes`),
230239
},
231240
);
241+
if (audio.byteLength === 0) {
242+
throw new Error("Azure Speech TTS API error: malformed audio response");
243+
}
244+
return audio;
232245
} finally {
233246
await release();
234247
}

‎extensions/gradium/tts.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,4 +226,28 @@ describe("gradium tts diagnostics", () => {
226226

227227
expect(streamed.getReadCount()).toBeLessThan(20);
228228
});
229+
it.each([
230+
{ name: "JSON error", contentType: "application/json", body: '{"error":"denied"}' },
231+
{ name: "problem JSON", contentType: "application/problem+json", body: '{"title":"denied"}' },
232+
{ name: "HTML", contentType: "text/html; charset=utf-8", body: "<html>sign in</html>" },
233+
{ name: "empty audio", contentType: "audio/mpeg", body: "" },
234+
])("rejects a successful $name response as synthesized audio", async ({ contentType, body }) => {
235+
const fetchMock = vi
236+
.fn()
237+
.mockResolvedValue(
238+
new Response(body, { status: 200, headers: { "content-type": contentType } }),
239+
);
240+
vi.stubGlobal("fetch", fetchMock);
241+
242+
await expect(
243+
gradiumTTS({
244+
text: "hello",
245+
apiKey: "ok-key",
246+
baseUrl: "https://api.gradium.ai",
247+
voiceId: "YTpq7expH9539ERJ",
248+
outputFormat: "wav",
249+
timeoutMs: 5_000,
250+
}),
251+
).rejects.toThrow("Gradium API error: malformed audio response");
252+
});
229253
});

‎extensions/gradium/tts.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// Gradium plugin module implements tts behavior.
2-
import { assertOkOrThrowProviderError } from "openclaw/plugin-sdk/provider-http";
2+
import {
3+
assertOkOrThrowProviderError,
4+
assertProviderBinaryResponseContent,
5+
} from "openclaw/plugin-sdk/provider-http";
36
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
47
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
58
import { GRADIUM_API_HOSTNAME, normalizeGradiumBaseUrl } from "./shared.js";
@@ -54,10 +57,22 @@ export async function gradiumTTS(params: {
5457
try {
5558
await assertOkOrThrowProviderError(response, "Gradium API error");
5659

57-
return await readResponseWithLimit(response, maxBytes, {
60+
try {
61+
assertProviderBinaryResponseContent(response, "Gradium API error", "audio");
62+
} catch (error) {
63+
// A debug-capture clone can keep the tee open, so waiting for cancel would hang
64+
// before the rejected response and its dispatcher can be released.
65+
void response.body?.cancel().catch(() => undefined);
66+
throw error;
67+
}
68+
const audio = await readResponseWithLimit(response, maxBytes, {
5869
onOverflow: ({ maxBytes: maxBytesLocal }) =>
5970
new Error(`Gradium TTS audio response exceeds ${maxBytesLocal} bytes`),
6071
});
72+
if (audio.byteLength === 0) {
73+
throw new Error("Gradium API error: malformed audio response");
74+
}
75+
return audio;
6176
} finally {
6277
await release();
6378
}

‎extensions/openai/tts.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,60 @@ describe("openai tts", () => {
306306
).rejects.toThrow("OpenAI TTS API error (503): temporary upstream outage");
307307
});
308308

309+
it.each([
310+
{ name: "JSON error", contentType: "application/json", body: '{"error":"denied"}' },
311+
{ name: "problem JSON", contentType: "application/problem+json", body: '{"title":"denied"}' },
312+
{ name: "HTML", contentType: "text/html; charset=utf-8", body: "<html>sign in</html>" },
313+
{ name: "empty audio", contentType: "audio/mpeg", body: "" },
314+
])(
315+
"rejects a successful $name response as synthesized audio",
316+
async ({ contentType, body }) => {
317+
globalThis.fetch = vi
318+
.fn()
319+
.mockResolvedValue(
320+
new Response(body, { status: 200, headers: { "content-type": contentType } }),
321+
) as unknown as typeof fetch;
322+
323+
await expect(
324+
openaiTTS({
325+
text: "hello",
326+
apiKey: "test-key",
327+
baseUrl: "https://api.openai.com/v1",
328+
model: "gpt-4o-mini-tts",
329+
voice: "alloy",
330+
responseFormat: "mp3",
331+
timeoutMs: 5_000,
332+
}),
333+
).rejects.toThrow("OpenAI TTS API error: malformed audio response");
334+
},
335+
);
336+
337+
it.each([
338+
{ name: "audio content type", contentType: "audio/mpeg" },
339+
{ name: "generic binary content type", contentType: "application/octet-stream" },
340+
{ name: "missing content type", contentType: undefined },
341+
])("preserves nonempty $name speech responses", async ({ contentType }) => {
342+
const audio = Buffer.from("audio-bytes");
343+
globalThis.fetch = vi.fn().mockResolvedValue(
344+
new Response(audio, {
345+
status: 200,
346+
...(contentType ? { headers: { "content-type": contentType } } : {}),
347+
}),
348+
) as unknown as typeof fetch;
349+
350+
await expect(
351+
openaiTTS({
352+
text: "hello",
353+
apiKey: "test-key",
354+
baseUrl: "https://api.openai.com/v1",
355+
model: "gpt-4o-mini-tts",
356+
voice: "alloy",
357+
responseFormat: "mp3",
358+
timeoutMs: 5_000,
359+
}),
360+
).resolves.toEqual(audio);
361+
});
362+
309363
it("caps streamed audio responses instead of buffering oversized TTS output", async () => {
310364
const streamed = createStreamingErrorResponse({
311365
status: 200,

‎extensions/openai/tts.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Openai plugin module implements tts behavior.
22
import {
33
assertOkOrThrowProviderError,
4+
assertProviderBinaryResponseContent,
45
resolveProviderRequestHeaders,
56
} from "openclaw/plugin-sdk/provider-http";
67
import {
@@ -182,10 +183,22 @@ export async function openaiTTS(params: {
182183

183184
await assertOkOrThrowProviderError(response, "OpenAI TTS API error");
184185

185-
return await readResponseWithLimit(response, maxBytes, {
186+
try {
187+
assertProviderBinaryResponseContent(response, "OpenAI TTS API error", "audio");
188+
} catch (error) {
189+
// Capture may clone and tee this response; awaiting cancellation would
190+
// deadlock before the rejected response and dispatcher can be released.
191+
void response.body?.cancel().catch(() => undefined);
192+
throw error;
193+
}
194+
const audio = await readResponseWithLimit(response, maxBytes, {
186195
onOverflow: ({ maxBytes: maxBytesLocal }) =>
187196
new Error(`OpenAI TTS audio response exceeds ${maxBytesLocal} bytes`),
188197
});
198+
if (audio.byteLength === 0) {
199+
throw new Error("OpenAI TTS API error: malformed audio response");
200+
}
201+
return audio;
189202
} finally {
190203
await release();
191204
}

‎extensions/xai/tts.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -644,4 +644,29 @@ describe("xai tts", () => {
644644
).rejects.toThrow("xAI TTS API error (503): temporary upstream outage");
645645
});
646646
});
647+
it.each([
648+
{ name: "JSON error", contentType: "application/json", body: '{"error":"denied"}' },
649+
{ name: "problem JSON", contentType: "application/problem+json", body: '{"title":"denied"}' },
650+
{ name: "HTML", contentType: "text/html; charset=utf-8", body: "<html>sign in</html>" },
651+
{ name: "empty audio", contentType: "audio/mpeg", body: "" },
652+
])("rejects a successful $name response as synthesized audio", async ({ contentType, body }) => {
653+
const fetchMock = vi
654+
.fn()
655+
.mockResolvedValue(
656+
new Response(body, { status: 200, headers: { "content-type": contentType } }),
657+
);
658+
globalThis.fetch = fetchMock as unknown as typeof fetch;
659+
660+
await expect(
661+
xaiTTS({
662+
text: "hello",
663+
apiKey: "ok-key",
664+
baseUrl: XAI_BASE_URL,
665+
voiceId: "eve",
666+
language: "en",
667+
responseFormat: "mp3",
668+
timeoutMs: 5_000,
669+
}),
670+
).rejects.toThrow("xAI TTS API error: malformed audio response");
671+
});
647672
});

‎extensions/xai/tts.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { canonicalizeBase64 } from "openclaw/plugin-sdk/media-runtime";
33
import {
44
assertOkOrThrowProviderError,
5+
assertProviderBinaryResponseContent,
56
postJsonRequest,
67
readProviderJsonResponse,
78
} from "openclaw/plugin-sdk/provider-http";
@@ -505,10 +506,22 @@ export async function xaiTTS(params: {
505506
try {
506507
await assertOkOrThrowProviderError(response, "xAI TTS API error");
507508

508-
return await readResponseWithLimit(response, maxBytes, {
509+
try {
510+
assertProviderBinaryResponseContent(response, "xAI TTS API error", "audio");
511+
} catch (error) {
512+
// A debug-capture clone can keep the tee open, so waiting for cancel would hang
513+
// before the rejected response and its dispatcher can be released.
514+
void response.body?.cancel().catch(() => undefined);
515+
throw error;
516+
}
517+
const audio = await readResponseWithLimit(response, maxBytes, {
509518
onOverflow: ({ maxBytes: maxBytesLocal }) =>
510519
new Error(`xAI TTS audio response exceeds ${maxBytesLocal} bytes`),
511520
});
521+
if (audio.byteLength === 0) {
522+
throw new Error("xAI TTS API error: malformed audio response");
523+
}
524+
return audio;
512525
} finally {
513526
await release();
514527
}

0 commit comments

Comments
 (0)