1. A small proxy that holds your key
Browsers can call the API directly, but a key in a public page can be copied and spent by anyone. Put this in front of it (Cloudflare Worker shown; the same steps work in a Next.js route, Express or a Firebase Function). An open proxy is as bad as a public key, so this one only answers your own pages (including the browser's CORS preflight), limits each IP address, caps the upload size and scores only the practice texts you list. It refuses to run until the key, the allowed origins and the rate limit are configured.
// Your server keeps the key; the widget posts to /assess on your domain.
// Cloudflare Worker. It refuses to run until all three are set:
// TONEPERFECT_API_KEY secret: npx wrangler secret put TONEPERFECT_API_KEY
// ALLOWED_ORIGINS your pages, comma-separated: "https://your-site.example"
// ASSESS_LIMIT rate-limit binding (wrangler.toml below)
// Origin only stops other websites; any script can forge it. The per-IP limit
// and the fixed list of texts are what bound the credits a script can spend.
const PRACTICE = new Set(['zh-CN|你好', 'zh-CN|谢谢']); // language|text your pages show
const MAX_BYTES = 2 * 1024 * 1024; // 15 s of browser audio is far less
const KEY_RE = /^[A-Za-z0-9_.:-]{8,128}$/;
const fail = (status, code, message, headers = {}) =>
Response.json({ error: { code, message } }, { status, headers });
export default {
async fetch(request, env) {
const origins = (env.ALLOWED_ORIGINS || '').split(',').map(o => o.trim()).filter(Boolean);
if (!env.TONEPERFECT_API_KEY || !env.ASSESS_LIMIT || !origins.length)
return fail(500, 'proxy_not_configured', 'Set TONEPERFECT_API_KEY, ALLOWED_ORIGINS and ASSESS_LIMIT.');
const origin = request.headers.get('Origin') || '';
if (!origins.includes(origin)) return fail(403, 'origin_not_allowed', 'This page may not use the proxy.');
const cors = { 'Access-Control-Allow-Origin': origin, Vary: 'Origin' };
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: { ...cors,
'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Idempotency-Key',
'Access-Control-Max-Age': '600' } });
if (request.method !== 'POST') return fail(405, 'method_not_allowed', 'POST only.', cors);
const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
if (!(await env.ASSESS_LIMIT.limit({ key: ip })).success)
return fail(429, 'rate_limit', 'Too many recordings. Try again in a minute.', cors);
const size = Number(request.headers.get('Content-Length'));
if (!size || size > MAX_BYTES) return fail(413, 'upload_too_large', 'Send one short recording.', cors);
const form = await request.formData();
const audio = form.get('audio'), text = String(form.get('text') || ''), language = String(form.get('language') || '');
if (!(audio instanceof File) || !PRACTICE.has(language + '|' + text))
return fail(422, 'text_not_allowed', 'This proxy scores only the practice texts on this site.', cors);
const body = new FormData();
body.append('audio', audio, audio.name || 'take.webm');
body.append('text', text);
body.append('language', language);
for (const field of ['pinyin', 'task']) if (form.get(field)) body.append(field, String(form.get(field)).slice(0, 1000));
const key = request.headers.get('Idempotency-Key');
const upstream = await fetch('https://api.toneperfect.app/v1/assess', { method: 'POST', body, headers: {
Authorization: 'Bearer ' + env.TONEPERFECT_API_KEY,
'Idempotency-Key': key && KEY_RE.test(key) ? key : crypto.randomUUID(), // one per recording
'TonePerfect-Response': 'compact' } });
return new Response(upstream.body, { status: upstream.status, headers: { ...cors, 'Content-Type': 'application/json' } });
},
};name = "toneperfect-embed-proxy"
main = "worker.js"
compatibility_date = "2025-09-01"
[[ratelimits]]
name = "ASSESS_LIMIT"
namespace_id = "1001"
simple = { limit = 10, period = 60 } # 10 recordings per minute per IP
[vars]
ALLOWED_ORIGINS = "https://your-site.example"Add every sentence your pages use to PRACTICE. If your site has many, look the text up on the server by a prompt ID instead of trusting the text the browser sends. For a site with sign-in, also check the user's session in the proxy and limit per user.
2. One tag where the button goes
<div class="toneperfect-check" data-endpoint="https://your-site.example/assess"
data-text="你好" data-language="zh-CN"></div>
<script src="https://api.toneperfect.app/static/embed.js" defer></script>The script adds a record button, records with the browser's microphone, sends the recording to your endpoint, and shows the score with the words or syllables to review. For Mandarin it shows which tone was expected and which was heard. It is about 5 KB, has no dependencies and asks for the microphone only when the learner presses record.
3. What your learners see
- An overall score from 0 to 100 and each word coloured by its score.
- The units to review (for Mandarin: "tone: expected 3, heard 2").
- A small "Powered by TonePerfect" link under the result. Please keep it; it is how other builders find us.
Cost
One credit per recording up to 15 seconds; failed or unassessable recordings are free. While you wire it up, put a test key (tp_test_…) in the proxy: it returns a fixed example result and spends nothing. The 50 free credits then cover real testing, then plans start at $10 for 2,500 recordings. Building a free tool for learners? Tell us about it at nik@toneperfect.app.
Styling and events
The widget uses a .toneperfect-check container and plain class names (.tp-record, .tp-score, .tp-word) so your CSS wins. It dispatches a toneperfect:result event with the compact result on the container, so you can save progress in your own app.