1
-import { describe, expect, layer } from '@effect/vitest';
2
-import { ConfigProvider, Effect } from 'effect';
3
-import { extendConfigProvider } from 'src/services/config';
4
-import { cli, MockConsole, TestLive } from 'test/__utils__';
5
-import { createServer, type IncomingMessage } from 'node:http';
6
-import { Composio } from '@composio/core';
7
-
8
-const testConfigProvider = ConfigProvider.fromMap(
9
- new Map([['COMPOSIO_USER_API_KEY', 'test_api_key']])
10
-).pipe(extendConfigProvider);
11
-
12
-const mockV3TriggerEvent = {
13
- id: 'msg-123',
14
- timestamp: '2026-02-23T12:00:00Z',
15
- type: 'composio.trigger.message',
16
- metadata: {
17
- log_id: 'log-123',
18
- trigger_slug: 'GMAIL_NEW_GMAIL_MESSAGE',
19
- trigger_id: 'trg_123',
20
- connected_account_id: 'con_123',
21
- auth_config_id: 'ac_123',
22
- user_id: 'user_123',
23
- },
24
- data: {
25
- subject: 'Hello',
26
- from: 'hello@example.com',
27
- },
28
-} as const;
29
-
30
-type CapturedWebhookRequest = {
31
- body: string;
32
- headers: {
33
- webhookId: string;
34
- webhookTimestamp: string;
35
- webhookSignature: string;
36
- webhookVersion: string;
37
- };
38
-};
39
-
40
-const startWebhookServer = async (): Promise<{
41
- url: string;
42
- waitForRequest: Promise<CapturedWebhookRequest>;
43
- close: () => Promise<void>;
44
-}> => {
45
- let resolveRequest: ((value: CapturedWebhookRequest) => void) | undefined;
46
- let rejectRequest: ((reason?: unknown) => void) | undefined;
47
-
48
- const waitForRequest = new Promise<CapturedWebhookRequest>((resolve, reject) => {
49
- resolveRequest = resolve;
50
- rejectRequest = reject;
51
- });
52
-
53
- const readBody = (req: IncomingMessage): Promise<string> =>
54
- new Promise((resolve, reject) => {
55
- const chunks: Buffer[] = [];
56
- req.on('data', chunk => {
57
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
58
- });
59
- req.on('end', () => {
60
- resolve(Buffer.concat(chunks).toString('utf8'));
61
- });
62
- req.on('error', reject);
63
- });
64
-
65
- const server = createServer(async (req, res) => {
66
- try {
67
- const body = await readBody(req);
68
- resolveRequest?.({
69
- body,
70
- headers: {
71
- webhookId: (req.headers['webhook-id'] as string | undefined) ?? '',
72
- webhookTimestamp: (req.headers['webhook-timestamp'] as string | undefined) ?? '',
73
- webhookSignature: (req.headers['webhook-signature'] as string | undefined) ?? '',
74
- webhookVersion: (req.headers['webhook-version'] as string | undefined) ?? '',
75
- },
76
- });
77
- res.statusCode = 200;
78
- res.end('ok');
79
- } catch (error) {
80
- rejectRequest?.(error);
81
- res.statusCode = 500;
82
- res.end('error');
83
- }
84
- });
85
-
86
- await new Promise<void>((resolve, reject) => {
87
- server.listen(0, '127.0.0.1', () => resolve());
88
- server.on('error', reject);
89
- });
90
-
91
- const address = server.address();
92
- if (!address || typeof address === 'string') {
93
- throw new Error('Failed to bind webhook test server');
94
- }
95
-
96
- return {
97
- url: `http://127.0.0.1:${address.port}/webhook`,
98
- waitForRequest,
99
- close: () =>
100
- new Promise((resolve, reject) => {
101
- server.close(error => {
102
- if (error) reject(error);
103
- else resolve();
104
- });
105
- }),
106
- };
107
-};
108
-
109
-describe('CLI: composio dev triggers listen', () => {
110
- layer(
111
- TestLive({
112
- baseConfigProvider: testConfigProvider,
113
- fixture: 'global-test-user-id',
114
- realtimeData: {
115
- events: [mockV3TriggerEvent],
116
- },
117
- })
118
- )('[Given] one realtime event [Then] prints normalized event output', it => {
119
- it.scoped('prints event summary and payload', () =>
120
- Effect.gen(function* () {
121
- yield* cli(['dev', 'triggers', 'listen', '--max-events', '1']);
122
- const lines = yield* MockConsole.getLines({ stripAnsi: true });
123
- const output = lines.join('\n');
124
-
125
- expect(output).toContain('Listening for realtime trigger events');
126
- expect(output).not.toContain('Writing matching events to:');
127
- expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
128
- expect(output).toContain('"subject":"Hello"');
129
- expect(output).toContain('Stopped after receiving 1 matching events');
130
- })
131
- );
132
- });
133
-
134
- layer(
135
- TestLive({
136
- baseConfigProvider: testConfigProvider,
137
- fixture: 'global-test-user-id',
138
- realtimeData: {
139
- events: [mockV3TriggerEvent],
140
- },
141
- })
142
- )('[Given] composio dev listen [Then] works like composio dev triggers listen', it => {
143
- it.scoped('dev listen expands to triggers listen', () =>
144
- Effect.gen(function* () {
145
- yield* cli(['dev', 'listen', '--max-events', '1']);
146
- const lines = yield* MockConsole.getLines({ stripAnsi: true });
147
- const output = lines.join('\n');
148
-
149
- expect(output).toContain('Listening for realtime trigger events');
150
- expect(output).toContain('GMAIL_NEW_GMAIL_MESSAGE');
151
- expect(output).toContain('Stopped after receiving 1 matching events');
152
- })
153
- );
154
- });
155
-
156
- layer(
157
- TestLive({
158
- baseConfigProvider: testConfigProvider,
159
- fixture: 'global-test-user-id',
160
- realtimeData: {
161
- events: [mockV3TriggerEvent],
162
- },
163
- })
164
- )('[Given] --table [Then] prints compact table rows', it => {
165
- it.scoped('prints table header and event row', () =>
166
- Effect.gen(function* () {
167
- yield* cli(['dev', 'triggers', 'listen', '--table', '--max-events', '1']);
168
- const lines = yield* MockConsole.getLines({ stripAnsi: true });
169
- const output = lines.join('\n');
170
-
171
- expect(output).toContain('Timestamp');
172
- expect(output).toContain('Trigger Id');
173
- expect(output).toContain('Trigger Slug');
174
- expect(output).toContain('Toolkit');
175
- expect(output).toContain('User Id');
176
- expect(output).toContain('Connected Account Id');
177
- expect(output).not.toContain('Event #1');
178
- expect(output).not.toContain('Trigger:');
179
- expect(output).toContain('trg_123');
180
- expect(output).toContain('GMAIL_NEW_GMAIL_');
181
- expect(output).toContain('GMAIL');
182
- expect(output).toContain('user_123');
183
- expect(output).toContain('con_123');
184
- })
185
- );
186
- });
187
-
188
- layer(TestLive())('[Given] no API key [Then] warns user to login', it => {
189
- it.scoped('warns user to login', () =>
190
- Effect.gen(function* () {
191
- yield* cli(['dev', 'triggers', 'listen']);
192
- const lines = yield* MockConsole.getLines({ stripAnsi: true });
193
- const output = lines.join('\n');
194
- expect(output).toContain('not logged in');
195
- })
196
- );
197
- });
198
-
199
- layer(
200
- TestLive({
201
- baseConfigProvider: testConfigProvider,
202
- fixture: 'global-test-user-id',
203
- realtimeData: { events: [mockV3TriggerEvent] },
204
- })
205
- )(
206
- '[Given] --forward without COMPOSIO_WEBHOOK_SECRET [Then] generates session signing secret',
207
- it => {
208
- it.scoped('shows generated signing secret for forward mode', () =>
209
- Effect.gen(function* () {
210
- delete process.env.COMPOSIO_WEBHOOK_SECRET;
211
- yield* cli([
212
- 'dev',
213
- 'triggers',
214
- 'listen',
215
- '--forward',
216
- 'http://localhost:8080/webhook',
217
- '--max-events',
218
- '1',
219
- ]);
220
- const lines = yield* MockConsole.getLines({ stripAnsi: true });
221
- const output = lines.join('\n');
222
- expect(output).toContain('No COMPOSIO_WEBHOOK_SECRET found');
223
- expect(output).toContain('Forward URL: http://localhost:8080/webhook');
224
- expect(output).toContain('Generated signing secret: composio-forward-secret-');
225
- })
226
- );
227
- }
228
- );
229
-
230
- layer(
231
- TestLive({
232
- baseConfigProvider: testConfigProvider,
233
- fixture: 'global-test-user-id',
234
- realtimeData: { events: [mockV3TriggerEvent] },
235
- })
236
- )('[Given] --forward [Then] sends signed webhook verifiable by composio/core', it => {
237
- it.scoped('forwards request with headers and valid signature', () => {
238
- const previousSecret = process.env.COMPOSIO_WEBHOOK_SECRET;
239
- const restoreWebhookSecret = () => {
240
- if (previousSecret === undefined) {
241
- delete process.env.COMPOSIO_WEBHOOK_SECRET;
242
- return;
243
- }
244
- process.env.COMPOSIO_WEBHOOK_SECRET = previousSecret;
245
- };
246
-
247
- return Effect.gen(function* () {
248
- process.env.COMPOSIO_WEBHOOK_SECRET = 'test-webhook-secret';
249
-
250
- const server = yield* Effect.acquireRelease(
251
- Effect.tryPromise(() => startWebhookServer()),
252
- resource =>
253
- Effect.tryPromise(() => resource.close()).pipe(Effect.catchAll(() => Effect.void))
254
- );
255
-
256
- yield* cli(['dev', 'triggers', 'listen', '--forward', server.url, '--max-events', '1']);
257
-
258
- const request = yield* Effect.tryPromise({
259
- try: () =>
260
- Promise.race([
261
- server.waitForRequest,
262
- new Promise<never>((_, reject) =>
263
- setTimeout(() => reject(new Error('Timed out waiting for forwarded webhook')), 3000)
264
- ),
265
- ]),
266
- catch: error => new Error(String(error)),
267
- });
268
-
269
- expect(request.headers.webhookId).not.toEqual('');
270
- expect(request.headers.webhookTimestamp).not.toEqual('');
271
- expect(request.headers.webhookSignature).toContain('v1,');
272
- expect(request.headers.webhookVersion).toEqual('V3');
273
-
274
- const composio = new Composio({
275
- apiKey: 'test-api-key',
276
- disableVersionCheck: true,
277
- allowTracking: false,
278
- });
279
-
280
- const verification = yield* Effect.tryPromise(() =>
281
- composio.triggers.verifyWebhook({
282
- payload: request.body,
283
- id: request.headers.webhookId,
284
- timestamp: request.headers.webhookTimestamp,
285
- signature: request.headers.webhookSignature,
286
- secret: 'test-webhook-secret',
287
- })
288
- );
289
-
290
- expect(verification.rawPayload).toEqual(mockV3TriggerEvent);
291
- }).pipe(
292
- Effect.ensuring(
293
- Effect.sync(() => {
294
- restoreWebhookSecret();
295
- })
296
- )
297
- );
298
- });
299
- });
300
-});