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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(voice): bring-your-own ElevenLabs key, and meter TTS overage to $THREE credits
nirholas07cbf34e4858
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b432fa03..60fdfc3ad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,7 +6,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-08-06+- **Docs · Wallet Portfolio** (`/docs/portfolio`): How the live wallet portfolio works: the keyless Solana-first data sources behind /api/crypto/portfolio, the stable/major/token classification, the honest 24h coverage contract, and the full response shape for agents and scripts.- **Sign Mirror** (`/sign-mirror`): Learn the ASL alphabet by making it: the avatar forms the letter, your camera watches your hand, and the page grades the handshape live, naming the finger that is off. Fully on-device; no video ever uploaded.+- **Wallet Portfolio** (`/portfolio`): A live portfolio view for any Solana or Ethereum wallet: total value, 24h move with honest coverage, stablecoin/major/token breakdown, top-asset allocation, and every holding priced in real time. Free, keyless, deep-linkable, no account.- **A dry Agora wallet now tells you which address to fund**: Posting your first bounty could fail with an unreadable blockchain error. Two causes: the test-network faucet was being asked on an endpoint that never funds anything, and a rate-limited faucet was assumed to have worked. Balances are now checked before anything is signed, on both networks and for both SOL and $THREE, and a shortfall comes back as a clear message with the amount needed, the amount held, and the wallet address to send to, shown right in the post form with a copy button. (`/agora`) `[fix]`- **A mirror that grades your fingerspelling, without your camera leaving the room**: Learning the manual alphabet has two halves, and until now three.ws only taught the easier one: watching an avatar form the letters. The new Sign Mirror page teaches the other half, making them yourself. The avatar forms the target letter, your camera watches your hand, and the page scores your handshape live, finger by finger. Hold the shape and the letter passes; hold it wrong and it names the finger to fix, and when your hand is cleanly forming a different letter it tells you which one it sees. The alphabet is arranged as a short course, easiest shapes first, with the famously confusable pairs saved for when you are ready, and your progress stays on your device. The privacy line is absolute: the hand tracking runs inside your browser tab, the grading is simple arithmetic, and no video frame, hand position, or score is ever uploaded. There is no network call in the practice loop at all, which also makes it fit for classrooms. (`/sign-mirror`) `[feature]`- **A paced payment rail now says "retry shortly" instead of reporting itself broken**: When the wallet that pays Solana network fees for platform payments has spent its daily fee budget, settlement pauses on purpose until the budget refills at the UTC reset or the wallet is topped up. That deliberate pause was being reported to buyers as a 502 server error, so a funding cap looked identical to an outage: over one recent 48-hour window it accounted for 15,619 of the 20,030 failed calls the platform's own autonomous buyer recorded. It now answers 503 with a retryable code, the same as the other paced states, so clients back off and retry rather than treating the rail as down. Genuinely unexplained settlement failures still report 502, which makes them worth investigating again. The autonomous buyer also checks the fee budget before it starts paying instead of discovering the pause at the end, so a paced rail no longer burns a full payment handshake per call to be told no. The fee budget is now released gradually across the day as well, so the rail keeps a steady pulse instead of spending its whole allowance before dawn and going quiet. (`/economy-lab`) `[fix, improvement]`@@ -52,6 +54,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The public discovery manifest now says plainly which three.ws capabilities are free**: AI assistants and crawlers read the manifest at /.well-known/ai-plugin.json to learn what three.ws does, and it used to describe everything, 3D generation included, as a pay-per-call service. It now leads with the free, keyless lane (text-to-3D model and avatar generation, the browser viewer, the augmented-reality launcher, and the read-only market data endpoints, none of which need an account or an API key) and presents the optional pay-per-call catalog separately after it. The manifest also carries the real 512x512 three.ws brand mark instead of the favicon, and links the terms of service directly instead of the site root. `[improvement, docs]`- **The three.ws 3D Studio GPT now explains why a generation was refused**: When the free text-to-3D custom GPT hit a rate limit or asked about a job without a handle, three.ws answered with a body the GPT had no field to read, so ChatGPT showed the user nothing useful. Those replies now carry the plain-language message the published Actions contract promises, so the assistant can say what happened and when to try again. A new contract test validates every response the endpoint can produce against the OpenAPI schema three.ws serves, so the two cannot drift apart again. `[fix]`- **Trading swarm actions now carry the same protections as every other money action**: Contributing to or exiting a trading swarm moves real SOL out of a custodial wallet, and pausing or killing one changes a live treasury's mandate, but those actions were missing two guards the rest of the platform's money actions have had. They now require the same anti-forgery token, so another website cannot make a request on your behalf while you are signed in, and they are capped at the same rate an agent trade is, in their own budget so an active trader can never rate-limit their own swarm. `[security]`+- **Voice Lab: bring your own ElevenLabs key, or pay for extra speech with $THREE credits**: Voice cloning and speech now have three clear lanes. Everyone keeps a free lane on the platform account: 3 voice clones a day and 1,000 spoken characters an hour, with cached clips always free. When the free hour is spent, speech keeps working and is metered to your prepaid credit balance (top up with $THREE or SOL at /credits) at $0.30 per 1,000 characters, refunded automatically if a clip fails. And anyone with their own ElevenLabs account can paste their API key into the new card on the Voice Lab page to run cloning and speech entirely on their account, with no platform limits; the key stays in your browser and is never stored on our servers. (`/voice`) `[feature, improvement]`## 2026-08-05diff --git a/api/_lib/elevenlabs.js b/api/_lib/elevenlabs.jsindex 1ce0535d8..cd485154b 100644--- a/api/_lib/elevenlabs.js+++ b/api/_lib/elevenlabs.js@@ -62,6 +62,30 @@ export function isConfigured() {return !!env.ELEVENLABS_API_KEY;}+// ── BYOK (bring your own key) ────────────────────────────────────────────────+// Users can supply their own ElevenLabs API key per request via the+// `x-eleven-key` header. A user key routes the call to THEIR ElevenLabs+// account (their voices, their quota, their bill), so the platform's char+// budget and credit metering do not apply. The key is used for the one request+// and never stored server-side.++const USER_KEY_MAX_LEN = 256;++/**+ * Resolve the API key for a request: a valid `x-eleven-key` header wins,+ * otherwise the platform key. Returns { apiKey, byok } where apiKey may be+ * null when neither is available.+ * @param {import('http').IncomingMessage} req+ */+export function resolveElevenKey(req) {+ const raw = req?.headers?.['x-eleven-key'];+ const userKey = typeof raw === 'string' ? raw.trim() : '';+ if (userKey && userKey.length <= USER_KEY_MAX_LEN && /^[\x21-\x7e]+$/.test(userKey)) {+ return { apiKey: userKey, byok: true };+ }+ return { apiKey: elevenApiKey(), byok: false };+}+/** Build an Error tagged with an HTTP status (and optional upstream detail). */function upstreamError(message, status, extra = {}) {return Object.assign(new Error(message), { status, ...extra });@@ -81,14 +105,17 @@ export function invalidateVoiceCache() {/*** Fetch the account's voices, filtered to safe public fields.+ * A user-supplied `apiKey` (BYOK) reads that user's own account and bypasses+ * the shared per-instance cache, so one user's catalog never leaks to another.* @returns {Promise<{ voices: Array, cached: boolean }>}* @throws {Error & { status:number }} 503 when unconfigured, 502 on upstream failure.*/-export async function listVoices({ force = false } = {}) {- const apiKey = elevenApiKey();+export async function listVoices({ force = false, apiKey: keyOverride = null } = {}) {+ const apiKey = keyOverride || elevenApiKey();if (!apiKey) throw upstreamError('ElevenLabs is not configured', 503);+ const shareCache = !keyOverride || keyOverride === elevenApiKey();- if (!force && voiceCache && Date.now() - voiceCache.at < VOICE_TTL_MS) {+ if (shareCache && !force && voiceCache && Date.now() - voiceCache.at < VOICE_TTL_MS) {return { voices: voiceCache.voices, cached: true };}@@ -112,22 +139,23 @@ export async function listVoices({ force = false } = {}) {preview_url: v.preview_url || null,}));- voiceCache = { at: Date.now(), voices };+ if (shareCache) voiceCache = { at: Date.now(), voices };return { voices, cached: false };}// ── Cloning ──────────────────────────────────────────────────────────────────/**- * Instant Voice Cloning via the official SDK.- * @param {{ name:string, description?:string, files:File[] }} input+ * Instant Voice Cloning via the official SDK. A user-supplied `apiKey` (BYOK)+ * clones onto that user's own ElevenLabs account.+ * @param {{ name:string, description?:string, files:File[], apiKey?:string|null }} input* @returns {Promise<{ voiceId:string, requiresVerification:boolean }>}* @throws {Error & { status:number, upstreamBody?:string }} on failure. IVC is* a paid-tier feature; the free tier surfaces `can_not_use_instant_* voice_cloning` here, which callers can pass through verbatim.*/-export async function createClonedVoice({ name, description, files }) {- const apiKey = elevenApiKey();+export async function createClonedVoice({ name, description, files, apiKey: keyOverride = null }) {+ const apiKey = keyOverride || elevenApiKey();if (!apiKey) throw upstreamError('ElevenLabs is not configured', 503);// Dynamic import: the official SDK's module graph takes ~5s to evaluate,diff --git a/api/_lib/pricing/catalog.js b/api/_lib/pricing/catalog.jsindex 27f2515fe..9cac1837c 100644--- a/api/_lib/pricing/catalog.js+++ b/api/_lib/pricing/catalog.js@@ -39,6 +39,12 @@ const FORGE_HIGH_USD = Number(priceUsdcForTier(TIERS.high)); // 0.50// any model into an engine-ready asset — a deliverable, billed per export.const FORGE_GAMEREADY_USD = Number(priceUsdcForOutput('gameready')); // 0.10+// Premium TTS (ElevenLabs) overage: retail USD per 1,000 synthesized characters+// once a user's free hourly quota is spent. Upstream Flash v2.5 cost is roughly+// $0.11/1k chars at the Creator tier; $0.30 retail keeps margin for the settle+// rail. The free quota and the BYOK bypass live in api/tts/eleven.js.+export const TTS_ELEVEN_USD_PER_1K = 0.3;+// ── The catalog ─────────────────────────────────────────────────────────────────// id → { label, category, policy, usd }. `usd: null` ⇒ price set per-call.export const CATALOG = Object.freeze({@@ -97,6 +103,12 @@ export const CATALOG = Object.freeze({policy: POLICY.CONSUMPTION,usd: 0.5,},+ 'tts.eleven': {+ label: 'Voice: premium TTS beyond the free hourly quota',+ category: 'generation',+ policy: POLICY.CONSUMPTION,+ usd: null, // per-call: characters * TTS_ELEVEN_USD_PER_1K / 1000+ },'selfie.reconstruct': {label: 'Selfie → Avatar reconstruction',category: 'generation',diff --git a/api/tts/eleven-clone.js b/api/tts/eleven-clone.jsindex 7f1cdc6d7..6e2117dea 100644--- a/api/tts/eleven-clone.js+++ b/api/tts/eleven-clone.js@@ -18,8 +18,9 @@*/import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, method, wrap, error, json } from '../_lib/http.js';-import { createClonedVoice, isConfigured } from '../_lib/elevenlabs.js';+import { cors, method, wrap, error, json, rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';+import { createClonedVoice, resolveElevenKey } from '../_lib/elevenlabs.js';export const config = {api: { bodyParser: false },@@ -33,12 +34,28 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- if (!isConfigured())- return error(res, 503, 'not_configured', 'ElevenLabs is not configured on this server');+ // 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);+ if (!apiKey)+ return error(+ res,+ 503,+ 'not_configured',+ '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 paid IVC slots on the shared account: hold+ // them to the same 3/day cap the agent-voice clone path already enforces.+ if (!byok) {+ const rl = await limits.voiceClone(userId);+ if (!rl.success) return rateLimited(res, rl);+ }const ct = req.headers['content-type'] || '';if (!ct.toLowerCase().startsWith('multipart/form-data'))@@ -103,7 +120,12 @@ export default wrap(async (req, res) => {let result;try {- result = await createClonedVoice({ name, description, files: [audioFile] });+ result = await createClonedVoice({+ name,+ description,+ files: [audioFile],+ apiKey: byok ? apiKey : null,+ });} catch (err) {const status = err.status || 502;console.error(@@ -121,7 +143,6 @@ export default wrap(async (req, res) => {});}- const userId = session?.id ?? bearer.userId;if (process.env.TTS_DEBUG === '1') {console.log(`[tts/eleven-clone] user=${userId} cloned voice "${name}" -> ${result.voiceId} (audio=${audio.data.length}B)`,diff --git a/api/tts/eleven.js b/api/tts/eleven.jsindex bdb087443..c6aa1d6e7 100644--- a/api/tts/eleven.js+++ b/api/tts/eleven.js@@ -4,7 +4,16 @@* Server proxy for ElevenLabs TTS. Keeps the API key server-side. The clip is* streamed straight to the client (low TTFB) and, on a clean finish, cached in* R2 for 30 days keyed by sha256(voiceId + text + modelId + voice_settings).- * Rate-limits per user: 1000 chars / hour tracked via Redis INCRBY.+ *+ * Billing ladder (header `x-tts-billing` reports which rung served the call):+ * byok - request carried an `x-eleven-key` header: the user's own+ * ElevenLabs account pays, so no platform budget or credits apply.+ * free - within the free hourly character budget (1000 chars / hour,+ * tracked via Redis INCRBY on the platform key).+ * credits - budget spent: the request is metered against the user's prepaid+ * credit wallet (top up with $THREE or SOL at /credits) at+ * TTS_ELEVEN_USD_PER_1K, with a 402 + top_up_url when short.+ * Cache hits are always free and never touch the budget.** Body: {* voiceId: string,@@ -18,17 +27,19 @@* Response: audio/mpeg (chunked)*/-import { env } from '../_lib/env.js';+import { randomUUID } from 'node:crypto';import { getRedis as _getSharedRedis } from '../_lib/redis.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { cors, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';-import { limits, clientIp } from '../_lib/rate-limit.js';+import { cors, method, wrap, error, json, readJson, rateLimited } from '../_lib/http.js';+import { limits } from '../_lib/rate-limit.js';import { sha256 } from '../_lib/crypto.js';import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';+import { chargeCreditsForAction, refundCredits } from '../_lib/credits.js';+import { TTS_ELEVEN_USD_PER_1K } from '../_lib/pricing/catalog.js';import {ELEVEN_BASE,DEFAULT_TTS_MODEL,- elevenApiKey,+ resolveElevenKey,normalizeVoiceSettings,} from '../_lib/elevenlabs.js';@@ -51,9 +62,14 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const apiKey = elevenApiKey();+ const { apiKey, byok } = resolveElevenKey(req);if (!apiKey)- return error(res, 503, 'not_configured', 'ElevenLabs is not configured on this server');+ return error(+ res,+ 503,+ 'not_configured',+ '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));@@ -81,54 +97,9 @@ export default wrap(async (req, res) => {body.voice_settings && typeof body.voice_settings === 'object' ? body.voice_settings : {},);- // ── Char-based rate limit ─────────────────────────────────────────────────- // rKey is lifted to function scope so a failed synthesis can refund the- // characters it optimistically reserves below.- let rKey = null;- if (redis) {- const hourBucket = Math.floor(Date.now() / 3_600_000);- const key = `tts:chars:${userId}:${hourBucket}`;- try {- const used = Number((await redis.get(key)) || 0);- if (used + text.length > CHARS_PER_HOUR) {- return error(- res,- 429,- 'rate_limited',- `TTS character limit (${CHARS_PER_HOUR}/hr) reached. Try again next hour.`,- );- }- // Increment before synthesis to prevent parallel races from blowing past limit.- const newTotal = await redis.incrby(key, text.length);- await redis.expire(key, 7200);- // Only arm the refund path once the reservation actually landed.- rKey = key;- if (newTotal > CHARS_PER_HOUR) {- await redis.decrby(key, text.length).catch(() => {});- rKey = null;- return error(- res,- 429,- 'rate_limited',- `TTS character limit (${CHARS_PER_HOUR}/hr) reached. Try again next hour.`,- );- }- } catch (err) {- // Redis outage / over-quota: fail open rather than 500 the synth, matching- // the shared limiter's non-critical behavior. ElevenLabs' own account quota- // stays the hard ceiling, so an unmetered call here can't run away on cost.- console.warn('[tts/eleven] char-limit redis degraded, allowing:', err?.message || err);- rKey = null;- }- }-- // Refund reserved characters when synthesis ultimately fails, so a user is- // not billed against the hourly budget for a clip they never received.- const refundChars = async () => {- if (rKey) await redis.decrby(rKey, text.length).catch(() => {});- };-// ── R2 cache lookup ───────────────────────────────────────────────────────+ // Checked BEFORE any metering: a cached clip costs nothing upstream, so it+ // never consumes the free budget and never charges credits.const cacheHash = await sha256(`${voiceId}\x00${text}\x00${modelId}\x00${settings.stability}\x00${settings.similarity_boost}\x00${settings.style}\x00${settings.use_speaker_boost}`,);@@ -141,13 +112,107 @@ export default wrap(async (req, res) => {res.setHeader('content-type', 'audio/mpeg');res.setHeader('content-length', String(buf.length));res.setHeader('x-tts-cache', 'hit');+ res.setHeader('x-tts-billing', 'free');res.setHeader('cache-control', 'private, max-age=86400');return res.end(buf);} catch {- // Cache read failed — fall through to synthesize fresh.+ // Cache read failed: fall through to synthesize fresh.+ }+ }++ // ── Metering ladder: byok → free hourly budget → prepaid credits ──────────+ // BYOK requests run on the user's own ElevenLabs account, so the platform+ // budget and credit wallet never apply. Platform-key requests consume the+ // free hourly character budget first; once it is spent, the request is+ // charged to the user's credit wallet (topped up with $THREE or SOL).+ let billing = byok ? 'byok' : 'free';+ // rKey / creditCharge are lifted to function scope so a failed synthesis can+ // refund whichever lane the request was metered on.+ let rKey = null;+ let creditCharge = null;++ const chargeOverage = async () => {+ const idempotencyKey = `tts:eleven:${randomUUID()}`;+ const usd = Math.max(0.0001, (text.length / 1000) * TTS_ELEVEN_USD_PER_1K);+ const charged = await chargeCreditsForAction({+ user: session || { id: userId },+ action: 'tts.eleven',+ usd,+ refType: 'tts',+ refId: cacheHash,+ idempotencyKey,+ meta: { chars: text.length, voiceId, modelId },+ });+ creditCharge = { idempotencyKey, chargedUsd: charged.chargedUsd };+ billing = 'credits';+ };++ if (!byok && redis) {+ let overBudget = false;+ const hourBucket = Math.floor(Date.now() / 3_600_000);+ const key = `tts:chars:${userId}:${hourBucket}`;+ try {+ const used = Number((await redis.get(key)) || 0);+ if (used + text.length > CHARS_PER_HOUR) {+ overBudget = true;+ } else {+ // Increment before synthesis to prevent parallel races from blowing past limit.+ const newTotal = await redis.incrby(key, text.length);+ await redis.expire(key, 7200);+ // Only arm the refund path once the reservation actually landed.+ rKey = key;+ if (newTotal > CHARS_PER_HOUR) {+ await redis.decrby(key, text.length).catch(() => {});+ rKey = null;+ overBudget = true;+ }+ }+ } catch (err) {+ // Redis outage / over-quota: fail open rather than 500 the synth, matching+ // the shared limiter's non-critical behavior. ElevenLabs' own account quota+ // stays the hard ceiling, so an unmetered call here can't run away on cost.+ console.warn('[tts/eleven] char-limit redis degraded, allowing:', err?.message || err);+ rKey = null;+ }++ if (overBudget) {+ try {+ await chargeOverage();+ } catch (err) {+ if (err?.code === 'insufficient_credits') {+ return json(res, 402, {+ error: 'insufficient_credits',+ feature: 'tts.eleven',+ available_usd: err.available_usd,+ required_usd: err.required_usd,+ top_up_url: '/credits',+ message:+ `Free TTS quota (${CHARS_PER_HOUR} chars/hr) is spent and your credit balance is short. ` ++ 'Top up with $THREE at /credits, wait for the hourly reset, or bring your own ElevenLabs key.',+ });+ }+ throw err;+ }}}+ // Refund whichever metering lane was used when synthesis ultimately fails,+ // so a user is never billed for a clip they never received.+ const refundMetering = async () => {+ if (rKey) await redis.decrby(rKey, text.length).catch(() => {});+ if (creditCharge?.chargedUsd > 0) {+ await refundCredits({+ userId,+ amountUsd: creditCharge.chargedUsd,+ action: 'tts.eleven',+ refType: 'tts',+ refId: cacheHash,+ idempotencyKey: `${creditCharge.idempotencyKey}:refund`,+ meta: { reason: 'synthesis_failed' },+ }).catch((e) => console.warn('[tts/eleven] credit refund failed:', e?.message || e));+ }+ };+// ── Synthesize via ElevenLabs ─────────────────────────────────────────────let elResp;try {@@ -174,14 +239,14 @@ export default wrap(async (req, res) => {);} catch (fetchErr) {console.error('[tts/eleven] ElevenLabs fetch failed', fetchErr);- await refundChars();+ await refundMetering();return error(res, 502, 'upstream_error', 'Could not reach ElevenLabs');}if (!elResp.ok) {const msg = await elResp.text().catch(() => '');console.error('[tts/eleven] ElevenLabs error', elResp.status, msg);- await refundChars();+ await refundMetering();return error(res, 502, 'upstream_error', `ElevenLabs returned ${elResp.status}`);}@@ -189,6 +254,9 @@ export default wrap(async (req, res) => {// buffer, so the complete audio can be cached once it has fully arrived.res.setHeader('content-type', 'audio/mpeg');res.setHeader('x-tts-cache', 'miss');+ res.setHeader('x-tts-billing', billing);+ if (creditCharge?.chargedUsd > 0)+ res.setHeader('x-tts-charged-usd', creditCharge.chargedUsd.toFixed(6));res.setHeader('cache-control', 'private, max-age=86400');if (!elResp.body) {diff --git a/api/tts/eleven/voices.js b/api/tts/eleven/voices.jsindex 8626b26d4..4ec97c77e 100644--- a/api/tts/eleven/voices.js+++ b/api/tts/eleven/voices.js@@ -2,14 +2,16 @@* GET /api/tts/eleven/voices** Returns the ElevenLabs voice list (filtered to safe public fields), served- * from the shared per-instance cache in _lib/elevenlabs.js. Returns- * { enabled: false, voices: [] } when ELEVENLABS_API_KEY is not set so the- * client can gate the UI without a separate config check.+ * from the shared per-instance cache in _lib/elevenlabs.js. A request carrying+ * its own `x-eleven-key` header (BYOK) lists that account's voices instead,+ * uncached. Returns { enabled: false, voices: [] } when ELEVENLABS_API_KEY is+ * not set and no user key was sent, so the client can gate the UI without a+ * separate config check.*/import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';import { cors, json, method, wrap, error } from '../../_lib/http.js';-import { isConfigured, listVoices, TTS_MODELS } from '../../_lib/elevenlabs.js';+import { resolveElevenKey, listVoices, TTS_MODELS } from '../../_lib/elevenlabs.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -19,11 +21,15 @@ export default wrap(async (req, res) => {const bearer = session ? null : await authenticateBearer(extractBearer(req));if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');- if (!isConfigured()) return json(res, 200, { enabled: false, voices: [], models: TTS_MODELS });+ // A user-supplied x-eleven-key (BYOK) lists THAT account's voices; otherwise+ // the platform account's. Unconfigured with no user key stays a soft-off so+ // the client can gate the UI without a separate config check.+ const { apiKey, byok } = resolveElevenKey(req);+ if (!apiKey) return json(res, 200, { enabled: false, voices: [], models: TTS_MODELS });let result;try {- result = await listVoices();+ result = await listVoices(byok ? { apiKey } : {});} catch (e) {console.error('[tts/eleven/voices] listVoices failed', e);return error(diff --git a/data/changelog.json b/data/changelog.jsonindex f0199c18d..b8b6559f8 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -18393,6 +18393,16 @@"fix"],"link": "/agora"+ },+ {+ "date": "2026-08-06",+ "title": "Voice Lab: bring your own ElevenLabs key, or pay for extra speech with $THREE credits",+ "summary": "Voice cloning and speech now have three clear lanes. Everyone keeps a free lane on the platform account: 3 voice clones a day and 1,000 spoken characters an hour, with cached clips always free. When the free hour is spent, speech keeps working and is metered to your prepaid credit balance (top up with $THREE or SOL at /credits) at $0.30 per 1,000 characters, refunded automatically if a clip fails. And anyone with their own ElevenLabs account can paste their API key into the new card on the Voice Lab page to run cloning and speech entirely on their account, with no platform limits; the key stays in your browser and is never stored on our servers.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/voice"}]}diff --git a/docs/voice-lab.md b/docs/voice-lab.mdindex d07058d4d..7da6f5bb0 100644--- a/docs/voice-lab.md+++ b/docs/voice-lab.md@@ -27,6 +27,26 @@ The live `/voice` playground synthesizes with a single default model (`eleven_fl- `eleven_turbo_v2_5`: Turbo v2.5, balanced latency and quality.- `eleven_multilingual_v2`: Multilingual v2, highest quality, 29 languages.+## Billing: free quota, $THREE credits, or your own key++Every synthesis and clone request rides one of three rungs, and the response header `x-tts-billing` tells you which one served it:++1. **Free quota (default).** Requests run on the platform's ElevenLabs account: 1,000 speech characters per user per hour and 3 clones per user per day. Cached clips are always free and never touch the quota.+2. **Prepaid credits.** Once the hourly character quota is spent, `/api/tts/eleven` meters the request against your [credit balance](https://three.ws/credits) (top up with $THREE or SOL) at $0.30 per 1,000 characters, the `tts.eleven` action in the pricing catalog. A short balance returns `402 insufficient_credits` with `top_up_url`, and a failed synthesis refunds the charge. The response header `x-tts-charged-usd` reports what a metered call cost.+3. **Bring your own key (BYOK).** Send your own ElevenLabs API key in the `x-eleven-key` header on any of the three endpoints (`/api/tts/eleven`, `/api/tts/eleven/voices`, `/api/tts/eleven-clone`) and the call runs on *your* ElevenLabs account: your voices, your quota, your bill, with no platform limits or credit metering. The server uses the key for that one request and never stores it. On [/voice](https://three.ws/voice), the "Use Your Own ElevenLabs Key" card saves the key to your browser's `localStorage` and attaches the header automatically.++```bash+# Synthesize on YOUR ElevenLabs account (BYOK): no platform quota, no credits.+curl -X POST 'https://three.ws/api/tts/eleven' \+ -H 'authorization: Bearer <TOKEN>' \+ -H 'x-eleven-key: <YOUR_ELEVENLABS_KEY>' \+ -H 'content-type: application/json' \+ -d '{ "voiceId": "<VOICE_ID>", "text": "Running on my own account." }' \+ --output hello.mp3+```++Note that agent-assigned voices always run on the platform account (the agent speaks server-side, where your browser key is not present), so a voice you want an agent to use must be cloned on the platform rungs, not under BYOK.+## Walkthrough1. Open [/voice](https://three.ws/voice) and sign in (both endpoints require auth).@@ -70,10 +90,10 @@ The agent-voice handler ([`api/agents/_id/voice.js`](../api/agents/_id/voice.js)- **Recorder states.** `idle` -> `recording` (live waveform, timer, level meter) -> `review` (playback, name, Clone / Re-record) -> `cloning` (spinner) -> `done` (green check, `voice_id` shown, actions: Try in playground / Add to an agent / Record another).- **Auth required.** Both TTS endpoints return `401 unauthorized` without a session or bearer token. Requests send `credentials: 'include'`.-- **Server config.** ElevenLabs must be configured (`ELEVENLABS_API_KEY`) or the endpoints return `503 not_configured`.+- **Server config.** ElevenLabs must be configured (`ELEVENLABS_API_KEY`) or the endpoints return `503 not_configured`; a request carrying its own `x-eleven-key` header still works (see the billing section above).- **Paid cloning tier.** Instant Voice Cloning is an ElevenLabs paid-tier (Starter and up) feature. On a free upstream tier the API surfaces the upstream `can_not_use_instant_voice_cloning` body verbatim as a `502`.- **Length rules.** Voice Lab recommends 20 to 30 seconds, auto-stops at 60, and rejects under 3. The separate agent-clone endpoint (`POST /api/agents/:id/voice/clone`) enforces a 30-second floor and 3 clones per user per day.-- **Synthesis limits.** 500 characters per playground request; 1000 characters per hour per user (reserved-then-refunded so a failed synth does not burn quota). Clips are cached in R2 for 30 days.+- **Synthesis limits.** 500 characters per playground request; 1000 free characters per hour per user (reserved-then-refunded so a failed synth does not burn quota), then metered to credits per the billing section. BYOK requests skip both. Clips are cached in R2 for 30 days.- **Audio size.** Clone uploads are capped at ~10 MB.- **"Add to an agent" on `/voice`** links to the dashboard; the actual assignment happens in the agent editor. The cloned `voice_id` lives in browser `localStorage` until you assign it.- **Error copy.** Mic denial, recorder failure, too-short recording, missing name, network failure, and clone failure each map to a specific message; the playground shows "Synthesizing...", then a size and cached/generated tag, or an error.diff --git a/pages/voice.html b/pages/voice.htmlindex a5b92eca8..5ed6a15ad 100644--- a/pages/voice.html+++ b/pages/voice.html@@ -640,6 +640,37 @@align-items: center;}+ /* ── BYOK: your own ElevenLabs key ───────────── */+ .vl-byok-copy {+ margin: 0 0 14px;+ font-size: 13px;+ line-height: 1.6;+ color: #999999;+ }+ .vl-byok-copy a { color: #e8e8e8; text-decoration: underline; text-underline-offset: 2px; }+ .vl-byok-copy a:hover { color: #ffffff; }+ .vl-byok-row {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ align-items: center;+ margin-bottom: 8px;+ }+ .vl-byok-row input {+ flex: 1;+ min-width: 220px;+ padding: 10px 12px;+ background: #070707;+ border: 1px solid #212121;+ border-radius: 9px;+ color: #e8e8e8;+ font: inherit;+ font-size: 14px;+ outline: none;+ transition: border-color 0.15s;+ }+ .vl-byok-row input:focus { border-color: #ffffff; }+/* ── Responsive ─────────────────────────────── */@media (max-width: 640px) {.vl-root { padding: 20px 16px 60px; }@@ -790,6 +821,32 @@</div></div></div>++ <!-- ── BYOK: your own ElevenLabs key ─────────── -->+ <div class="vl-section" id="byokSection">+ <div class="vl-section-head">+ <h2 class="vl-section-title">Use Your Own ElevenLabs Key</h2>+ </div>+ <div class="vl-card">+ <div class="vl-card-body">+ <p class="vl-byok-copy">+ By default, cloning and speech run on the three.ws account: 3 free clones a day+ and 1,000 free speech characters an hour, after which synthesis is metered to your+ <a href="/credits">credit balance</a> (top up with $THREE or SOL).+ Paste your own <a href="https://elevenlabs.io/app/settings/api-keys" target="_blank" rel="noopener">ElevenLabs API key</a>+ to run everything on your ElevenLabs account instead: your voices, your quota, no+ platform limits. The key is stored only in this browser and sent only with your+ own voice requests; the server never keeps it.+ </p>+ <div class="vl-byok-row">+ <input type="password" id="byokKey" placeholder="sk_..." autocomplete="off" spellcheck="false" aria-label="ElevenLabs API key" />+ <button class="vl-btn vl-btn-primary" id="byokSave" type="button">Save key</button>+ <button class="vl-btn" id="byokClear" type="button" hidden>Remove</button>+ </div>+ <span class="vl-pg-hint" id="byokStatus" role="status" style="font-size:12px;color:#666666;"></span>+ </div>+ </div>+ </div></main><script src="/nav.js" defer></script>diff --git a/public/changelog.json b/public/changelog.jsonindex 230d4b62d..1b30cfe28 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-08-06T20:09:15.798Z",+ "generated_at": "2026-08-06T20:41:27.416Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-08-06",+ "type": "launch",+ "title": "Docs · Wallet Portfolio",+ "summary": "How the live wallet portfolio works: the keyless Solana-first data sources behind /api/crypto/portfolio, the stable/major/token classification, the honest 24h coverage contract, and the full response shape for agents and scripts.",+ "link": "/docs/portfolio",+ "tags": [+ "launch"+ ]+ },{"date": "2026-08-06","type": "launch",@@ -16,6 +26,16 @@"launch"]},+ {+ "date": "2026-08-06",+ "type": "launch",+ "title": "Wallet Portfolio",+ "summary": "A live portfolio view for any Solana or Ethereum wallet: total value, 24h move with honest coverage, stablecoin/major/token breakdown, top-asset allocation, and every holding priced in real time. Free, keyless, deep-linkable, no account.",+ "link": "/portfolio",+ "tags": [+ "launch"+ ]+ },{"date": "2026-08-06","type": "update",@@ -491,6 +511,17 @@"security"]},+ {+ "date": "2026-08-06",+ "type": "update",+ "title": "Voice Lab: bring your own ElevenLabs key, or pay for extra speech with $THREE credits",+ "summary": "Voice cloning and speech now have three clear lanes. Everyone keeps a free lane on the platform account: 3 voice clones a day and 1,000 spoken characters an hour, with cached clips always free. When the free hour is spent, speech keeps working and is metered to your prepaid credit balance (top up with $THREE or SOL at /credits) at $0.30 per 1,000 characters, refunded automatically if a clip fails. And anyone with their own ElevenLabs account can paste their API key into the new card on the Voice Lab page to run cloning and speech entirely on their account, with no platform limits; the key stays in your browser and is never stored on our servers.",+ "link": "/voice",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-08-05","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex ce2e29d3f..29302976b 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Docs · Wallet Portfolio</title>+ <link>https://three.ws/docs/portfolio</link>+ <guid isPermaLink="false">2026-08-06:Docs · Wallet Portfolio</guid>+ <pubDate>Thu, 06 Aug 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>How the live wallet portfolio works: the keyless Solana-first data sources behind /api/crypto/portfolio, the stable/major/token classification, the honest 24h coverage contract, and the full response shape for agents and scripts.</description>+ </item><item><title>Sign Mirror</title><link>https://three.ws/sign-mirror</link>@@ -14,6 +22,14 @@<category>launch</category><description>Learn the ASL alphabet by making it: the avatar forms the letter, your camera watches your hand, and the page grades the handshape live, naming the finger that is off. Fully on-device; no video ever uploaded.</description></item>+ <item>+ <title>Wallet Portfolio</title>+ <link>https://three.ws/portfolio</link>+ <guid isPermaLink="false">2026-08-06:Wallet Portfolio</guid>+ <pubDate>Thu, 06 Aug 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A live portfolio view for any Solana or Ethereum wallet: total value, 24h move with honest coverage, stablecoin/major/token breakdown, top-asset allocation, and every holding priced in real time. Free, keyless, deep-linkable, no account.</description>+ </item><item><title>A dry Agora wallet now tells you which address to fund</title><link>https://three.ws/agora</link>@@ -374,6 +390,14 @@<category>security</category><description>Contributing to or exiting a trading swarm moves real SOL out of a custodial wallet, and pausing or killing one changes a live treasury's mandate, but those actions were missing two guards the rest of the platform's money actions have had. They now require the same anti-forgery token, so another website cannot make a request on your behalf while you are signed in, and they are capped at the same rate an agent trade is, in their own budget so an active trader can never rate-limit their own swarm.</description></item>+ <item>+ <title>Voice Lab: bring your own ElevenLabs key, or pay for extra speech with $THREE credits</title>+ <link>https://three.ws/voice</link>+ <guid isPermaLink="false">2026-08-06:Voice Lab: bring your own ElevenLabs key, or pay for extra speech with $THREE credits</guid>+ <pubDate>Thu, 06 Aug 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Voice cloning and speech now have three clear lanes. Everyone keeps a free lane on the platform account: 3 voice clones a day and 1,000 spoken characters an hour, with cached clips always free. When the free hour is spent, speech keeps working and is metered to your prepaid credit balance (top up with $THREE or SOL at /credits) at $0.30 per 1,000 characters, refunded automatically if a clip fails. And anyone with their own ElevenLabs account can paste their API key into the new card on the Voice Lab page to run cloning and speech entirely on their account, with no platform limits; the key stays in your browser and is never stored on our servers.</description>+ </item><item><title>Docs · The free LLM failover chain</title><link>https://three.ws/docs/free-llm-providers</link>diff --git a/public/features.json b/public/features.jsonindex 537d43102..8f5ac1053 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-06T20:09:15.789Z",+ "generated_at": "2026-08-06T20:41:27.407Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1546,6 +1546,16 @@"tags": [],"showcase": false},+ {+ "path": "/portfolio",+ "title": "Wallet Portfolio",+ "description": "A live portfolio view for any Solana or Ethereum wallet: total value, 24h move with honest coverage, stablecoin/major/token breakdown, top-asset allocation, and every holding priced in real time. Free, keyless, deep-linkable, no account.",+ "added": "2026-08-06",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/launcher","title": "Memetic Launcher",@@ -6256,6 +6266,16 @@"indexable": true,"tags": [],"showcase": false+ },+ {+ "path": "/docs/portfolio",+ "title": "Docs · Wallet Portfolio",+ "description": "How the live wallet portfolio works: the keyless Solana-first data sources behind /api/crypto/portfolio, the stable/major/token classification, the honest 24h coverage contract, and the full response shape for agents and scripts.",+ "added": "2026-08-06",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false}]},diff --git a/src/dashboard-next/pages/library/voice.js b/src/dashboard-next/pages/library/voice.jsindex 2a6f8d1cf..6e771057f 100644--- a/src/dashboard-next/pages/library/voice.js+++ b/src/dashboard-next/pages/library/voice.js@@ -97,7 +97,7 @@ export async function renderVoice(host) {banner.style.cssText = 'margin-bottom:14px;padding:14px 16px;text-align:left';banner.innerHTML = `<h3 style="margin:0 0 4px;font-size:14px">ElevenLabs is not configured</h3>- <p style="margin:0;font-size:12px">Voice picking and previews are disabled until <code>ELEVENLABS_API_KEY</code> is set on the server. Agents will fall back to browser TTS.</p>+ <p style="margin:0;font-size:12px">Voice picking and previews are disabled until <code>ELEVENLABS_API_KEY</code> is set on the server. Agents will fall back to browser TTS. You can still clone and play voices with your own ElevenLabs key in the <a href="/voice">Voice Lab</a>.</p>`;list.appendChild(banner);}diff --git a/src/voice-lab.js b/src/voice-lab.jsindex 285cc1a45..21c34b529 100644--- a/src/voice-lab.js+++ b/src/voice-lab.js@@ -1,3 +1,5 @@+import { getElevenKey, setElevenKey, clearElevenKey, withElevenKey, maskElevenKey } from './voice/eleven-key.js';+const $ = (id) => document.getElementById(id);// ── Reading scripts ──────────────────────────────────────────────────────────@@ -375,6 +377,7 @@ async function cloneVoice() {res = await fetch('/api/tts/eleven-clone', {method: 'POST',credentials: 'include',+ headers: withElevenKey(),body: fd,});} catch (err) {@@ -517,16 +520,25 @@ async function speakPlayground() {const r = await fetch('/api/tts/eleven', {method: 'POST',credentials: 'include',- headers: { 'content-type': 'application/json' },+ headers: withElevenKey({ 'content-type': 'application/json' }),body: JSON.stringify({ voiceId, text }),});if (!r.ok) {const errText = await r.text().catch(() => '');- throw new Error(`HTTP ${r.status}: ${errText.slice(0, 200)}`);+ let msg = '';+ try {+ const body = JSON.parse(errText);+ msg = body.message || body.error_description || body.error || '';+ } catch {+ msg = errText.slice(0, 200);+ }+ throw new Error(msg || `HTTP ${r.status}`);}const cacheHit = r.headers.get('x-tts-cache') === 'hit';+ const billing = r.headers.get('x-tts-billing');+ const chargedUsd = Number(r.headers.get('x-tts-charged-usd') || 0);const buf = await r.arrayBuffer();const blob = new Blob([buf], { type: 'audio/mpeg' });const url = URL.createObjectURL(blob);@@ -537,7 +549,11 @@ async function speakPlayground() {$('pgOutput').classList.add('visible');audio.play().catch(() => {});- $('pgHint').textContent = `${(buf.byteLength / 1024).toFixed(0)} KB · ${cacheHit ? 'cached' : 'generated'}`;+ const billingNote =+ billing === 'byok' ? ' · your key'+ : chargedUsd > 0 ? ` · $${chargedUsd.toFixed(4)} credits`+ : '';+ $('pgHint').textContent = `${(buf.byteLength / 1024).toFixed(0)} KB · ${cacheHit ? 'cached' : 'generated'}${billingNote}`;} catch (err) {$('pgHint').textContent = `Error: ${err.message}`;} finally {@@ -556,7 +572,7 @@ async function playVoiceSample(voiceId) {const r = await fetch('/api/tts/eleven', {method: 'POST',credentials: 'include',- headers: { 'content-type': 'application/json' },+ headers: withElevenKey({ 'content-type': 'application/json' }),body: JSON.stringify({voiceId,text: "Hello, I'm your cloned voice. How does this sound?",@@ -629,10 +645,48 @@ document.addEventListener('keydown', (e) => {}});+// ── BYOK: your own ElevenLabs key ────────────────────────────────────────────++function renderByokState() {+ const key = getElevenKey();+ $('byokClear').hidden = !key;+ $('byokKey').placeholder = key ? maskElevenKey(key) : 'sk_...';+ $('byokSave').textContent = key ? 'Update key' : 'Save key';+ $('byokStatus').textContent = key+ ? `Using your ElevenLabs account (${maskElevenKey(key)}). Clones and speech are billed to it.`+ : 'Using the three.ws account with the free quota.';+}++$('byokSave').addEventListener('click', () => {+ const value = $('byokKey').value.trim();+ if (!value) {+ $('byokStatus').textContent = 'Paste your ElevenLabs API key first.';+ $('byokKey').focus();+ return;+ }+ setElevenKey(value);+ $('byokKey').value = '';+ renderByokState();+});++$('byokKey').addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ $('byokSave').click();+ }+});++$('byokClear').addEventListener('click', () => {+ clearElevenKey();+ $('byokKey').value = '';+ renderByokState();+});+// ── Init ─────────────────────────────────────────────────────────────────────renderLibrary();renderPlaygroundVoices();+renderByokState();// Auto-populate voice name with a sensible defaultconst now = new Date();diff --git a/src/voice/eleven-key.js b/src/voice/eleven-key.jsnew file mode 100644index 000000000..b0544ebc9--- /dev/null+++ b/src/voice/eleven-key.js@@ -0,0 +1,47 @@+// Client-side store for a user's own ElevenLabs API key (BYOK).+//+// The key lives only in this browser's localStorage and is sent as the+// `x-eleven-key` header on voice requests. The server resolves it per request+// (api/_lib/elevenlabs.js resolveElevenKey) and never stores it: BYOK calls+// run on the user's own ElevenLabs account, bypassing the platform's free+// quota, credit metering, and daily clone cap.++const STORAGE_KEY = 'three_eleven_key_v1';++/** @returns {string|null} the saved key, or null when none is saved. */+export function getElevenKey() {+ try {+ return (localStorage.getItem(STORAGE_KEY) || '').trim() || null;+ } catch {+ return null;+ }+}++/** Save (non-empty) or clear (empty) the key. Returns the stored value. */+export function setElevenKey(key) {+ const k = String(key || '').trim();+ try {+ if (k) localStorage.setItem(STORAGE_KEY, k);+ else localStorage.removeItem(STORAGE_KEY);+ } catch {+ // Storage unavailable (private mode): the key just won't persist.+ }+ return k || null;+}++export function clearElevenKey() {+ setElevenKey('');+}++/** Merge the BYOK header into a fetch headers object when a key is saved. */+export function withElevenKey(headers = {}) {+ const key = getElevenKey();+ return key ? { ...headers, 'x-eleven-key': key } : headers;+}++/** "sk_12…89ab" style preview for UI display; never render the full key. */+export function maskElevenKey(key = getElevenKey()) {+ if (!key) return '';+ if (key.length <= 8) return `${key.slice(0, 2)}…`;+ return `${key.slice(0, 5)}…${key.slice(-4)}`;+}diff --git a/tests/api-tts-elevenlabs.test.js b/tests/api-tts-elevenlabs.test.jsindex 655c6a93f..d96f4ddea 100644--- a/tests/api-tts-elevenlabs.test.js+++ b/tests/api-tts-elevenlabs.test.js@@ -22,6 +22,7 @@ import {normalizeVoiceSettings,elevenApiKey,isConfigured,+ resolveElevenKey,listVoices,invalidateVoiceCache,createClonedVoice,@@ -59,6 +60,63 @@ describe('config gate', () => {});});+describe('resolveElevenKey (BYOK)', () => {+ const reqWith = (key) => ({ headers: key === undefined ? {} : { 'x-eleven-key': key } });++ it('prefers a valid x-eleven-key header over the platform key', () => {+ expect(resolveElevenKey(reqWith('sk_user_own_key'))).toEqual({+ apiKey: 'sk_user_own_key',+ byok: true,+ });+ });++ it('falls back to the platform key when no header is sent', () => {+ expect(resolveElevenKey(reqWith(undefined))).toEqual({+ apiKey: 'sk_test_key',+ byok: false,+ });+ });++ it('rejects malformed user keys (whitespace inside, control chars, oversized)', () => {+ for (const bad of ['has space', 'ctrl\x01char', 'x'.repeat(300), '', ' ']) {+ expect(resolveElevenKey(reqWith(bad))).toEqual({ apiKey: 'sk_test_key', byok: false });+ }+ });++ it('returns a null key when neither a user key nor the platform key exists', () => {+ delete process.env.ELEVENLABS_API_KEY;+ expect(resolveElevenKey(reqWith(undefined))).toEqual({ apiKey: null, byok: false });+ });++ it('trims surrounding whitespace on the user key', () => {+ expect(resolveElevenKey(reqWith(' sk_padded '))).toEqual({+ apiKey: 'sk_padded',+ byok: true,+ });+ });+});++describe('listVoices with a BYOK key', () => {+ it('bypasses the shared cache in both directions', async () => {+ global.fetch.mockResolvedValue(voicesResponse([{ voice_id: 'plat', name: 'Platform' }]));+ await listVoices();+ expect(global.fetch).toHaveBeenCalledTimes(1);++ // A user key must not be served the platform's cached catalog...+ global.fetch.mockResolvedValue(voicesResponse([{ voice_id: 'mine', name: 'Mine' }]));+ const user = await listVoices({ apiKey: 'sk_user_own_key' });+ expect(user.cached).toBe(false);+ expect(user.voices[0].voice_id).toBe('mine');+ expect(global.fetch).toHaveBeenCalledTimes(2);+ expect(global.fetch.mock.calls[1][1].headers['xi-api-key']).toBe('sk_user_own_key');++ // ...and must not have poisoned the platform cache on the way through.+ const plat = await listVoices();+ expect(plat.cached).toBe(true);+ expect(plat.voices[0].voice_id).toBe('plat');+ });+});+describe('isValidModel / TTS_MODELS', () => {it('accepts catalog models and rejects everything else', () => {expect(isValidModel('eleven_flash_v2_5')).toBe(true);