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): harden proxy and fix critical review findings

lvalicsbf3e0ce7dfa6
diff --git a/apps/web/functions/api/proxy/[[catchall]].ts b/apps/web/functions/api/proxy/[[catchall]].ts
index 911d0237..66ae0182 100644
--- a/apps/web/functions/api/proxy/[[catchall]].ts
+++ b/apps/web/functions/api/proxy/[[catchall]].ts
@@ -15,20 +15,24 @@
interface ServiceConfig {
baseUrl: string;
+ allowedPaths: RegExp;
authHeaders: (key: string) => Record<string, string>;
}
const SERVICE_CONFIG: Record<string, ServiceConfig> = {
elevenlabs: {
baseUrl: "https://api.elevenlabs.io/v1",
+ allowedPaths: /^(voices|models|text-to-speech\/[\w-]+)$/,
authHeaders: (key) => ({ "xi-api-key": key }),
},
openai: {
baseUrl: "https://api.openai.com/v1",
+ allowedPaths: /^(chat\/completions|models)$/,
authHeaders: (key) => ({ Authorization: `Bearer ${key}` }),
},
anthropic: {
baseUrl: "https://api.anthropic.com/v1",
+ allowedPaths: /^(messages)$/,
authHeaders: (key) => ({
"x-api-key": key,
"anthropic-version": "2023-06-01",
@@ -36,50 +40,87 @@ const SERVICE_CONFIG: Record<string, ServiceConfig> = {
},
};
-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",
-};
+const ALLOWED_ORIGINS = [
+ "https://openreel.pages.dev",
+ "https://openreel-preview.pages.dev",
+];
+
+const MAX_REQUEST_BODY_BYTES = 1_048_576; // 1 MB
+const UPSTREAM_TIMEOUT_MS = 25_000;
+
+function getCorsHeaders(request: Request): Record<string, string> {
+ const origin = request.headers.get("Origin") ?? "";
+ const allowedOrigin = ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0];
+ return {
+ "Access-Control-Allow-Origin": allowedOrigin,
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
+ "Access-Control-Allow-Headers": "Content-Type, x-proxy-api-key",
+ Vary: "Origin",
+ };
+}
+
+function jsonError(
+ message: string,
+ status: number,
+ corsHeaders: Record<string, string>,
+): Response {
+ return new Response(JSON.stringify({ error: message }), {
+ status,
+ headers: { "Content-Type": "application/json", ...corsHeaders },
+ });
+}
export const onRequest: PagesFunction = async (context) => {
- // Handle CORS preflight
+ const corsHeaders = getCorsHeaders(context.request);
+
if (context.request.method === "OPTIONS") {
- return new Response(null, { status: 204, headers: CORS_HEADERS });
+ return new Response(null, { status: 204, headers: corsHeaders });
}
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 },
- });
+ return jsonError("Missing service in URL path", 400, corsHeaders);
}
const service = pathParts[0];
const remainingPath = pathParts.slice(1).join("/");
+ if (remainingPath.includes("..") || remainingPath.includes("//")) {
+ return jsonError("Invalid path", 400, corsHeaders);
+ }
+
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 },
- });
+ return jsonError(`Unknown service: ${service}`, 400, corsHeaders);
+ }
+
+ if (remainingPath && !config.allowedPaths.test(remainingPath)) {
+ return jsonError("Path not allowed for this service", 403, corsHeaders);
}
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 },
- });
+ return jsonError("Missing x-proxy-api-key header", 401, corsHeaders);
}
+ if (
+ context.request.method === "POST" &&
+ context.request.headers.has("Content-Length")
+ ) {
+ const contentLength = parseInt(
+ context.request.headers.get("Content-Length") ?? "0",
+ 10,
+ );
+ if (contentLength > MAX_REQUEST_BODY_BYTES) {
+ return jsonError("Request body too large", 413, corsHeaders);
+ }
+ }
+
+ const originalUrl = new URL(context.request.url);
const targetUrl = remainingPath
- ? `${config.baseUrl}/${remainingPath}`
- : config.baseUrl;
+ ? `${config.baseUrl}/${remainingPath}${originalUrl.search}`
+ : `${config.baseUrl}${originalUrl.search}`;
- // Build headers for the upstream request
const upstreamHeaders = new Headers();
const contentType = context.request.headers.get("Content-Type");
if (contentType) {
@@ -89,15 +130,24 @@ export const onRequest: PagesFunction = async (context) => {
upstreamHeaders.set(key, value);
}
- const upstreamResponse = await fetch(targetUrl, {
- method: context.request.method,
- headers: upstreamHeaders,
- body: context.request.method !== "GET" ? context.request.body : undefined,
- });
+ let upstreamResponse: Response;
+ try {
+ upstreamResponse = await fetch(targetUrl, {
+ method: context.request.method,
+ headers: upstreamHeaders,
+ body: context.request.method !== "GET" ? context.request.body : undefined,
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
+ });
+ } catch (err) {
+ const message =
+ err instanceof DOMException && err.name === "TimeoutError"
+ ? "Upstream request timed out"
+ : "Failed to reach upstream service";
+ return jsonError(message, 502, corsHeaders);
+ }
- // Forward the response, adding CORS headers
const responseHeaders = new Headers(upstreamResponse.headers);
- for (const [key, value] of Object.entries(CORS_HEADERS)) {
+ for (const [key, value] of Object.entries(corsHeaders)) {
responseHeaders.set(key, value);
}
diff --git a/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx b/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
index 9b230998..60a50bde 100644
--- a/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
+++ b/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
@@ -106,7 +106,7 @@ export const TextToSpeechPanel: React.FC = () => {
return (
<div className="space-y-3 w-full min-w-0 max-w-full">
- <audio ref={audioRef} onEnded={handleAudioEnded} className="hidden" />
+ <audio ref={audioRef as React.RefObject<HTMLAudioElement>} onEnded={handleAudioEnded} className="hidden" />
<div className="flex items-center justify-between p-2 bg-primary/10 rounded-lg border border-primary/30">
<div className="flex items-center gap-2">
diff --git a/apps/web/src/components/editor/inspector/hooks/useTtsActions.ts b/apps/web/src/components/editor/inspector/hooks/useTtsActions.ts
index fd692bc9..f88ebcdf 100644
--- a/apps/web/src/components/editor/inspector/hooks/useTtsActions.ts
+++ b/apps/web/src/components/editor/inspector/hooks/useTtsActions.ts
@@ -1,4 +1,4 @@
-import { useState, useCallback, useRef } from "react";
+import { useState, useCallback, useRef, useEffect } from "react";
import type { TtsProvider } from "../../../../stores/settings-store";
import { useProjectStore } from "../../../../stores/project-store";
import { PIPER_VOICES } from "../tts-constants";
@@ -69,6 +69,18 @@ export function useTtsActions(options: UseTtsActionsOptions): UseTtsActionsRetur
const audioRef = useRef<HTMLAudioElement | null>(null);
const audioUrlRef = useRef<string | null>(null);
+ useEffect(() => {
+ return () => {
+ if (audioUrlRef.current) {
+ URL.revokeObjectURL(audioUrlRef.current);
+ audioUrlRef.current = null;
+ }
+ if (audioRef.current) {
+ audioRef.current.pause();
+ }
+ };
+ }, []);
+
const getSelectedVoiceName = useCallback((): string => {
if (provider === "piper") {
return PIPER_VOICES.find((v) => v.id === selectedVoice)?.name ?? "TTS";
diff --git a/apps/web/src/components/editor/settings/SettingsDialog.tsx b/apps/web/src/components/editor/settings/SettingsDialog.tsx
index b18bd903..dc184c3a 100644
--- a/apps/web/src/components/editor/settings/SettingsDialog.tsx
+++ b/apps/web/src/components/editor/settings/SettingsDialog.tsx
@@ -36,11 +36,14 @@ export const SettingsDialog: React.FC = () => {
</DialogDescription>
</DialogHeader>
- {/* Tab bar */}
- <div className="flex gap-1 p-1 bg-muted rounded-md">
+ <div role="tablist" aria-label="Settings" className="flex gap-1 p-1 bg-muted rounded-md">
{TABS.map((tab) => (
<button
key={tab.id}
+ role="tab"
+ aria-selected={settingsTab === tab.id}
+ aria-controls={`settings-tabpanel-${tab.id}`}
+ id={`settings-tab-${tab.id}`}
onClick={() => setTab(tab.id)}
className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-sm transition-colors ${
settingsTab === tab.id
@@ -54,8 +57,12 @@ export const SettingsDialog: React.FC = () => {
))}
</div>
- {/* Tab content */}
- <div className="flex-1 overflow-y-auto pr-1 mt-2">
+ <div
+ role="tabpanel"
+ id={`settings-tabpanel-${settingsTab}`}
+ aria-labelledby={`settings-tab-${settingsTab}`}
+ className="flex-1 overflow-y-auto pr-1 mt-2"
+ >
{settingsTab === "general" && <GeneralPanel />}
{settingsTab === "api-keys" && <ApiKeysPanel />}
</div>