Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(tts): reject an unknown voice id and gate the voice clone route behind auth

nirholas01d81b6de444
diff --git a/api/_lib/voice-providers.js b/api/_lib/voice-providers.js
index 7f92f5f18..1edabbcc7 100644
--- a/api/_lib/voice-providers.js
+++ b/api/_lib/voice-providers.js
@@ -67,6 +67,7 @@ const OPENAI_FORMATS = {
const OPENAI_VOICE_IDS = new Set(TTS_VOICES.map((v) => v.id));
const NVIDIA_VOICE_IDS = new Set(Object.keys(VOICE_TO_MAGPIE));
+const GEMINI_VOICE_IDS = new Set(GEMINI_VOICES.map((v) => v.id));
const SYNTH_TIMEOUT_MS = 45_000;
@@ -270,6 +271,48 @@ export async function listProviderVoices(providerId, { elevenKey = null, byok =
}
}
+/**
+ * Does `voiceId` name a real voice on this lane?
+ *
+ * `synthesizeVoice` quietly swaps an unrecognized id for the lane default, which
+ * is the right behavior for an internal router but the wrong answer to a caller:
+ * a typo comes back as somebody else's voice, billed, with a 200. Handlers call
+ * this at the request boundary so a bad id fails as a 400 before anything is
+ * metered.
+ *
+ * An empty id means "use the lane default" and is always accepted. ElevenLabs is
+ * per-account and grows at runtime (cloning, library adds), so upstream stays the
+ * authority there. A lane whose catalog cannot be fetched fails open: a catalog
+ * outage must never block synthesis that would otherwise have worked.
+ *
+ * @param {string} providerId
+ * @param {string} voiceId
+ * @returns {Promise<boolean>}
+ */
+export async function isKnownVoice(providerId, voiceId) {
+ const id = String(voiceId || '').trim();
+ if (!id) return true;
+ switch (providerId) {
+ case 'edge': {
+ if (!EDGE_VOICE_RE.test(id)) return false;
+ try {
+ const { voices } = await listEdgeVoices();
+ return voices.some((v) => v.id === id);
+ } catch {
+ return true;
+ }
+ }
+ case 'gemini':
+ return GEMINI_VOICE_IDS.has(id);
+ case 'nvidia':
+ return NVIDIA_VOICE_IDS.has(id);
+ case 'openai':
+ return OPENAI_VOICE_IDS.has(id);
+ default:
+ return true;
+ }
+}
+
// ── Synthesis ────────────────────────────────────────────────────────────────
function tagged(message, code, extra = {}) {
diff --git a/api/tts/catalog.js b/api/tts/catalog.js
index b4bfac7d7..e948329a7 100644
--- a/api/tts/catalog.js
+++ b/api/tts/catalog.js
@@ -7,7 +7,7 @@
* actually render.
*
* Query:
- * provider=edge|gemini|nvidia|openai|elevenlabs restrict to one lane
+ * provider=edge|gemini|nvidia|openai|elevenlabs restrict to one lane (400 on an unknown id)
* q=<text> substring filter (name, locale, labels)
* language=<tag> e.g. "en", "ja"
* limit=<n> cap voices returned (default 400, max 2000)
@@ -26,11 +26,13 @@
* }
*/
-import { cors, json, method, wrap } from '../_lib/http.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { resolveElevenKey } from '../_lib/elevenlabs.js';
import {
VOICE_PROVIDERS,
+ PROVIDER_IDS,
+ getProvider,
providerAvailability,
providerModels,
providerDefaultVoice,
@@ -45,7 +47,18 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://localhost');
- const only = url.searchParams.get('provider');
+ const only = (url.searchParams.get('provider') || '').trim();
+ // An unrecognized provider used to answer 200 with an empty catalog, which the
+ // picker can only render as "no voices" with no way to tell a typo from a lane
+ // that is genuinely down. /api/tts/synthesize already rejects the same id.
+ if (only && !getProvider(only)) {
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ `unknown provider "${only}". Known lanes: ${PROVIDER_IDS.join(', ')}`,
+ );
+ }
const q = (url.searchParams.get('q') || '').trim().toLowerCase();
const language = (url.searchParams.get('language') || '').trim().toLowerCase();
const limit = Math.min(
diff --git a/api/tts/eleven-clone.js b/api/tts/eleven-clone.js
index f515f6dde..92e7a18fd 100644
--- a/api/tts/eleven-clone.js
+++ b/api/tts/eleven-clone.js
@@ -24,7 +24,7 @@
import { randomUUID } from 'node:crypto';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { cors, method, wrap, error, json, rateLimited } from '../_lib/http.js';
+import { cors, method, wrap, error, json, rateLimited, readBody } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { chargeCreditsForAction, refundCredits } from '../_lib/credits.js';
import { createClonedVoice, resolveElevenKey } from '../_lib/elevenlabs.js';
@@ -41,6 +41,13 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
+ // Identity first: this endpoint has no anonymous lane, so a signed-out caller
+ // gets a 401 rather than a reading of what this server has configured.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ const userId = session?.id ?? bearer.userId;
+
// A user-supplied x-eleven-key (BYOK) clones onto THAT user's ElevenLabs
// account: their quota, their bill, so the platform's daily cap is skipped.
const { apiKey, byok } = resolveElevenKey(req);
@@ -52,11 +59,6 @@ export default wrap(async (req, res) => {
'ElevenLabs is not configured on this server. Send your own key in the x-eleven-key header to use your account.',
);
- const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
- const userId = session?.id ?? bearer.userId;
-
// Platform-key clones consume limited IVC slots on the shared account, so
// even paid clones hold to the same 3/day abuse cap the agent-voice clone
// path enforces. (The per-clone credit charge happens further down, after
@@ -84,12 +86,9 @@ export default wrap(async (req, res) => {
raw = await readBody(req, MAX_REQUEST_BYTES);
} catch (err) {
const status = err.status || 400;
- return error(
- res,
- status,
- status === 413 ? 'payload_too_large' : 'bad_request',
- err.message,
- );
+ const code =
+ status === 413 ? 'payload_too_large' : status === 408 ? 'request_timeout' : 'bad_request';
+ return error(res, status, code, err.message);
}
let parts;
@@ -215,24 +214,6 @@ export default wrap(async (req, res) => {
// ── helpers ──────────────────────────────────────────────────────────────────
-function readBody(req, limit) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- let total = 0;
- req.on('data', (c) => {
- total += c.length;
- if (total > limit) {
- reject(Object.assign(new Error('payload too large'), { status: 413 }));
- req.destroy();
- return;
- }
- chunks.push(c);
- });
- req.on('end', () => resolve(Buffer.concat(chunks)));
- req.on('error', reject);
- });
-}
-
/**
* Minimal RFC 7578 multipart parser. Sufficient for the single-file + few
* scalar fields shape this endpoint accepts. Returns an array of
@@ -258,10 +239,9 @@ function parseMultipart(buf, boundary) {
const headerStr = buf.slice(pos, headersEnd).toString('utf8');
const dataStart = headersEnd + 4;
- const nextBoundary = buf.indexOf(
- crlf.length ? Buffer.concat([crlf, delim]) : delim,
- dataStart,
- );
+ // A part's payload ends at the CRLF immediately before the next boundary;
+ // that CRLF belongs to the delimiter, not to the data.
+ const nextBoundary = buf.indexOf(Buffer.concat([crlf, delim]), dataStart);
if (nextBoundary < 0) throw new Error('no closing boundary for part');
const data = buf.slice(dataStart, nextBoundary);
diff --git a/api/tts/synthesize.js b/api/tts/synthesize.js
index aaf493e05..d11745907 100644
--- a/api/tts/synthesize.js
+++ b/api/tts/synthesize.js
@@ -41,6 +41,7 @@ import { resolveElevenKey } from '../_lib/elevenlabs.js';
import {
getProvider,
providerAvailability,
+ isKnownVoice,
synthesizeVoice,
usdForSynthesis,
creditActionFor,
@@ -129,6 +130,21 @@ export default wrap(async (req, res) => {
const voiceSettings =
body.voice_settings && typeof body.voice_settings === 'object' ? body.voice_settings : null;
+ // A voiceId the lane does not have is a caller error, and it has to be caught
+ // here: the router would otherwise swap in the lane default and return 200,
+ // so a typo came back as a different voice, charged, with nothing in the
+ // response saying so. Checked before the cache key is minted and before any
+ // metering, so a bad id costs nothing. An omitted voiceId still means "lane
+ // default" and passes.
+ if (!(await isKnownVoice(providerId, voiceId))) {
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ `"${voiceId}" is not a ${provider.label} voice. Pick one from /api/tts/catalog?provider=${providerId}`,
+ );
+ }
+
// ── R2 cache ──────────────────────────────────────────────────────────────
// Checked BEFORE metering: a cached clip costs nothing upstream, so it is
// never charged. BYOK clips are keyed separately: they render on a