|
5 | 5 | import { NextResponse } from 'next/server'; |
6 | 6 | import { GUIAgent, StatusEnum } from '@ui-tars/sdk'; |
7 | 7 | import { BrowserbaseOperator } from '@ui-tars/operator-browserbase'; |
| 8 | +import { z } from 'zod'; |
8 | 9 |
|
9 | 10 | export const dynamic = 'force-dynamic'; |
10 | 11 |
|
| 12 | +// Request rate limiting map: tracks requests per API key |
| 13 | +const requestRateLimitMap = new Map<string, { count: number; resetTime: number }>(); |
| 14 | +const RATE_LIMIT_WINDOW_MS = 60 * 1000; // 1 minute |
| 15 | +const MAX_REQUESTS_PER_WINDOW = 10; |
| 16 | + |
| 17 | +// Request body schema validation |
| 18 | +const AgentRequestSchema = z.object({ |
| 19 | + goal: z.string().min(1).max(5000), |
| 20 | + sessionId: z.string().min(1).max(256), |
| 21 | +}); |
| 22 | + |
| 23 | +type AgentRequest = z.infer<typeof AgentRequestSchema>; |
| 24 | + |
| 25 | +/** |
| 26 | + * Verify API authentication via Authorization header |
| 27 | + * SECURITY: Requires valid authorization token to prevent unauthorized access |
| 28 | + */ |
| 29 | +function verifyAuthentication(request: Request): string | null { |
| 30 | + const authHeader = request.headers.get('authorization'); |
| 31 | + if (!authHeader?.startsWith('Bearer ')) { |
| 32 | + return null; |
| 33 | + } |
| 34 | + const token = authHeader.substring(7); |
| 35 | + const expectedToken = process.env.AGENT_API_SECRET; |
| 36 | + if (!expectedToken || token !== expectedToken) { |
| 37 | + return null; |
| 38 | + } |
| 39 | + return token; |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Check rate limiting for the request |
| 44 | + * SECURITY: Prevents abuse by limiting requests per authentication token |
| 45 | + */ |
| 46 | +function checkRateLimit(apiKey: string): boolean { |
| 47 | + const now = Date.now(); |
| 48 | + const record = requestRateLimitMap.get(apiKey); |
| 49 | + |
| 50 | + if (!record || now >= record.resetTime) { |
| 51 | + requestRateLimitMap.set(apiKey, { count: 1, resetTime: now + RATE_LIMIT_WINDOW_MS }); |
| 52 | + return true; |
| 53 | + } |
| 54 | + |
| 55 | + if (record.count >= MAX_REQUESTS_PER_WINDOW) { |
| 56 | + return false; |
| 57 | + } |
| 58 | + |
| 59 | + record.count++; |
| 60 | + return true; |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * Structured logging for security audit trail |
| 65 | + * SECURITY: Provides comprehensive audit logs for forensic analysis |
| 66 | + */ |
| 67 | +function logSecurityEvent( |
| 68 | + eventType: string, |
| 69 | + clientIp: string | null, |
| 70 | + userId: string | null, |
| 71 | + details: Record<string, unknown>, |
| 72 | +) { |
| 73 | + const timestamp = new Date().toISOString(); |
| 74 | + const logEntry = { |
| 75 | + timestamp, |
| 76 | + eventType, |
| 77 | + clientIp: clientIp || 'unknown', |
| 78 | + userId: userId || 'unauthenticated', |
| 79 | + ...details, |
| 80 | + }; |
| 81 | + console.log(JSON.stringify(logEntry)); |
| 82 | +} |
| 83 | + |
11 | 84 | const SYSTEM_PROMPT = `You are a GUI agent. You are given a task and your action history, with screenshots. You need to perform the next action to complete the task. |
12 | 85 |
|
13 | 86 | ## Output Format |
@@ -37,19 +110,50 @@ export async function POST(request: Request) { |
37 | 110 | const responseStream = new TransformStream(); |
38 | 111 | const writer = responseStream.writable.getWriter(); |
39 | 112 | const encoder = new TextEncoder(); |
| 113 | + |
| 114 | + // Extract client IP for logging (SECURITY: for audit trail) |
| 115 | + const clientIp = request.headers.get('x-forwarded-for') || |
| 116 | + request.headers.get('x-real-ip') || |
| 117 | + 'unknown'; |
40 | 118 |
|
41 | 119 | try { |
42 | | - console.log('request', request); |
43 | | - const body = await request.json(); |
44 | | - const { goal, sessionId } = body; |
| 120 | + // SECURITY: Verify authentication before processing |
| 121 | + const apiToken = verifyAuthentication(request); |
| 122 | + if (!apiToken) { |
| 123 | + logSecurityEvent('auth_failed', clientIp, null, { reason: 'missing_or_invalid_token' }); |
| 124 | + return NextResponse.json( |
| 125 | + { error: 'Unauthorized: Missing or invalid authorization token' }, |
| 126 | + { status: 401 }, |
| 127 | + ); |
| 128 | + } |
| 129 | + |
| 130 | + // SECURITY: Check rate limiting |
| 131 | + if (!checkRateLimit(apiToken)) { |
| 132 | + logSecurityEvent('rate_limit_exceeded', clientIp, apiToken, {}); |
| 133 | + return NextResponse.json( |
| 134 | + { error: 'Rate limit exceeded' }, |
| 135 | + { status: 429 }, |
| 136 | + ); |
| 137 | + } |
45 | 138 |
|
46 | | - if (!sessionId) { |
| 139 | + // SECURITY: Validate request body schema |
| 140 | + let parsedBody: AgentRequest; |
| 141 | + try { |
| 142 | + const body = await request.json(); |
| 143 | + parsedBody = AgentRequestSchema.parse(body); |
| 144 | + } catch (error) { |
| 145 | + logSecurityEvent('validation_failed', clientIp, apiToken, { |
| 146 | + error: error instanceof Error ? error.message : 'Invalid request body' |
| 147 | + }); |
47 | 148 | return NextResponse.json( |
48 | | - { error: 'Missing sessionId in request body' }, |
| 149 | + { error: 'Invalid request body: goal and sessionId are required' }, |
49 | 150 | { status: 400 }, |
50 | 151 | ); |
51 | 152 | } |
52 | 153 |
|
| 154 | + const { goal, sessionId } = parsedBody; |
| 155 | + logSecurityEvent('request_accepted', clientIp, apiToken, { goal: goal.substring(0, 100) }); |
| 156 | + |
53 | 157 | console.log('sessionIdsessionIdsessionId', sessionId); |
54 | 158 | const operator = new BrowserbaseOperator({ |
55 | 159 | // browserbaseSessionID: sessionId, |
@@ -104,8 +208,10 @@ export async function POST(request: Request) { |
104 | 208 |
|
105 | 209 | guiAgent.run(goal); |
106 | 210 | } catch (error) { |
| 211 | + const errorMessage = error instanceof Error ? error.message : 'Unknown error'; |
| 212 | + logSecurityEvent('processing_error', clientIp, null, { error: errorMessage }); |
107 | 213 | console.error('Error in agent endpoint:', error); |
108 | | - writer.write(encoder.encode(JSON.stringify({ error }))); |
| 214 | + writer.write(encoder.encode(JSON.stringify({ error: 'Internal server error' }))); |
109 | 215 | writer.close(); |
110 | 216 | } |
111 | 217 |
|
|
0 commit comments