|
| 1 | +#!/usr/bin/env -S npm run tsn -T |
| 2 | + |
| 3 | +import { BrowserUse } from 'browser-use-sdk'; |
| 4 | +import { |
| 5 | + verifyWebhookEventSignature, |
| 6 | + type WebhookAgentTaskStatusUpdatePayload, |
| 7 | +} from 'browser-use-sdk/lib/webhooks'; |
| 8 | +import { createServer, IncomingMessage, type Server, type ServerResponse } from 'http'; |
| 9 | + |
| 10 | +import { env } from './utils'; |
| 11 | + |
| 12 | +env(); |
| 13 | + |
| 14 | +const PORT = 3000; |
| 15 | +const WAIT_FOR_TASK_FINISH_TIMEOUT = 60_000; |
| 16 | + |
| 17 | +// Environment --------------------------------------------------------------- |
| 18 | + |
| 19 | +const SECRET_KEY = process.env['SECRET_KEY']; |
| 20 | + |
| 21 | +// API ----------------------------------------------------------------------- |
| 22 | + |
| 23 | +// gets API Key from environment variable BROWSER_USE_API_KEY |
| 24 | +const browseruse = new BrowserUse(); |
| 25 | + |
| 26 | +// |
| 27 | + |
| 28 | +const whServerRef: { current: Server | null } = { current: null }; |
| 29 | + |
| 30 | +async function main() { |
| 31 | + if (!SECRET_KEY) { |
| 32 | + console.error('SECRET_KEY is not set'); |
| 33 | + process.exit(1); |
| 34 | + } |
| 35 | + |
| 36 | + console.log('Starting Browser Use Webhook Example'); |
| 37 | + console.log('Run `browser-use listen --dev http://localhost:3000/webhook`!'); |
| 38 | + |
| 39 | + // Start a Webhook Server |
| 40 | + |
| 41 | + const callback: { current: ((event: WebhookAgentTaskStatusUpdatePayload) => Promise<void>) | null } = { |
| 42 | + current: null, |
| 43 | + }; |
| 44 | + |
| 45 | + const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { |
| 46 | + if (req.method === 'POST' && req.url === '/webhook') { |
| 47 | + let body = ''; |
| 48 | + |
| 49 | + req.on('data', (chunk) => { |
| 50 | + body += chunk.toString(); |
| 51 | + }); |
| 52 | + |
| 53 | + req.on('end', async () => { |
| 54 | + try { |
| 55 | + const signature = req.headers['x-browser-use-signature'] as string; |
| 56 | + const timestamp = req.headers['x-browser-use-timestamp'] as string; |
| 57 | + |
| 58 | + const event = await verifyWebhookEventSignature( |
| 59 | + { |
| 60 | + evt: body, |
| 61 | + signature, |
| 62 | + timestamp, |
| 63 | + }, |
| 64 | + { |
| 65 | + secret: SECRET_KEY, |
| 66 | + }, |
| 67 | + ); |
| 68 | + |
| 69 | + if (!event.ok) { |
| 70 | + console.log('❌ Invalid webhook signature'); |
| 71 | + console.log(body); |
| 72 | + console.log(signature, 'signature'); |
| 73 | + console.log(timestamp, 'timestamp'); |
| 74 | + console.log(SECRET_KEY, 'SECRET_KEY'); |
| 75 | + |
| 76 | + res.writeHead(401, { 'Content-Type': 'application/json' }); |
| 77 | + res.end(JSON.stringify({ error: 'Invalid signature' })); |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + switch (event.event.type) { |
| 82 | + case 'agent.task.status_update': |
| 83 | + await callback.current?.(event.event.payload); |
| 84 | + |
| 85 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 86 | + res.end(JSON.stringify({ received: true })); |
| 87 | + break; |
| 88 | + case 'test': |
| 89 | + console.log('🧪 Test webhook received'); |
| 90 | + |
| 91 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 92 | + res.end(JSON.stringify({ received: true })); |
| 93 | + break; |
| 94 | + default: |
| 95 | + console.log('🧪 Unknown webhook received'); |
| 96 | + |
| 97 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 98 | + res.end(JSON.stringify({ received: true })); |
| 99 | + break; |
| 100 | + } |
| 101 | + } catch (error) { |
| 102 | + console.error(error); |
| 103 | + } |
| 104 | + }); |
| 105 | + } else if (req.method === 'GET' && req.url === '/health') { |
| 106 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 107 | + res.end(JSON.stringify({ status: 'ok', timestamp: new Date().toISOString() })); |
| 108 | + } else { |
| 109 | + res.writeHead(404, { 'Content-Type': 'application/json' }); |
| 110 | + res.end(JSON.stringify({ error: 'Not found' })); |
| 111 | + } |
| 112 | + }); |
| 113 | + |
| 114 | + whServerRef.current = server; |
| 115 | + |
| 116 | + server.listen(PORT, () => { |
| 117 | + console.log(`🌐 Webhook server listening on port ${PORT}`); |
| 118 | + console.log(`🔗 Health check: http://localhost:${PORT}/health`); |
| 119 | + }); |
| 120 | + |
| 121 | + await new Promise((resolve) => setTimeout(resolve, 1000)); |
| 122 | + |
| 123 | + // Create Task |
| 124 | + console.log('📝 Creating a new task...'); |
| 125 | + const task = await browseruse.tasks.create({ |
| 126 | + task: "What's the weather like in San Francisco and what's the current temperature?", |
| 127 | + }); |
| 128 | + |
| 129 | + console.log(`🔗 Task created: ${task.id}`); |
| 130 | + |
| 131 | + await new Promise<void>((resolve, reject) => { |
| 132 | + // NOTE: We set a timeout so we can catch it when the task is stuck |
| 133 | + // and stop the example. |
| 134 | + const interval = setTimeout(() => { |
| 135 | + reject(new Error('Task creation timed out')); |
| 136 | + }, WAIT_FOR_TASK_FINISH_TIMEOUT); |
| 137 | + |
| 138 | + // NOTE: We attach the callback to the current reference so we can receive updates from the server. |
| 139 | + callback.current = async (payload) => { |
| 140 | + if (payload.task_id !== task.id) { |
| 141 | + return; |
| 142 | + } |
| 143 | + |
| 144 | + console.log('🔄 Task status updated:', payload.status); |
| 145 | + |
| 146 | + if (payload.status === 'finished') { |
| 147 | + clearTimeout(interval); |
| 148 | + resolve(); |
| 149 | + } |
| 150 | + }; |
| 151 | + }).catch((error) => { |
| 152 | + console.error(error); |
| 153 | + process.exit(1); |
| 154 | + }); |
| 155 | + |
| 156 | + // Fetch final task result |
| 157 | + const status = await browseruse.tasks.retrieve(task.id); |
| 158 | + |
| 159 | + console.log('🎯 Final Task Status'); |
| 160 | + console.log('OUTPUT:'); |
| 161 | + console.log(status.doneOutput); |
| 162 | + |
| 163 | + server.close(); |
| 164 | +} |
| 165 | + |
| 166 | +// Handle graceful shutdown |
| 167 | +process.on('SIGINT', () => { |
| 168 | + console.log('\n👋 Shutting down gracefully...'); |
| 169 | + whServerRef.current?.close(); |
| 170 | + process.exit(0); |
| 171 | +}); |
| 172 | + |
| 173 | +// |
| 174 | + |
| 175 | +if (require.main === module) { |
| 176 | + main().catch(console.error); |
| 177 | +} |
0 commit comments