Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Improve security for sandbox video stream by introducing token
Vasek Mlejnskyc3d5bda61d59
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 119087c04..074d2bd73 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -42,7 +42,7 @@"autoprefixer": "^10.4.7","class-variance-authority": "^0.7.0","clsx": "^1.2.1",- "e2b": "^0.16.2",+ "e2b": "^1.0.5","fast-glob": "^3.3.0","fast-xml-parser": "^4.3.3","flexsearch": "^0.7.31",diff --git a/apps/web/src/app/api/stream/sandbox/[sandboxId]/route.ts b/apps/web/src/app/api/stream/sandbox/[sandboxId]/route.tsnew file mode 100644index 000000000..e4b26773c--- /dev/null+++ b/apps/web/src/app/api/stream/sandbox/[sandboxId]/route.ts@@ -0,0 +1,42 @@+import { NextResponse } from 'next/server'+import { createClient } from '@supabase/supabase-js'+import { verifySandbox } from '@/lib/utils'++const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!+const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!++const supabase = createClient(supabaseUrl, supabaseServiceKey)++export async function GET(request: Request, { params }: { params: { sandboxId: string } }) {+ const apiKey = request.headers.get('X-API-Key')+ const sandboxId = params.sandboxId++ if (!sandboxId) {+ return NextResponse.json({ error: 'Missing sandbox ID' }, { status: 400 })+ }++ if (!apiKey) {+ return NextResponse.json({ error: 'Missing E2B API Key' }, { status: 400 })+ }++ if (!(await verifySandbox(apiKey, sandboxId))) {+ return NextResponse.json({ error: 'Invalid E2B API Key' }, { status: 401 })+ }++ const { data: stream, error } = await supabase+ .from('sandbox_streams')+ .select('token')+ .eq('sandbox_id', sandboxId)+ .single()++ if (error) {+ return NextResponse.json({ error: `Failed to retrieve stream - ${error.message}` }, { status: 500 })+ }++ if (!stream) {+ return NextResponse.json({ error: `Stream not found for sandbox ${sandboxId}` }, { status: 404 })+ }++ return NextResponse.json({ token: stream.token }, { status: 200 })+}+diff --git a/apps/web/src/app/api/stream/sandbox/route.ts b/apps/web/src/app/api/stream/sandbox/route.tsindex 09282e39a..754e2dde4 100644--- a/apps/web/src/app/api/stream/sandbox/route.ts+++ b/apps/web/src/app/api/stream/sandbox/route.ts@@ -1,7 +1,7 @@import Mux from '@mux/mux-node'import { NextResponse } from 'next/server'-import { createClient } from '@supabase/supabase-js'+import { verifySandbox } from '@/lib/utils'const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!@@ -13,13 +13,40 @@ const mux = new Mux({tokenSecret: process.env.MUX_TOKEN_SECRET})++// Create a new live stream and return the stream keyexport async function POST(request: Request) {+ const apiKey = request.headers.get('X-API-Key')const { sandboxId } = await request.json()if (!sandboxId) {return NextResponse.json({ error: 'Missing sandboxId' }, { status: 400 })}+ if (!apiKey) {+ return NextResponse.json({ error: 'Missing E2B API Key' }, { status: 400 })+ }++ if (!(await verifySandbox(apiKey, sandboxId))) {+ return NextResponse.json({ error: 'Invalid E2B API Key' }, { status: 401 })+ }++ // Check if a stream already exists for the sandbox+ const { data: existingStream, error: existingStreamError } = await supabase+ .from('sandbox_streams')+ .select('token')+ .eq('sandbox_id', sandboxId)+ .single()++ if (existingStreamError && existingStreamError.code !== 'PGRST116') {+ return NextResponse.json({ error: `Failed to check existing stream - ${existingStreamError.message}` }, { status: 500 })+ }++ if (existingStream) {+ return NextResponse.json({ error: `Stream for the sandbox '${sandboxId}' already exists. There can be only one stream per sandbox.` }, { status: 400 })+ }++ // The stream doesn't exist yet, so create a new live streamconst liveStream = await mux.video.liveStreams.create({latency_mode: 'low',reconnect_window: 60,@@ -31,9 +58,19 @@ export async function POST(request: Request) {return NextResponse.json({ error: 'Failed to create live stream' }, { status: 500 })}- await supabase+ const { data, error }: { data: { token: string } | null, error: any } = await supabase.from('sandbox_streams').insert([{ sandbox_id: sandboxId, playback_id: liveStream.playback_ids[0].id }])+ .select('token')+ .single()++ if (error) {+ return NextResponse.json({ error: `Failed to insert and retrieve token - ${error.message}` }, { status: 500 })+ }++ if (!data) {+ return NextResponse.json({ error: 'Failed to insert and retrieve token - no data' }, { status: 500 })+ }- return NextResponse.json({ streamKey: liveStream.stream_key }, { status: 201 })+ return NextResponse.json({ streamKey: liveStream.stream_key, token: data.token }, { status: 201 })}diff --git a/apps/web/src/app/stream/sandbox/[sandboxId]/layout.tsx b/apps/web/src/app/stream/sandbox/[sandboxId]/layout.tsxdeleted file mode 100644index ba57e405e..000000000--- a/apps/web/src/app/stream/sandbox/[sandboxId]/layout.tsx+++ /dev/null@@ -1,9 +0,0 @@-import { Fragment } from 'react'--export default async function Layout({ children }) {- return (- <Fragment>- {children}- </Fragment>- )-}diff --git a/apps/web/src/app/stream/sandbox/[sandboxId]/page.tsx b/apps/web/src/app/stream/sandbox/[sandboxId]/page.tsxindex 918e2bd39..eb23c704e 100644--- a/apps/web/src/app/stream/sandbox/[sandboxId]/page.tsx+++ b/apps/web/src/app/stream/sandbox/[sandboxId]/page.tsx@@ -12,11 +12,12 @@ interface SandboxStream {playbackId: string}-async function fetchStream(sandboxId: string): Promise<SandboxStream | null> {+async function fetchStream(sandboxId: string, token: string): Promise<SandboxStream | null> {const { data, error } = await supabase.from('sandbox_streams').select('playback_id').eq('sandbox_id', sandboxId)+ .eq('token', token).single()if (error || !data) {@@ -26,8 +27,20 @@ async function fetchStream(sandboxId: string): Promise<SandboxStream | null> {return { sandboxId, playbackId: data.playback_id }}-export default async function StreamPage({ params }: { params: { sandboxId: string } }) {- const stream = await fetchStream(params.sandboxId)+export default async function StreamPage({+ params,+ searchParams // Add searchParams to props+}: {+ params: { sandboxId: string }+ searchParams: { token?: string } // Add type for searchParams+}) {+ const token = searchParams.token++ if (!token) {+ return <div>Missing token</div>+ }++ const stream = await fetchStream(params.sandboxId, token)if (!stream) {return <div>Stream not found</div>@@ -35,7 +48,7 @@ export default async function StreamPage({ params }: { params: { sandboxId: strireturn (<Suspense fallback={<div className="h-full w-full flex items-center justify-center">Loading stream...</div>}>- <div className="flex justify-center">+ <div className="flex justify-center max-h-[768px]"><MuxPlayerautoPlaymuteddiff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.tsindex d32b0fe65..2e5021059 100644--- a/apps/web/src/lib/utils.ts+++ b/apps/web/src/lib/utils.ts@@ -1,6 +1,13 @@+import { Sandbox } from 'e2b'import { type ClassValue, clsx } from 'clsx'import { twMerge } from 'tailwind-merge'export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs))}++// Verify that the sandbox exists and is associated with the API key+export async function verifySandbox(apiKey: string, sandboxId: string) {+ const sandboxes = await Sandbox.list({ apiKey })+ return sandboxes.some((sandbox) => sandbox.sandboxId === sandboxId)+}\ No newline at end of filediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1870d2672..3bf18285b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -121,8 +121,8 @@ importers:specifier: ^1.2.1version: 1.2.1e2b:- specifier: ^0.16.2- version: 0.16.2+ specifier: ^1.0.5+ version: 1.0.5fast-glob:specifier: ^3.3.0version: 3.3.1@@ -3979,14 +3979,14 @@ packages:resolution: {integrity: sha512-1A8za6ws41LQgv9HrE/66jyC5yuSjQ3L/KOpFtoBilsAK2iA2wuS5rTt1OCzIvtS2V7nVmedsUU+DGRcjBmOYA==}- resolution: {integrity: sha512-xKmVK4ipgVQPJ/uyyrfH9LnaawERRWt8U2UZhdhGfzdL/QU/OpBjuhoIbFCv1Uy6qXV4nIiJ6Nw4MBC4HmXf1g==}- engines: {node: '>=18'}-resolution: {integrity: sha512-A3T56Dso60AXTJO+V0zUNecYXDQB9jv6nm94DpLuEshjlk2MfbCF99rHgYUbOp9IOmh3EBv0RdEGIY5l4zJZQA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-0c2xqNQfVcVBmETsd1bXWCYaN3iVl7m81dJVcjB7O2/c15A7t0s/FkydcZGzVvfZchj40/1f09AdjGX6nk1eNQ==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}@@ -5077,11 +5077,6 @@ packages:resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}- resolution: {integrity: sha512-muId7Zzn9ywDsyXgTIafTry2sV3nySZeUDe6YedVd1Hvuuep5AsIlqK+XefWpYTyJG5e503F2xIuT2lcU6rCSw==}- peerDependencies:- ws: '*'-resolution: {integrity: sha512-hJnEP2Xk4+44DDwJqUQGdXal5VbyeWLaPyDl2AQc242Zr7iqz4DgpQOrEzglWVMGHMDCkguLHEKxd1+rOsmgSQ==}engines: {node: '>=4'}@@ -6030,10 +6025,6 @@ packages:resolution: {integrity: sha512-zM6elH0EZStD/gSiNlcPrzXcVQ/pZo3BDvC6CDwRDUt1dDzxlshpmQnpD6cZaJ39THaSmwVCxxRrPKNM1hHrDg==}- resolution: {integrity: sha512-smLZPck4OkKMNExcw8jMgrMOGgVGx2N/s6DbKL2ftNl77g5HfoGpZGFy79RBzU/EkaO0OZpwBnslfdBfh7ZcWg==}- engines: {node: '>= 12.0.0', npm: '>= 7.0.0'}-resolution: {integrity: sha512-1eNjQtbfNi5Z/kFhagDIaIRj6qqDzhjNJKz8cmMW0CVdGwT6e1GLbAfgI0d28VTJa1A8jz82jm/4dG8qNoNS8g==}@@ -6166,9 +6157,6 @@ packages:resolution: {integrity: sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==}- resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}-resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}engines: {node: '>=8'}@@ -7870,18 +7858,6 @@ packages:resolution: {integrity: sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==}- resolution: {integrity: sha512-W5OZiCjXEmk0yZ66ZN82beM5Sz7l7coYxpRkzS+p9PP+ToQry8szKh+61eNktr7EA9DOwvFGhfC605jDHbP6QQ==}- engines: {node: '>=10.0.0'}- peerDependencies:- bufferutil: ^4.0.1- utf-8-validate: '>=5.0.2'- peerDependenciesMeta:- bufferutil:- optional: true- utf-8-validate:- optional: true-resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==}engines: {node: '>=10.0.0'}@@ -12120,18 +12096,6 @@ snapshots:- dependencies:- normalize-path: 3.0.0- openapi-typescript-fetch: 1.1.3- path-browserify: 1.0.1- platform: 1.3.6- ws: 8.15.1([email protected])([email protected])- optionalDependencies:- bufferutil: 4.0.8- utf-8-validate: 6.0.3-dependencies:'@bufbuild/protobuf': 1.10.0@@ -12141,6 +12105,15 @@ snapshots:openapi-fetch: 0.9.8platform: 1.3.6+ dependencies:+ '@bufbuild/protobuf': 2.2.2+ '@connectrpc/connect': 2.0.0-rc.3(@bufbuild/[email protected])+ '@connectrpc/connect-web': 2.0.0-rc.3(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))+ compare-versions: 6.1.1+ openapi-fetch: 0.9.8+ platform: 1.3.6+@@ -13493,10 +13466,6 @@ snapshots:- dependencies:- ws: 8.15.1([email protected])([email protected])-@@ -14812,8 +14781,6 @@ snapshots:dependencies:openapi-typescript-helpers: 0.0.8- [email protected]: {}-@@ -14980,8 +14947,6 @@ snapshots:- [email protected]: {}-@@ -16859,11 +16824,6 @@ snapshots:signal-exit: 3.0.7typedarray-to-buffer: 3.1.5- optionalDependencies:- bufferutil: 4.0.8- utf-8-validate: 6.0.3-optionalDependencies:bufferutil: 4.0.8