Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

fix(security): route third-party API calls through server-side proxy

lvalicsdadb31202e5a
diff --git a/apps/web/functions/api/proxy/[[catchall]].ts b/apps/web/functions/api/proxy/[[catchall]].ts
new file mode 100644
index 00000000..911d0237
--- /dev/null
+++ b/apps/web/functions/api/proxy/[[catchall]].ts
@@ -0,0 +1,109 @@
+/**
+ * Cloudflare Pages Function: API proxy for third-party services.
+ *
+ * Routes requests from the browser to ElevenLabs, OpenAI, and Anthropic
+ * so that API keys never leave the same origin in production.
+ *
+ * URL pattern: /api/proxy/<service>/<path>
+ * e.g. POST /api/proxy/elevenlabs/text-to-speech/abc123
+ * POST /api/proxy/openai/chat/completions
+ * POST /api/proxy/anthropic/messages
+ *
+ * The API key is passed via the `x-proxy-api-key` header and translated
+ * to the correct service-specific header before forwarding.
+ */
+
+interface ServiceConfig {
+ baseUrl: string;
+ authHeaders: (key: string) => Record<string, string>;
+}
+
+const SERVICE_CONFIG: Record<string, ServiceConfig> = {
+ elevenlabs: {
+ baseUrl: "https://api.elevenlabs.io/v1",
+ authHeaders: (key) => ({ "xi-api-key": key }),
+ },
+ openai: {
+ baseUrl: "https://api.openai.com/v1",
+ authHeaders: (key) => ({ Authorization: `Bearer ${key}` }),
+ },
+ anthropic: {
+ baseUrl: "https://api.anthropic.com/v1",
+ authHeaders: (key) => ({
+ "x-api-key": key,
+ "anthropic-version": "2023-06-01",
+ }),
+ },
+};
+
+const CORS_HEADERS: Record<string, string> = {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
+ "Access-Control-Allow-Headers": "Content-Type, x-proxy-api-key",
+};
+
+export const onRequest: PagesFunction = async (context) => {
+ // Handle CORS preflight
+ if (context.request.method === "OPTIONS") {
+ return new Response(null, { status: 204, headers: CORS_HEADERS });
+ }
+
+ const pathParts = context.params.catchall as string[];
+ if (!pathParts || pathParts.length < 1) {
+ return new Response(JSON.stringify({ error: "Missing service in URL path" }), {
+ status: 400,
+ headers: { "Content-Type": "application/json", ...CORS_HEADERS },
+ });
+ }
+
+ const service = pathParts[0];
+ const remainingPath = pathParts.slice(1).join("/");
+
+ const config = SERVICE_CONFIG[service];
+ if (!config) {
+ return new Response(JSON.stringify({ error: `Unknown service: ${service}` }), {
+ status: 400,
+ headers: { "Content-Type": "application/json", ...CORS_HEADERS },
+ });
+ }
+
+ const apiKey = context.request.headers.get("x-proxy-api-key");
+ if (!apiKey) {
+ return new Response(JSON.stringify({ error: "Missing x-proxy-api-key header" }), {
+ status: 401,
+ headers: { "Content-Type": "application/json", ...CORS_HEADERS },
+ });
+ }
+
+ const targetUrl = remainingPath
+ ? `${config.baseUrl}/${remainingPath}`
+ : config.baseUrl;
+
+ // Build headers for the upstream request
+ const upstreamHeaders = new Headers();
+ const contentType = context.request.headers.get("Content-Type");
+ if (contentType) {
+ upstreamHeaders.set("Content-Type", contentType);
+ }
+ for (const [key, value] of Object.entries(config.authHeaders(apiKey))) {
+ upstreamHeaders.set(key, value);
+ }
+
+ const upstreamResponse = await fetch(targetUrl, {
+ method: context.request.method,
+ headers: upstreamHeaders,
+ body: context.request.method !== "GET" ? context.request.body : undefined,
+ });
+
+ // Forward the response, adding CORS headers
+ const responseHeaders = new Headers(upstreamResponse.headers);
+ for (const [key, value] of Object.entries(CORS_HEADERS)) {
+ responseHeaders.set(key, value);
+ }
+
+ return new Response(upstreamResponse.body, {
+ status: upstreamResponse.status,
+ statusText: upstreamResponse.statusText,
+ headers: responseHeaders,
+ });
+};
diff --git a/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx b/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
index 52170008..89f74329 100644
--- a/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
+++ b/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
@@ -20,7 +20,8 @@ import { Slider, Switch } from "@openreel/ui";
import { useProjectStore } from "../../../stores/project-store";
import { useSettingsStore } from "../../../stores/settings-store";
import { isSessionUnlocked, getSecret } from "../../../services/secure-storage";
-import { OPENREEL_TTS_URL, ELEVENLABS_API_URL, OPENAI_API_URL, ANTHROPIC_API_URL } from "../../../config/api-endpoints";
+import { apiFetch } from "../../../services/api-proxy";
+import { OPENREEL_TTS_URL } from "../../../config/api-endpoints";
type TtsProvider = "piper" | "elevenlabs";
@@ -154,9 +155,7 @@ export const TextToSpeechPanel: React.FC = () => {
setIsLoadingModels(true);
try {
- const response = await fetch(`${ELEVENLABS_API_URL}/models`, {
- headers: { "xi-api-key": apiKey },
- });
+ const response = await apiFetch("elevenlabs", "/models", apiKey);
if (!response.ok) throw new Error("Failed to fetch models");
@@ -188,9 +187,7 @@ export const TextToSpeechPanel: React.FC = () => {
setIsLoadingVoices(true);
try {
- const response = await fetch(`${ELEVENLABS_API_URL}/voices`, {
- headers: { "xi-api-key": apiKey },
- });
+ const response = await apiFetch("elevenlabs", "/voices", apiKey);
if (!response.ok) throw new Error("Failed to fetch voices");
@@ -366,14 +363,13 @@ export const TextToSpeechPanel: React.FC = () => {
throw new Error("ElevenLabs API key not found. Add it in Settings > API Keys.");
}
- const response = await fetch(
- `${ELEVENLABS_API_URL}/text-to-speech/${voiceId}`,
+ const response = await apiFetch(
+ "elevenlabs",
+ `/text-to-speech/${voiceId}`,
+ apiKey,
{
method: "POST",
- headers: {
- "xi-api-key": apiKey,
- "Content-Type": "application/json",
- },
+ headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: inputText,
model_id: elevenLabsModel,
@@ -406,14 +402,9 @@ export const TextToSpeechPanel: React.FC = () => {
}
if (llmProvider === "anthropic") {
- const response = await fetch(`${ANTHROPIC_API_URL}/messages`, {
+ const response = await apiFetch("anthropic", "/messages", apiKey, {
method: "POST",
- headers: {
- "x-api-key": apiKey,
- "anthropic-version": "2023-06-01",
- "anthropic-dangerous-direct-browser-access": "true",
- "Content-Type": "application/json",
- },
+ headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "claude-sonnet-4-20250514",
max_tokens: 2048,
@@ -435,12 +426,9 @@ export const TextToSpeechPanel: React.FC = () => {
}
// OpenAI
- const response = await fetch(`${OPENAI_API_URL}/chat/completions`, {
+ const response = await apiFetch("openai", "/chat/completions", apiKey, {
method: "POST",
- headers: {
- Authorization: `Bearer ${apiKey}`,
- "Content-Type": "application/json",
- },
+ headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [
diff --git a/apps/web/src/config/api-endpoints.ts b/apps/web/src/config/api-endpoints.ts
index 76ddce51..b6ade178 100644
--- a/apps/web/src/config/api-endpoints.ts
+++ b/apps/web/src/config/api-endpoints.ts
@@ -15,7 +15,10 @@ export const OPENREEL_CLOUD_URL = isDev
/** OpenReel transcription / TTS service */
export const OPENREEL_TTS_URL = "https://transcribe.openreel.video";
-/** Third-party API base URLs */
-export const ELEVENLABS_API_URL = "https://api.elevenlabs.io/v1";
-export const OPENAI_API_URL = "https://api.openai.com/v1";
-export const ANTHROPIC_API_URL = "https://api.anthropic.com/v1";
+/**
+ * Third-party API base URLs.
+ * These are used by the api-proxy service in dev mode (direct calls)
+ * and by the Cloudflare Pages Function proxy in production.
+ * Application code should use apiFetch() from services/api-proxy.ts
+ * instead of importing these directly.
+ */
diff --git a/apps/web/src/services/api-proxy.ts b/apps/web/src/services/api-proxy.ts
new file mode 100644
index 00000000..05855299
--- /dev/null
+++ b/apps/web/src/services/api-proxy.ts
@@ -0,0 +1,74 @@
+/**
+ * API proxy utility for third-party service calls.
+ *
+ * In development: calls third-party APIs directly (for convenience).
+ * In production: routes through Cloudflare Pages Functions proxy so
+ * API keys never leave the same origin.
+ */
+
+const isDev = import.meta.env.DEV;
+
+const DIRECT_CONFIG = {
+ elevenlabs: {
+ baseUrl: "https://api.elevenlabs.io/v1",
+ authHeaders: (key: string): Record<string, string> => ({
+ "xi-api-key": key,
+ }),
+ },
+ openai: {
+ baseUrl: "https://api.openai.com/v1",
+ authHeaders: (key: string): Record<string, string> => ({
+ Authorization: `Bearer ${key}`,
+ }),
+ },
+ anthropic: {
+ baseUrl: "https://api.anthropic.com/v1",
+ authHeaders: (key: string): Record<string, string> => ({
+ "x-api-key": key,
+ "anthropic-version": "2023-06-01",
+ "anthropic-dangerous-direct-browser-access": "true",
+ }),
+ },
+} as const;
+
+export type ApiService = keyof typeof DIRECT_CONFIG;
+
+/**
+ * Fetch from a third-party API, automatically routing through the proxy
+ * in production builds.
+ *
+ * @param service - Target service (elevenlabs, openai, anthropic)
+ * @param path - API path including leading slash, e.g. "/models" or "/text-to-speech/voiceId"
+ * @param apiKey - Decrypted API key for the service
+ * @param options - Standard RequestInit (method, body, extra headers, etc.)
+ */
+export async function apiFetch(
+ service: ApiService,
+ path: string,
+ apiKey: string,
+ options: globalThis.RequestInit = {},
+): Promise<Response> {
+ const extraHeaders = (options.headers ?? {}) as Record<string, string>;
+
+ if (isDev) {
+ const config = DIRECT_CONFIG[service];
+ const url = `${config.baseUrl}${path}`;
+ return fetch(url, {
+ ...options,
+ headers: {
+ ...config.authHeaders(apiKey),
+ ...extraHeaders,
+ },
+ });
+ }
+
+ // Production: route through same-origin proxy
+ const url = `/api/proxy/${service}${path}`;
+ return fetch(url, {
+ ...options,
+ headers: {
+ "x-proxy-api-key": apiKey,
+ ...extraHeaders,
+ },
+ });
+}