@devries-cameron20 / composio Mirror · read-only
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 125 lines 4.31 KB
Raw
1 /**
2 * Webhook Verification Server Example
3 *
4 * This example demonstrates how to verify incoming Composio webhooks
5 * using Bun.serve with the new verifyWebhook API.
6 *
7 * Prerequisites:
8 * 1. Set up your COMPOSIO_API_KEY and COMPOSIO_WEBHOOK_SECRET in the .env file
9 * 2. Install dependencies: pnpm install
10 * 3. Run the server: pnpm webhook
11 * 4. Expose your local server using telebit: `telebit http 3000`
12 * 5. Configure the webhook URL in your Composio dashboard: `https://<your-telebit-url>/webhook`
13 */
14
15 import {
16 Composio,
17 ComposioWebhookSignatureVerificationError,
18 ComposioWebhookPayloadError,
19 } from '@composio/core';
20 import 'dotenv/config';
21
22 const PORT = process.env.PORT || 3000;
23 const WEBHOOK_SECRET = process.env.COMPOSIO_WEBHOOK_SECRET;
24
25 if (!WEBHOOK_SECRET) {
26 console.error('❌ COMPOSIO_WEBHOOK_SECRET is required in .env file');
27 process.exit(1);
28 }
29
30 const composio = new Composio({
31 apiKey: process.env.COMPOSIO_API_KEY,
32 });
33
34 console.log(`🚀 Starting webhook server on port ${PORT}...`);
35
36 const server = Bun.serve({
37 port: PORT,
38 async fetch(request) {
39 const url = new URL(request.url);
40
41 // Health check endpoint
42 if (url.pathname === '/health') {
43 return new Response('OK', { status: 200 });
44 }
45
46 // Webhook endpoint
47 if (url.pathname === '/webhook' && request.method === 'POST') {
48 try {
49 // Get required headers
50 const webhookId = request.headers.get('webhook-id') || '';
51 const webhookTimestamp = request.headers.get('webhook-timestamp') || '';
52 const webhookSignature = request.headers.get('webhook-signature') || '';
53
54 // Get raw payload
55 const payload = await request.text();
56
57 console.log('\n📨 Received webhook request');
58 console.log(' Headers:');
59 console.log(` webhook-id: ${webhookId}`);
60 console.log(` webhook-timestamp: ${webhookTimestamp}`);
61 console.log(` webhook-signature: ${webhookSignature.substring(0, 30)}...`);
62
63 // Verify the webhook
64 const result = await composio.triggers.verifyWebhook({
65 id: webhookId,
66 timestamp: webhookTimestamp,
67 signature: webhookSignature,
68 payload,
69 secret: WEBHOOK_SECRET,
70 });
71
72 // Log the verified payload
73 console.log('\n✅ Webhook verified successfully!');
74 console.log(` Version: ${result.version}`);
75 console.log(` Trigger: ${result.payload.triggerSlug}`);
76 console.log(` User ID: ${result.payload.userId}`);
77 console.log(` Payload:`, JSON.stringify(result.payload.payload, null, 2));
78
79 // Process the trigger event here
80 // For example, you could emit an event, call another service, etc.
81
82 return new Response(JSON.stringify({ success: true }), {
83 status: 200,
84 headers: { 'Content-Type': 'application/json' },
85 });
86 } catch (error) {
87 console.error('\n❌ Webhook verification failed:', error);
88
89 // Return 401 for signature verification errors
90 if (error instanceof ComposioWebhookSignatureVerificationError) {
91 return new Response(JSON.stringify({ error: 'Unauthorized' }), {
92 status: 401,
93 headers: { 'Content-Type': 'application/json' },
94 });
95 }
96
97 // Return 400 for payload parsing errors
98 if (error instanceof ComposioWebhookPayloadError) {
99 return new Response(JSON.stringify({ error: 'Bad Request' }), {
100 status: 400,
101 headers: { 'Content-Type': 'application/json' },
102 });
103 }
104
105 // Return 500 for unexpected errors
106 return new Response(JSON.stringify({ error: 'Internal Server Error' }), {
107 status: 500,
108 headers: { 'Content-Type': 'application/json' },
109 });
110 }
111 }
112
113 // 404 for other routes
114 return new Response('Not Found', { status: 404 });
115 },
116 });
117
118 console.log(`✅ Webhook server running at http://localhost:${server.port}`);
119 console.log(`\n📋 Endpoints:`);
120 console.log(` POST /webhook - Receive and verify webhooks`);
121 console.log(` GET /health - Health check`);
122 console.log(`\n💡 Tips:`);
123 console.log(` 1. Expose this server with telebit: telebit http ${server.port}`);
124 console.log(` 2. Configure your telebit URL as webhook URL in Composio dashboard`);
125 console.log(` 3. The webhook secret should match what's configured in Composio`);