@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 1,901 lines 62.9 KB
Raw
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { mockClient } from '../utils/mocks/client.mock';
3 import { ConnectedAccounts } from '../../src/models/ConnectedAccounts';
4 import { Experimental } from '../../src/models/Experimental';
5 import ComposioClient from '@composio/client';
6 import { ConnectedAccountRetrieveResponse } from '@composio/client/resources/connected-accounts';
7 import {
8 ComposioAclOnlyForSharedError,
9 ComposioConnectedAccountNotFoundError,
10 ComposioConnectedAccountNotRevokableError,
11 ComposioConnectedAccountRevocationNotSupportedError,
12 ComposioFailedToCreateConnectedAccountLink,
13 } from '../../src/errors';
14 import {
15 BadRequestError,
16 ConflictError,
17 InternalServerError,
18 NotFoundError,
19 } from '@composio/client';
20 import { ConnectedAccountStatuses } from '../../src/types/connectedAccounts.types';
21 import { ComposioMultipleConnectedAccountsError } from '../../src/errors';
22 import { AuthSchemeTypes } from '../../src/types/authConfigs.types';
23 import { AuthScheme } from '../../src/models/AuthScheme';
24 import { ConnectionStatuses } from '../../src/types/connectedAccountAuthStates.types';
25 import logger from '../../src/utils/logger';
26
27 // Extend the mock client object for ConnectedAccounts testing
28 const extendedMockClient = {
29 ...mockClient,
30 connectedAccounts: {
31 ...mockClient.connectedAccounts,
32 create: vi.fn(),
33 retrieve: vi.fn(),
34 delete: vi.fn(),
35 refresh: vi.fn(),
36 revoke: vi.fn(),
37 completeAuth: vi.fn(),
38 patch: vi.fn(),
39 updateStatus: vi.fn(),
40 createConnectedAccountLink: vi.fn(),
41 },
42 link: {
43 create: vi.fn(),
44 },
45 authConfigs: {
46 list: vi.fn(),
47 create: vi.fn(),
48 },
49 };
50
51 describe('ConnectedAccounts', () => {
52 let connectedAccounts: ConnectedAccounts;
53
54 beforeEach(() => {
55 vi.clearAllMocks();
56 connectedAccounts = new ConnectedAccounts(extendedMockClient as unknown as ComposioClient);
57 });
58
59 describe('list', () => {
60 it('should call client.connectedAccounts.list with the provided query', async () => {
61 const query = { limit: 10 };
62 const mockResponse = { items: [], next_cursor: null, total_pages: 0 };
63
64 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
65
66 const result = await connectedAccounts.list(query);
67
68 expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(query, undefined);
69 expect(result).toEqual({
70 items: [],
71 nextCursor: null,
72 totalPages: 0,
73 });
74 });
75
76 it('should call client.connectedAccounts.list without query if none provided', async () => {
77 const mockResponse = { items: [], total_pages: 0, next_cursor: null };
78
79 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce(mockResponse);
80
81 const result = await connectedAccounts.list();
82
83 expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(undefined, undefined);
84 expect(result).toEqual({
85 items: [],
86 nextCursor: null,
87 totalPages: 0,
88 });
89 });
90 });
91
92 describe('initiate', () => {
93 it('should create a new connected account and return a ConnectionRequest and wait for it to be active', async () => {
94 const userId = 'user_123';
95 const authConfigId = 'auth_config_123';
96 const options = {
97 callbackUrl: 'https://example.com/callback',
98 };
99
100 // Mock list response to return empty list
101 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
102 items: [],
103 next_cursor: null,
104 total_pages: 1,
105 });
106
107 const mockResponse = {
108 id: 'conn_123',
109 connectionData: {
110 val: {
111 authScheme: AuthSchemeTypes.OAUTH2,
112 status: 'INITIALIZING',
113 redirectUrl: 'https://auth.example.com/connect',
114 },
115 },
116 };
117
118 extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
119
120 const connectionRequest = await connectedAccounts.initiate(userId, authConfigId, options);
121
122 // Verify list is called with ACTIVE status filter
123 expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(
124 expect.objectContaining({
125 user_ids: [userId],
126 auth_config_ids: [authConfigId],
127 statuses: [ConnectedAccountStatuses.ACTIVE],
128 }),
129 undefined
130 );
131
132 expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
133 {
134 auth_config: {
135 id: authConfigId,
136 },
137 connection: {
138 user_id: userId,
139 callback_url: options.callbackUrl,
140 state: undefined,
141 },
142 },
143 undefined
144 );
145
146 expect(connectionRequest).toHaveProperty('id', 'conn_123');
147 expect(connectionRequest).toHaveProperty('waitForConnection');
148 expect(typeof connectionRequest.waitForConnection).toBe('function');
149 });
150
151 it('should work without optional parameters', async () => {
152 const userId = 'user_123';
153 const authConfigId = 'auth_config_123';
154
155 // Mock list response to return empty list
156 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
157 items: [],
158 next_cursor: null,
159 total_pages: 1,
160 });
161
162 const mockResponse = {
163 id: 'conn_123',
164 connectionData: {
165 val: {
166 authScheme: AuthSchemeTypes.OAUTH2,
167 status: 'INITIALIZING',
168 redirectUrl: 'https://auth.example.com/connect',
169 },
170 },
171 };
172
173 extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
174
175 const connectionRequest = await connectedAccounts.initiate(userId, authConfigId);
176
177 expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
178 {
179 auth_config: {
180 id: authConfigId,
181 },
182 connection: {
183 user_id: userId,
184 callback_url: undefined,
185 state: undefined,
186 },
187 },
188 undefined
189 );
190
191 expect(connectionRequest).toHaveProperty('id', 'conn_123');
192 expect(connectionRequest).toHaveProperty('waitForConnection');
193 expect(typeof connectionRequest.waitForConnection).toBe('function');
194 });
195
196 it('should pass alias to the create API when provided', async () => {
197 const userId = 'user_123';
198 const authConfigId = 'auth_config_123';
199
200 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
201 items: [],
202 next_cursor: null,
203 total_pages: 1,
204 });
205
206 const mockResponse = {
207 id: 'conn_123',
208 connectionData: {
209 val: {
210 authScheme: AuthSchemeTypes.OAUTH2,
211 status: 'INITIALIZING',
212 redirectUrl: 'https://auth.example.com/connect',
213 },
214 },
215 };
216
217 extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
218
219 await connectedAccounts.initiate(userId, authConfigId, {
220 alias: 'work-gmail',
221 });
222
223 expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
224 expect.objectContaining({
225 auth_config: { id: authConfigId },
226 connection: expect.objectContaining({ user_id: userId, alias: 'work-gmail' }),
227 }),
228 undefined
229 );
230 });
231
232 it('should not include alias in create params when not provided', async () => {
233 const userId = 'user_123';
234 const authConfigId = 'auth_config_123';
235
236 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
237 items: [],
238 next_cursor: null,
239 total_pages: 1,
240 });
241
242 const mockResponse = {
243 id: 'conn_123',
244 connectionData: {
245 val: {
246 authScheme: AuthSchemeTypes.OAUTH2,
247 status: 'INITIALIZING',
248 redirectUrl: 'https://auth.example.com/connect',
249 },
250 },
251 };
252
253 extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
254
255 await connectedAccounts.initiate(userId, authConfigId);
256
257 const callArgs = extendedMockClient.connectedAccounts.create.mock.calls[0]![0];
258 expect(callArgs.connection).not.toHaveProperty('alias');
259 });
260
261 it('should throw ComposioMultipleConnectedAccountsError when multiple accounts exist and allowMultiple is false', async () => {
262 const userId = 'user_123';
263 const authConfigId = 'auth_config_123';
264
265 // Mock list response to return multiple accounts
266 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
267 items: [
268 {
269 id: 'conn_1',
270 status: ConnectedAccountStatuses.ACTIVE,
271 auth_config: {
272 id: authConfigId,
273 is_composio_managed: true,
274 is_disabled: false,
275 },
276 data: {},
277 params: {},
278 status_reason: null,
279 toolkit: {
280 slug: 'test-toolkit',
281 name: 'Test Toolkit',
282 },
283 is_disabled: false,
284 created_at: new Date().toISOString(),
285 updated_at: new Date().toISOString(),
286 },
287 {
288 id: 'conn_2',
289 status: ConnectedAccountStatuses.ACTIVE,
290 auth_config: {
291 id: authConfigId,
292 is_composio_managed: true,
293 is_disabled: false,
294 },
295 data: {},
296 params: {},
297 status_reason: null,
298 toolkit: {
299 slug: 'test-toolkit',
300 name: 'Test Toolkit',
301 },
302 is_disabled: false,
303 created_at: new Date().toISOString(),
304 updated_at: new Date().toISOString(),
305 },
306 ],
307 next_cursor: null,
308 total_pages: 1,
309 });
310
311 await expect(connectedAccounts.initiate(userId, authConfigId)).rejects.toThrow(
312 ComposioMultipleConnectedAccountsError
313 );
314 });
315
316 it('should filter by ACTIVE status when checking for existing accounts', async () => {
317 const userId = 'user_123';
318 const authConfigId = 'auth_config_123';
319
320 // Mock list response to return empty list (no ACTIVE accounts)
321 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
322 items: [],
323 next_cursor: null,
324 total_pages: 1,
325 });
326
327 const mockResponse = {
328 id: 'conn_123',
329 connectionData: {
330 val: {
331 authScheme: AuthSchemeTypes.OAUTH2,
332 status: 'INITIALIZING',
333 redirectUrl: 'https://auth.example.com/connect',
334 },
335 },
336 };
337
338 extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
339
340 await connectedAccounts.initiate(userId, authConfigId);
341
342 // Verify that list is called with statuses filter set to ACTIVE only
343 // This ensures expired/inactive accounts don't block new connection creation
344 expect(extendedMockClient.connectedAccounts.list).toHaveBeenCalledWith(
345 expect.objectContaining({
346 user_ids: [userId],
347 auth_config_ids: [authConfigId],
348 statuses: [ConnectedAccountStatuses.ACTIVE],
349 }),
350 undefined
351 );
352 });
353
354 it('should allow multiple accounts when allowMultiple is true', async () => {
355 const userId = 'user_123';
356 const authConfigId = 'auth_config_123';
357
358 // Mock list response to return multiple accounts
359 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
360 items: [
361 {
362 id: 'conn_1',
363 status: ConnectedAccountStatuses.ACTIVE,
364 auth_config: {
365 id: authConfigId,
366 is_composio_managed: true,
367 is_disabled: false,
368 },
369 data: {},
370 params: {},
371 status_reason: null,
372 toolkit: {
373 slug: 'test-toolkit',
374 name: 'Test Toolkit',
375 },
376 is_disabled: false,
377 created_at: new Date().toISOString(),
378 updated_at: new Date().toISOString(),
379 },
380 {
381 id: 'conn_2',
382 status: ConnectedAccountStatuses.ACTIVE,
383 auth_config: {
384 id: authConfigId,
385 is_composio_managed: true,
386 is_disabled: false,
387 },
388 data: {},
389 params: {},
390 status_reason: null,
391 toolkit: {
392 slug: 'test-toolkit',
393 name: 'Test Toolkit',
394 },
395 is_disabled: false,
396 created_at: new Date().toISOString(),
397 updated_at: new Date().toISOString(),
398 },
399 ],
400 next_cursor: null,
401 total_pages: 1,
402 });
403
404 const mockResponse = {
405 id: 'conn_123',
406 connectionData: {
407 val: {
408 authScheme: AuthSchemeTypes.OAUTH2,
409 status: 'INITIALIZING',
410 redirectUrl: 'https://auth.example.com/connect',
411 },
412 },
413 };
414
415 extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
416
417 const connectionRequest = await connectedAccounts.initiate(userId, authConfigId, {
418 allowMultiple: true,
419 });
420
421 expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
422 {
423 auth_config: {
424 id: authConfigId,
425 },
426 connection: {
427 user_id: userId,
428 callback_url: undefined,
429 state: undefined,
430 },
431 },
432 undefined
433 );
434
435 expect(connectionRequest).toHaveProperty('id', 'conn_123');
436 expect(connectionRequest).toHaveProperty('waitForConnection');
437 expect(typeof connectionRequest.waitForConnection).toBe('function');
438 });
439
440 it('should create a connected account with OAuth2 token import and return ACTIVE ConnectionRequest', async () => {
441 const userId = 'user_123';
442 const authConfigId = 'auth_config_123';
443 const options = {
444 callbackUrl: 'https://example.com/callback',
445 config: AuthScheme.OAuth2({
446 access_token: 'test_token',
447 token_type: 'Bearer',
448 }),
449 };
450
451 // Mock list response to return empty list
452 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
453 items: [],
454 next_cursor: null,
455 total_pages: 1,
456 });
457
458 // When tokens are imported, the API should return ACTIVE with no redirectUrl
459 const mockResponse = {
460 id: 'conn_123',
461 connectionData: {
462 val: {
463 status: ConnectionStatuses.ACTIVE,
464 },
465 },
466 };
467
468 extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
469
470 const connectionRequest = await connectedAccounts.initiate(userId, authConfigId, options);
471
472 expect(extendedMockClient.connectedAccounts.create).toHaveBeenCalledWith(
473 {
474 auth_config: {
475 id: authConfigId,
476 },
477 connection: {
478 user_id: userId,
479 callback_url: options.callbackUrl,
480 state: options.config,
481 },
482 },
483 undefined
484 );
485
486 expect(connectionRequest).toHaveProperty('id', 'conn_123');
487 expect(connectionRequest).toHaveProperty('status', ConnectionStatuses.ACTIVE);
488 expect(connectionRequest).toHaveProperty('redirectUrl', null);
489 expect(typeof connectionRequest.waitForConnection).toBe('function');
490 });
491
492 it('should return INITIATED status with redirectUrl when no tokens are provided', async () => {
493 const userId = 'user_123';
494 const authConfigId = 'auth_config_123';
495
496 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
497 items: [],
498 next_cursor: null,
499 total_pages: 1,
500 });
501
502 const mockResponse = {
503 id: 'conn_456',
504 connectionData: {
505 val: {
506 status: ConnectionStatuses.INITIATED,
507 redirectUrl: 'https://auth.example.com/connect',
508 },
509 },
510 };
511
512 extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);
513
514 const connectionRequest = await connectedAccounts.initiate(userId, authConfigId);
515
516 expect(connectionRequest).toHaveProperty('id', 'conn_456');
517 expect(connectionRequest).toHaveProperty('status', ConnectionStatuses.INITIATED);
518 expect(connectionRequest).toHaveProperty('redirectUrl', 'https://auth.example.com/connect');
519 });
520 });
521
522 // SEC-339: initiate() must gate its deprecation warning on the response
523 // `Deprecation` HTTP header (RFC 9745) that apollo emits only on the
524 // retiring branch (Composio-managed + redirectable OAuth). These tests pin
525 // that contract so the previous false-positive behavior — warning purely
526 // off auth_scheme, which over-fired for custom auth configs — can't come
527 // back. See https://docs.composio.dev/docs/changelog/2026/04/24
528 describe('initiate deprecation header gate', () => {
529 /** Wrap a value as an APIPromise-shaped thenable that also exposes
530 * `.withResponse()` returning the value plus a synthesised Response
531 * carrying the given headers. Mirrors the @composio/client APIPromise
532 * surface that the SDK now consumes for header-aware deprecation. */
533 function mockApiPromiseWithHeaders<T>(
534 data: T,
535 headers: Record<string, string> = {}
536 ): Promise<T> & {
537 withResponse: () => Promise<{ data: T; response: Response }>;
538 } {
539 const response = new Response(null, { headers: new Headers(headers) });
540 const promise = Promise.resolve(data) as Promise<T> & {
541 withResponse: () => Promise<{ data: T; response: Response }>;
542 };
543 promise.withResponse = () => Promise.resolve({ data, response });
544 return promise;
545 }
546
547 const userId = 'user_dep';
548 const authConfigId = 'auth_config_dep';
549 const baseResponse = {
550 id: 'conn_dep',
551 connectionData: {
552 val: {
553 authScheme: AuthSchemeTypes.OAUTH2,
554 status: 'INITIALIZING',
555 redirectUrl: 'https://auth.example.com/connect',
556 },
557 },
558 };
559
560 /** Re-import the model with a fresh module-level
561 * `_legacyInitiateWarningEmitted` so each test starts unwarned. */
562 async function freshConnectedAccounts() {
563 vi.resetModules();
564 const { ConnectedAccounts: Fresh } = await import('../../src/models/ConnectedAccounts');
565 const fresh = new Fresh(extendedMockClient as unknown as ComposioClient);
566 const loggerMod = await import('../../src/utils/logger');
567 const warnSpy = vi.spyOn(loggerMod.default, 'warn').mockImplementation(() => {});
568 return { connectedAccounts: fresh, warnSpy };
569 }
570
571 it('warns once when response carries a Deprecation header (managed + OAuth retiring path)', async () => {
572 const { connectedAccounts: fresh, warnSpy } = await freshConnectedAccounts();
573 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
574 items: [],
575 next_cursor: null,
576 total_pages: 1,
577 });
578 extendedMockClient.connectedAccounts.create.mockReturnValueOnce(
579 mockApiPromiseWithHeaders(baseResponse, {
580 Deprecation: '@1776988800',
581 Sunset: 'Fri, 08 May 2026 00:00:00 GMT',
582 Link: '<https://docs.composio.dev/docs/changelog/2026/04/24>; rel="deprecation"',
583 })
584 );
585
586 const req = await fresh.initiate(userId, authConfigId);
587
588 expect(req).toHaveProperty('id', 'conn_dep');
589 expect(warnSpy).toHaveBeenCalledTimes(1);
590 expect(warnSpy.mock.calls[0]![0]).toMatch(/composio\.connectedAccounts\.link\(\)/);
591 expect(warnSpy.mock.calls[0]![0]).toMatch(/2026-07-03/);
592 });
593
594 it('does NOT warn when response has no Deprecation header (custom auth config)', async () => {
595 // Regression test: prior auth_scheme-only check warned for any
596 // OAUTH2 response, including custom configs that are not subject
597 // to the cutover. Header absence is the canonical "you're fine"
598 // signal from apollo.
599 const { connectedAccounts: fresh, warnSpy } = await freshConnectedAccounts();
600 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
601 items: [],
602 next_cursor: null,
603 total_pages: 1,
604 });
605 extendedMockClient.connectedAccounts.create.mockReturnValueOnce(
606 mockApiPromiseWithHeaders(baseResponse /* no Deprecation header */)
607 );
608
609 const req = await fresh.initiate(userId, authConfigId);
610
611 expect(req).toHaveProperty('id', 'conn_dep');
612 expect(warnSpy).not.toHaveBeenCalled();
613 });
614
615 it('warns at most once per process even across multiple managed-OAuth calls', async () => {
616 const { connectedAccounts: fresh, warnSpy } = await freshConnectedAccounts();
617 // Two consecutive managed-OAuth calls. Both responses carry the
618 // Deprecation header, but the module-level guard should let only
619 // the first one through.
620 for (let i = 0; i < 2; i++) {
621 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
622 items: [],
623 next_cursor: null,
624 total_pages: 1,
625 });
626 extendedMockClient.connectedAccounts.create.mockReturnValueOnce(
627 mockApiPromiseWithHeaders(baseResponse, { Deprecation: '@1776988800' })
628 );
629 await fresh.initiate(userId, authConfigId);
630 }
631
632 expect(warnSpy).toHaveBeenCalledTimes(1);
633 });
634 });
635
636 describe('get', () => {
637 it('should retrieve a connected account by nanoid and transform the response', async () => {
638 const nanoid = 'conn_123';
639 const mockResponse = {
640 id: 'nanoid',
641 status: 'ACTIVE',
642 auth_scopes: ['read:user', 'write:user'],
643 auth_config: {
644 id: 'test-auth-config',
645 is_composio_managed: true,
646 is_disabled: false,
647 },
648 state: {
649 authScheme: AuthSchemeTypes.OAUTH2,
650 val: {
651 status: 'ACTIVE',
652 access_token: 'access_token_123',
653 token_type: 'Bearer',
654 },
655 },
656 user_id: 'user_123',
657 data: {},
658 params: {},
659 is_disabled: false,
660 created_at: '2023-01-01T00:00:00Z',
661 updated_at: '2023-01-01T00:00:00Z',
662 status_reason: null,
663 toolkit: {
664 slug: 'test-toolkit',
665 },
666 };
667
668 extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockResponse);
669
670 const result = await connectedAccounts.get(nanoid);
671
672 expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(nanoid, undefined);
673 expect(result).toEqual({
674 id: 'nanoid',
675 status: 'ACTIVE',
676 authConfig: {
677 id: 'test-auth-config',
678 isComposioManaged: true,
679 isDisabled: false,
680 },
681 wordId: null,
682 alias: null,
683 state: {
684 authScheme: AuthSchemeTypes.OAUTH2,
685 val: {
686 status: 'ACTIVE',
687 access_token: 'access_token_123',
688 token_type: 'Bearer',
689 },
690 },
691 data: {},
692 params: {},
693 statusReason: null,
694 isDisabled: false,
695 createdAt: '2023-01-01T00:00:00Z',
696 updatedAt: '2023-01-01T00:00:00Z',
697 toolkit: {
698 slug: 'test-toolkit',
699 },
700 testRequestEndpoint: undefined,
701 });
702 });
703
704 it('should preserve alias and wordId when the API returns them', async () => {
705 const nanoid = 'conn_456';
706 const mockResponse = {
707 id: nanoid,
708 status: 'ACTIVE',
709 word_id: 'castle',
710 alias: 'Work Gmail',
711 auth_config: {
712 id: 'test-auth-config',
713 is_composio_managed: true,
714 is_disabled: false,
715 },
716 is_disabled: false,
717 created_at: '2023-01-01T00:00:00Z',
718 updated_at: '2023-01-01T00:00:00Z',
719 status_reason: null,
720 toolkit: {
721 slug: 'gmail',
722 },
723 };
724
725 extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockResponse);
726
727 const result = await connectedAccounts.get(nanoid);
728
729 expect(result.wordId).toBe('castle');
730 expect(result.alias).toBe('Work Gmail');
731 });
732
733 it('should accept revoked connected account status from the generated client', async () => {
734 const nanoid = 'conn_revoked';
735 const mockResponse = {
736 id: nanoid,
737 status: ConnectedAccountStatuses.REVOKED,
738 auth_config: {
739 id: 'test-auth-config',
740 is_composio_managed: true,
741 is_disabled: false,
742 },
743 is_disabled: false,
744 created_at: '2023-01-01T00:00:00Z',
745 updated_at: '2023-01-01T00:00:00Z',
746 status_reason: 'revoked by user',
747 toolkit: {
748 slug: 'gmail',
749 },
750 };
751
752 extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockResponse);
753
754 const result = await connectedAccounts.get(nanoid);
755
756 expect(result.status).toBe(ConnectedAccountStatuses.REVOKED);
757 expect(result.statusReason).toBe('revoked by user');
758 });
759 });
760
761 describe('delete', () => {
762 it('should delete a connected account by nanoid', async () => {
763 const nanoid = 'conn_123';
764 const mockResponse = { success: true };
765
766 extendedMockClient.connectedAccounts.delete.mockResolvedValueOnce(mockResponse);
767
768 const result = await connectedAccounts.delete(nanoid);
769
770 expect(extendedMockClient.connectedAccounts.delete).toHaveBeenCalledWith(
771 nanoid,
772 undefined,
773 undefined
774 );
775 expect(result).toEqual(mockResponse);
776 });
777 });
778
779 describe('refresh', () => {
780 it('should refresh a connected account by nanoid without options', async () => {
781 const nanoid = 'conn_123';
782 const mockResponse = { id: nanoid, refreshed: true };
783
784 extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);
785
786 const result = await connectedAccounts.refresh(nanoid);
787
788 expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
789 nanoid,
790 undefined,
791 undefined
792 );
793 expect(result).toEqual(mockResponse);
794 });
795
796 it('should refresh a connected account with redirectUrl option', async () => {
797 const nanoid = 'conn_123';
798 const redirectUrl = 'https://example.com/oauth/callback';
799 const mockResponse = { id: nanoid, refreshed: true };
800
801 extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);
802
803 const result = await connectedAccounts.refresh(nanoid, { redirectUrl });
804
805 expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
806 nanoid,
807 {
808 query_redirect_url: redirectUrl,
809 },
810 undefined
811 );
812 expect(result).toEqual(mockResponse);
813 });
814
815 it('should ignore the removed validateCredentials option and warn', async () => {
816 const nanoid = 'conn_123';
817 const mockResponse = { id: nanoid, refreshed: true };
818 const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});
819
820 extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);
821
822 const result = await connectedAccounts.refresh(nanoid, { validateCredentials: true });
823
824 expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
825 nanoid,
826 {
827 query_redirect_url: undefined,
828 },
829 undefined
830 );
831 expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('validateCredentials'));
832 expect(result).toEqual(mockResponse);
833 warnSpy.mockRestore();
834 });
835
836 it('should refresh a connected account with both options', async () => {
837 const nanoid = 'conn_123';
838 const options = {
839 redirectUrl: 'https://example.com/callback',
840 validateCredentials: false,
841 };
842 const mockResponse = { id: nanoid, refreshed: true };
843
844 extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);
845
846 const result = await connectedAccounts.refresh(nanoid, options);
847
848 expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
849 nanoid,
850 {
851 query_redirect_url: options.redirectUrl,
852 },
853 undefined
854 );
855 expect(result).toEqual(mockResponse);
856 });
857
858 it('should throw ValidationError for invalid options', async () => {
859 const nanoid = 'conn_123';
860 const invalidOptions = { redirectUrl: 123 };
861
862 await expect(connectedAccounts.refresh(nanoid, invalidOptions as unknown)).rejects.toThrow(
863 'Failed to parse connected account refresh options'
864 );
865
866 expect(extendedMockClient.connectedAccounts.refresh).not.toHaveBeenCalled();
867 });
868
869 it('should handle empty options object gracefully', async () => {
870 const nanoid = 'conn_123';
871 const mockResponse = { id: nanoid, refreshed: true };
872
873 extendedMockClient.connectedAccounts.refresh.mockResolvedValueOnce(mockResponse);
874
875 const result = await connectedAccounts.refresh(nanoid, {});
876
877 expect(extendedMockClient.connectedAccounts.refresh).toHaveBeenCalledWith(
878 nanoid,
879 {
880 query_redirect_url: undefined,
881 },
882 undefined
883 );
884 expect(result).toEqual(mockResponse);
885 });
886 });
887
888 describe('updateStatus', () => {
889 it('should update the status of a connected account', async () => {
890 const nanoid = 'conn_123';
891 const params = { enabled: true };
892 const mockResponse = { id: nanoid, enabled: true };
893
894 extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
895
896 const result = await connectedAccounts.updateStatus(nanoid, params);
897
898 expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
899 nanoid,
900 params,
901 undefined
902 );
903 expect(result).toEqual(mockResponse);
904 });
905 });
906
907 describe('enable', () => {
908 it('should enable a connected account', async () => {
909 const nanoid = 'conn_123';
910 const mockResponse = { id: nanoid, enabled: true };
911
912 extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
913
914 const result = await connectedAccounts.enable(nanoid);
915
916 expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
917 nanoid,
918 {
919 enabled: true,
920 },
921 undefined
922 );
923 expect(result).toEqual(mockResponse);
924 });
925 });
926
927 describe('disable', () => {
928 it('should disable a connected account', async () => {
929 const nanoid = 'conn_123';
930 const mockResponse = { id: nanoid, enabled: false };
931
932 extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
933
934 const result = await connectedAccounts.disable(nanoid);
935
936 expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
937 nanoid,
938 {
939 enabled: false,
940 },
941 undefined
942 );
943 expect(result).toEqual(mockResponse);
944 });
945 });
946
947 describe('waitForConnection', () => {
948 it('should wait for a connected account to become active', async () => {
949 const nanoid = 'conn_123';
950 const authConfigId = 'auth_config_123';
951 const mockGetResponse = {
952 id: nanoid,
953 status: ConnectedAccountStatuses.INITIALIZING,
954 auth_scopes: ['read:user', 'write:user'],
955 auth_config: {
956 id: authConfigId,
957 auth_scheme: AuthSchemeTypes.OAUTH2,
958 is_composio_managed: true,
959 is_disabled: false,
960 },
961 state: {
962 authScheme: AuthSchemeTypes.OAUTH2,
963 val: {
964 status: ConnectedAccountStatuses.INITIALIZING,
965 access_token: 'access_token_123',
966 token_type: 'Bearer',
967 },
968 },
969 user_id: 'user_123',
970 data: {},
971 params: {},
972 is_disabled: false,
973 created_at: '2023-01-01T00:00:00Z',
974 updated_at: '2023-01-01T00:00:00Z',
975 status_reason: null,
976 toolkit: {
977 slug: 'test-toolkit',
978 },
979 } as unknown as ConnectedAccountRetrieveResponse;
980
981 const mockActiveResponse = {
982 ...mockGetResponse,
983 status: ConnectedAccountStatuses.ACTIVE,
984 state: {
985 authScheme: AuthSchemeTypes.OAUTH2,
986 val: {
987 status: ConnectedAccountStatuses.ACTIVE,
988 access_token: 'access_token_123',
989 token_type: 'Bearer',
990 },
991 },
992 } as unknown as ConnectedAccountRetrieveResponse;
993
994 // Mock the get method first call
995 extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockGetResponse);
996 // Mock the subsequent call in waitForConnection
997 extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockActiveResponse);
998
999 const result = await connectedAccounts.waitForConnection(nanoid);
1000
1001 expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(nanoid);
1002 expect(result).toEqual({
1003 id: nanoid,
1004 status: ConnectedAccountStatuses.ACTIVE,
1005 alias: null,
1006 authConfig: {
1007 id: 'auth_config_123',
1008 authScheme: AuthSchemeTypes.OAUTH2,
1009 isComposioManaged: true,
1010 isDisabled: false,
1011 },
1012 state: {
1013 authScheme: AuthSchemeTypes.OAUTH2,
1014 val: {
1015 status: ConnectedAccountStatuses.ACTIVE,
1016 access_token: 'access_token_123',
1017 token_type: 'Bearer',
1018 },
1019 },
1020 data: {},
1021 params: {},
1022 statusReason: null,
1023 isDisabled: false,
1024 createdAt: '2023-01-01T00:00:00Z',
1025 updatedAt: '2023-01-01T00:00:00Z',
1026 toolkit: {
1027 slug: 'test-toolkit',
1028 },
1029 testRequestEndpoint: undefined,
1030 wordId: null,
1031 });
1032 });
1033
1034 it('should throw ComposioConnectedAccountNotFoundError if connected account does not exist', async () => {
1035 const nanoid = 'non_existent_conn';
1036
1037 extendedMockClient.connectedAccounts.retrieve.mockRejectedValueOnce(
1038 new ComposioClient.NotFoundError(404, undefined, undefined, {} as Headers)
1039 );
1040
1041 try {
1042 await connectedAccounts.waitForConnection(nanoid);
1043 } catch (error) {
1044 expect(error).toBeInstanceOf(ComposioConnectedAccountNotFoundError);
1045 }
1046 });
1047
1048 it('should use the provided timeout value', async () => {
1049 const nanoid = 'conn_123';
1050 const timeout = 30000;
1051 const mockGetResponse = {
1052 id: nanoid,
1053 status: ConnectedAccountStatuses.INITIALIZING,
1054 auth_config: {
1055 id: 'auth_config_123',
1056 is_composio_managed: true,
1057 is_disabled: false,
1058 },
1059 state: {
1060 authScheme: AuthSchemeTypes.OAUTH2,
1061 val: {
1062 status: ConnectedAccountStatuses.INITIALIZING,
1063 access_token: 'access_token_123',
1064 token_type: 'Bearer',
1065 },
1066 },
1067 user_id: 'user_123',
1068 data: {},
1069 params: {},
1070 is_disabled: false,
1071 created_at: '2023-01-01T00:00:00Z',
1072 updated_at: '2023-01-01T00:00:00Z',
1073 status_reason: null,
1074 auth_scopes: ['read:user'],
1075 toolkit: {
1076 slug: 'test-toolkit',
1077 },
1078 } as unknown as ConnectedAccountRetrieveResponse;
1079
1080 const mockActiveResponse = {
1081 ...mockGetResponse,
1082 status: 'ACTIVE',
1083 state: {
1084 authScheme: AuthSchemeTypes.OAUTH2,
1085 val: {
1086 status: ConnectedAccountStatuses.ACTIVE,
1087 access_token: 'access_token_123',
1088 token_type: 'Bearer',
1089 },
1090 },
1091 } as unknown as ConnectedAccountRetrieveResponse;
1092
1093 extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockGetResponse);
1094 extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockActiveResponse);
1095
1096 const result = await connectedAccounts.waitForConnection(nanoid, timeout);
1097
1098 expect(extendedMockClient.connectedAccounts.retrieve).toHaveBeenCalledWith(nanoid);
1099 expect(result).toEqual({
1100 id: nanoid,
1101 status: ConnectedAccountStatuses.ACTIVE,
1102 alias: null,
1103 authConfig: {
1104 id: 'auth_config_123',
1105 authScheme: undefined,
1106 isComposioManaged: true,
1107 isDisabled: false,
1108 },
1109 state: {
1110 authScheme: AuthSchemeTypes.OAUTH2,
1111 val: {
1112 status: ConnectedAccountStatuses.ACTIVE,
1113 access_token: 'access_token_123',
1114 token_type: 'Bearer',
1115 },
1116 },
1117 data: {},
1118 params: {},
1119 statusReason: null,
1120 isDisabled: false,
1121 createdAt: '2023-01-01T00:00:00Z',
1122 updatedAt: '2023-01-01T00:00:00Z',
1123 toolkit: {
1124 slug: 'test-toolkit',
1125 },
1126 testRequestEndpoint: undefined,
1127 wordId: null,
1128 });
1129 });
1130 });
1131
1132 describe('update', () => {
1133 it('should enable a connected account', async () => {
1134 const nanoid = 'conn_abc123';
1135 const mockResponse = { success: true, id: nanoid, status: 'ACTIVE' };
1136
1137 extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
1138
1139 const result = await connectedAccounts.update(nanoid, { enabled: true });
1140
1141 expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
1142 nanoid,
1143 {
1144 enabled: true,
1145 },
1146 undefined
1147 );
1148 expect(result).toEqual({ success: true, id: nanoid, status: 'ACTIVE' });
1149 });
1150
1151 it('should disable a connected account', async () => {
1152 const nanoid = 'conn_abc123';
1153 const mockResponse = { success: true };
1154
1155 extendedMockClient.connectedAccounts.updateStatus.mockResolvedValueOnce(mockResponse);
1156
1157 const result = await connectedAccounts.update(nanoid, { enabled: false });
1158
1159 expect(extendedMockClient.connectedAccounts.updateStatus).toHaveBeenCalledWith(
1160 nanoid,
1161 {
1162 enabled: false,
1163 },
1164 undefined
1165 );
1166 expect(result).toEqual({ success: true });
1167 });
1168
1169 it('should throw ValidationError for invalid params', async () => {
1170 await expect(
1171 connectedAccounts.update('conn_abc123', { enabled: 'yes' } as unknown)
1172 ).rejects.toThrow('Failed to parse connected account update params');
1173 });
1174 });
1175
1176 describe('link', () => {
1177 beforeEach(() => {
1178 // link() now mirrors initiate() and pre-flights connectedAccounts.list to
1179 // enforce the allowMultiple guard. Default to no existing connections so
1180 // existing tests don't need to mock the list call themselves.
1181 extendedMockClient.connectedAccounts.list.mockResolvedValue({
1182 items: [],
1183 next_cursor: null,
1184 total_pages: 0,
1185 });
1186 });
1187
1188 it('should create a connected account link without options and return a ConnectionRequest', async () => {
1189 const userId = 'user_123';
1190 const authConfigId = 'auth_config_123';
1191
1192 // Mock the API response for client.link.create
1193 const mockLinkResponse = {
1194 connected_account_id: 'conn_456def',
1195 redirect_url: 'https://connect.composio.dev/auth?token=abc123',
1196 };
1197
1198 extendedMockClient.link.create.mockResolvedValueOnce(mockLinkResponse);
1199
1200 const connectionRequest = await connectedAccounts.link(userId, authConfigId);
1201
1202 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1203 {
1204 auth_config_id: authConfigId,
1205 user_id: userId,
1206 },
1207 undefined
1208 );
1209
1210 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1211 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
1212 expect(connectionRequest).toHaveProperty(
1213 'redirectUrl',
1214 'https://connect.composio.dev/auth?token=abc123'
1215 );
1216 expect(connectionRequest).toHaveProperty('waitForConnection');
1217 expect(typeof connectionRequest.waitForConnection).toBe('function');
1218 });
1219
1220 it('should create a connected account link with callback URL and return a ConnectionRequest', async () => {
1221 const userId = 'user_123';
1222 const authConfigId = 'auth_config_123';
1223 const options = {
1224 callbackUrl: 'https://example.com/callback',
1225 };
1226
1227 // Mock the API response for client.link.create
1228 const mockLinkResponse = {
1229 connected_account_id: 'conn_456def',
1230 redirect_url:
1231 'https://connect.composio.dev/auth?token=abc123&callback_url=https://example.com/callback',
1232 };
1233
1234 extendedMockClient.link.create.mockResolvedValueOnce(mockLinkResponse);
1235
1236 const connectionRequest = await connectedAccounts.link(userId, authConfigId, options);
1237
1238 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1239 {
1240 auth_config_id: authConfigId,
1241 user_id: userId,
1242 callback_url: options.callbackUrl,
1243 },
1244 undefined
1245 );
1246
1247 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1248 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
1249 expect(connectionRequest).toHaveProperty(
1250 'redirectUrl',
1251 'https://connect.composio.dev/auth?token=abc123&callback_url=https://example.com/callback'
1252 );
1253 expect(connectionRequest).toHaveProperty('waitForConnection');
1254 expect(typeof connectionRequest.waitForConnection).toBe('function');
1255 });
1256
1257 it('should validate options parameter and throw ValidationError for invalid options', async () => {
1258 const userId = 'user_123';
1259 const authConfigId = 'auth_config_123';
1260 const invalidOptions = {
1261 callbackUrl: 123, // Invalid type - should be string
1262 };
1263
1264 await expect(
1265 connectedAccounts.link(userId, authConfigId, invalidOptions as unknown)
1266 ).rejects.toThrow('Failed to parse create connected account link options');
1267
1268 // Ensure API was not called with invalid options
1269 expect(extendedMockClient.link.create).not.toHaveBeenCalled();
1270 });
1271
1272 it('should return a ConnectionRequest with the expected structure', async () => {
1273 const userId = 'user_123';
1274 const authConfigId = 'auth_config_123';
1275 const options = {
1276 callbackUrl: 'https://example.com/callback',
1277 };
1278
1279 const mockLinkResponse = {
1280 connected_account_id: 'conn_456def',
1281 redirect_url: 'https://connect.composio.dev/auth?token=abc123',
1282 };
1283
1284 extendedMockClient.link.create.mockResolvedValueOnce(mockLinkResponse);
1285
1286 const connectionRequest = await connectedAccounts.link(userId, authConfigId, options);
1287
1288 // Test the structure of the returned ConnectionRequest
1289 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1290 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
1291 expect(connectionRequest).toHaveProperty(
1292 'redirectUrl',
1293 'https://connect.composio.dev/auth?token=abc123'
1294 );
1295 expect(connectionRequest).toHaveProperty('waitForConnection');
1296 expect(connectionRequest).toHaveProperty('toJSON');
1297 expect(connectionRequest).toHaveProperty('toString');
1298
1299 // Test that methods are functions
1300 expect(typeof connectionRequest.waitForConnection).toBe('function');
1301 expect(typeof connectionRequest.toJSON).toBe('function');
1302 expect(typeof connectionRequest.toString).toBe('function');
1303
1304 // Test serialization methods
1305 const jsonObj = connectionRequest.toJSON();
1306 expect(jsonObj).toHaveProperty('id', connectionRequest.id);
1307 expect(jsonObj).toHaveProperty('status', connectionRequest.status);
1308 expect(jsonObj).toHaveProperty('redirectUrl', connectionRequest.redirectUrl);
1309
1310 const jsonString = connectionRequest.toString();
1311 expect(typeof jsonString).toBe('string');
1312 const parsedObj = JSON.parse(jsonString);
1313 expect(parsedObj).toEqual(jsonObj);
1314 });
1315
1316 it('should handle various callback URL formats', async () => {
1317 const userId = 'user_123';
1318 const authConfigId = 'auth_config_123';
1319
1320 const testCases = [
1321 'https://example.com/callback',
1322 'http://localhost:3000/auth/callback',
1323 'https://app.example.com/integration/composio/callback?state=xyz',
1324 'https://subdomain.example.com:8080/callback',
1325 ];
1326
1327 for (const callbackUrl of testCases) {
1328 const mockLinkResponse = {
1329 connected_account_id: 'conn_456def',
1330 redirect_url: 'https://connect.composio.dev/auth?token=abc123',
1331 };
1332
1333 extendedMockClient.link.create.mockResolvedValueOnce(mockLinkResponse);
1334
1335 const options = { callbackUrl };
1336 const connectionRequest = await connectedAccounts.link(userId, authConfigId, options);
1337
1338 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1339 {
1340 auth_config_id: authConfigId,
1341 user_id: userId,
1342 callback_url: callbackUrl,
1343 },
1344 undefined
1345 );
1346
1347 expect(connectionRequest).toHaveProperty('id', 'conn_456def');
1348 expect(connectionRequest).toHaveProperty('status', ConnectedAccountStatuses.INITIATED);
1349 expect(connectionRequest).toHaveProperty('waitForConnection');
1350 expect(typeof connectionRequest.waitForConnection).toBe('function');
1351 }
1352 });
1353
1354 it('should create a connection request that can wait for completion', async () => {
1355 const userId = 'user_123';
1356 const authConfigId = 'auth_config_123';
1357
1358 const mockLinkResponse = {
1359 connected_account_id: 'conn_456def',
1360 redirect_url: 'https://connect.composio.dev/auth?token=abc123',
1361 };
1362
1363 extendedMockClient.link.create.mockResolvedValueOnce(mockLinkResponse);
1364
1365 const connectionRequest = await connectedAccounts.link(userId, authConfigId);
1366
1367 // Mock the retrieve method to simulate connection completion
1368 const mockActiveResponse = {
1369 id: 'conn_456def',
1370 status: ConnectedAccountStatuses.ACTIVE,
1371 auth_config: {
1372 id: authConfigId,
1373 is_composio_managed: true,
1374 is_disabled: false,
1375 },
1376 state: {
1377 authScheme: AuthSchemeTypes.OAUTH2,
1378 val: {
1379 status: ConnectedAccountStatuses.ACTIVE,
1380 access_token: 'access_token_123',
1381 token_type: 'Bearer',
1382 },
1383 },
1384 user_id: userId,
1385 data: {},
1386 params: {},
1387 is_disabled: false,
1388 created_at: '2023-01-01T00:00:00Z',
1389 updated_at: '2023-01-01T00:00:00Z',
1390 status_reason: null,
1391 toolkit: {
1392 slug: 'test-toolkit',
1393 },
1394 };
1395
1396 extendedMockClient.connectedAccounts.retrieve.mockResolvedValueOnce(mockActiveResponse);
1397
1398 const result = await connectionRequest.waitForConnection();
1399
1400 expect(result).toHaveProperty('id', 'conn_456def');
1401 expect(result).toHaveProperty('status', ConnectedAccountStatuses.ACTIVE);
1402 });
1403
1404 it('should throw ComposioFailedToCreateConnectedAccountLink when API call fails', async () => {
1405 const userId = 'user_123';
1406 const authConfigId = 'auth_config_123';
1407 const apiError = new Error('API Error: Network failure');
1408
1409 extendedMockClient.link.create.mockRejectedValueOnce(apiError);
1410
1411 await expect(connectedAccounts.link(userId, authConfigId)).rejects.toThrow(
1412 ComposioFailedToCreateConnectedAccountLink
1413 );
1414
1415 await expect(connectedAccounts.link(userId, authConfigId)).rejects.toThrow(
1416 'Failed to create connected account link'
1417 );
1418
1419 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1420 {
1421 auth_config_id: authConfigId,
1422 user_id: userId,
1423 },
1424 undefined
1425 );
1426 });
1427
1428 it('should not include callback_url in API call when callbackUrl is not provided', async () => {
1429 const userId = 'user_123';
1430 const authConfigId = 'auth_config_123';
1431 const options = {}; // Empty options, no callbackUrl
1432
1433 const mockLinkResponse = {
1434 connected_account_id: 'conn_456def',
1435 redirect_url: 'https://connect.composio.dev/auth?token=abc123',
1436 };
1437
1438 extendedMockClient.link.create.mockResolvedValueOnce(mockLinkResponse);
1439
1440 await connectedAccounts.link(userId, authConfigId, options);
1441
1442 // Verify that callback_url is not included in the API call
1443 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1444 {
1445 auth_config_id: authConfigId,
1446 user_id: userId,
1447 },
1448 undefined
1449 );
1450
1451 // Ensure callback_url key is not present at all
1452 const callArgs = extendedMockClient.link.create.mock.calls[0][0];
1453 expect(callArgs).not.toHaveProperty('callback_url');
1454 });
1455
1456 it('throws ComposioMultipleConnectedAccountsError when an active connection exists and allowMultiple is false', async () => {
1457 const userId = 'user_123';
1458 const authConfigId = 'auth_config_123';
1459
1460 extendedMockClient.connectedAccounts.list.mockReset();
1461 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
1462 items: [
1463 {
1464 id: 'conn_existing',
1465 status: ConnectedAccountStatuses.ACTIVE,
1466 auth_config: { id: authConfigId, auth_scheme: 'OAUTH2', is_composio_managed: true },
1467 toolkit: { slug: 'gmail' },
1468 },
1469 ],
1470 next_cursor: null,
1471 total_pages: 1,
1472 });
1473
1474 await expect(connectedAccounts.link(userId, authConfigId)).rejects.toThrow(
1475 ComposioMultipleConnectedAccountsError
1476 );
1477
1478 expect(extendedMockClient.link.create).not.toHaveBeenCalled();
1479 });
1480
1481 it('skips the guard when allowMultiple is true and proceeds with link.create', async () => {
1482 const userId = 'user_123';
1483 const authConfigId = 'auth_config_123';
1484
1485 extendedMockClient.connectedAccounts.list.mockReset();
1486 extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({
1487 items: [
1488 {
1489 id: 'conn_existing',
1490 status: ConnectedAccountStatuses.ACTIVE,
1491 auth_config: { id: authConfigId, auth_scheme: 'OAUTH2', is_composio_managed: true },
1492 toolkit: { slug: 'gmail' },
1493 },
1494 ],
1495 next_cursor: null,
1496 total_pages: 1,
1497 });
1498 extendedMockClient.link.create.mockResolvedValueOnce({
1499 connected_account_id: 'conn_new',
1500 redirect_url: 'https://connect.composio.dev/auth?token=xyz',
1501 });
1502
1503 const connectionRequest = await connectedAccounts.link(userId, authConfigId, {
1504 allowMultiple: true,
1505 alias: 'work-gmail',
1506 });
1507
1508 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1509 {
1510 auth_config_id: authConfigId,
1511 user_id: userId,
1512 alias: 'work-gmail',
1513 },
1514 undefined
1515 );
1516 expect(connectionRequest).toHaveProperty('id', 'conn_new');
1517 });
1518 });
1519
1520 describe('link with experimental block (SHARED + ACL)', () => {
1521 beforeEach(() => {
1522 extendedMockClient.connectedAccounts.list.mockResolvedValue({
1523 items: [],
1524 next_cursor: null,
1525 total_pages: 0,
1526 });
1527 extendedMockClient.link.create.mockResolvedValue({
1528 connected_account_id: 'conn_shared_abc',
1529 redirect_url: 'https://connect.composio.dev/auth?token=xyz',
1530 });
1531 });
1532
1533 it('forwards experimental block with accountType + aclConfigForShared to client.link.create', async () => {
1534 await connectedAccounts.link('user_123', 'auth_config_123', {
1535 experimental: {
1536 accountType: 'SHARED',
1537 aclConfigForShared: {
1538 allowAllUsers: true,
1539 notAllowedUserIds: ['user_bob'],
1540 },
1541 },
1542 });
1543
1544 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1545 {
1546 auth_config_id: 'auth_config_123',
1547 user_id: 'user_123',
1548 experimental: {
1549 account_type: 'SHARED',
1550 acl_config_for_shared: {
1551 allow_all_users: true,
1552 not_allowed_user_ids: ['user_bob'],
1553 },
1554 },
1555 },
1556 undefined
1557 );
1558 });
1559
1560 it('omits the inner acl block when aclConfigForShared is undefined', async () => {
1561 await connectedAccounts.link('user_123', 'auth_config_123', {
1562 experimental: { accountType: 'SHARED' },
1563 });
1564
1565 const body = extendedMockClient.link.create.mock.calls[0][0];
1566 expect(body.experimental).toEqual({ account_type: 'SHARED' });
1567 expect('acl_config_for_shared' in body.experimental).toBe(false);
1568 });
1569
1570 it('omits the experimental block entirely when not provided', async () => {
1571 await connectedAccounts.link('user_123', 'auth_config_123');
1572
1573 const body = extendedMockClient.link.create.mock.calls[0][0];
1574 expect('experimental' in body).toBe(false);
1575 });
1576
1577 it('serializes only the inner ACL fields the caller provided', async () => {
1578 await connectedAccounts.link('user_123', 'auth_config_123', {
1579 experimental: {
1580 accountType: 'SHARED',
1581 aclConfigForShared: { allowedUserIds: ['user_alice'] },
1582 },
1583 });
1584
1585 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1586 {
1587 auth_config_id: 'auth_config_123',
1588 user_id: 'user_123',
1589 experimental: {
1590 account_type: 'SHARED',
1591 acl_config_for_shared: { allowed_user_ids: ['user_alice'] },
1592 },
1593 },
1594 undefined
1595 );
1596 });
1597
1598 it('preserves explicit empty arrays in the serialized body', async () => {
1599 await connectedAccounts.link('user_123', 'auth_config_123', {
1600 experimental: {
1601 accountType: 'SHARED',
1602 aclConfigForShared: { allowedUserIds: [], notAllowedUserIds: [] },
1603 },
1604 });
1605
1606 expect(extendedMockClient.link.create).toHaveBeenCalledWith(
1607 {
1608 auth_config_id: 'auth_config_123',
1609 user_id: 'user_123',
1610 experimental: {
1611 account_type: 'SHARED',
1612 acl_config_for_shared: {
1613 allowed_user_ids: [],
1614 not_allowed_user_ids: [],
1615 },
1616 },
1617 },
1618 undefined
1619 );
1620 });
1621
1622 it('maps 400 AclOnlyForShared to ComposioAclOnlyForSharedError', async () => {
1623 extendedMockClient.link.create.mockReset();
1624 extendedMockClient.link.create.mockRejectedValueOnce(
1625 Object.assign(
1626 new BadRequestError(
1627 400,
1628 undefined,
1629 'acl_config_for_shared is only valid on SHARED connections.',
1630 {}
1631 ),
1632 {}
1633 )
1634 );
1635
1636 await expect(
1637 connectedAccounts.link('user_123', 'auth_config_123', {
1638 experimental: {
1639 accountType: 'PRIVATE',
1640 aclConfigForShared: { allowAllUsers: true },
1641 },
1642 })
1643 ).rejects.toBeInstanceOf(ComposioAclOnlyForSharedError);
1644 });
1645
1646 it('falls back to ComposioFailedToCreateConnectedAccountLink on unrelated errors', async () => {
1647 extendedMockClient.link.create.mockReset();
1648 extendedMockClient.link.create.mockRejectedValueOnce(new Error('network died'));
1649
1650 await expect(connectedAccounts.link('user_123', 'auth_config_123')).rejects.toBeInstanceOf(
1651 ComposioFailedToCreateConnectedAccountLink
1652 );
1653 });
1654 });
1655
1656 describe('list with accountType filter', () => {
1657 it('forwards accountType to the wire as a flat query param', async () => {
1658 extendedMockClient.connectedAccounts.list.mockResolvedValue({
1659 items: [],
1660 next_cursor: null,
1661 total_pages: 0,
1662 });
1663
1664 await connectedAccounts.list({ accountType: 'SHARED', userIds: ['user_creator'] });
1665
1666 const callArg = extendedMockClient.connectedAccounts.list.mock.calls[0][0];
1667 expect(callArg.account_type).toBe('SHARED');
1668 expect(callArg.user_ids).toEqual(['user_creator']);
1669 });
1670
1671 it('omits account_type when accountType is not provided', async () => {
1672 extendedMockClient.connectedAccounts.list.mockResolvedValue({
1673 items: [],
1674 next_cursor: null,
1675 total_pages: 0,
1676 });
1677
1678 await connectedAccounts.list({ userIds: ['user_creator'] });
1679
1680 const callArg = extendedMockClient.connectedAccounts.list.mock.calls[0][0];
1681 expect('account_type' in callArg).toBe(false);
1682 });
1683 });
1684
1685 describe('connectedAccounts.updateAcl', () => {
1686 it('serializes PATCH body under experimental.acl_config_for_shared', async () => {
1687 extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1688 id: 'ca_abc',
1689 status: 'ACTIVE',
1690 success: true,
1691 });
1692
1693 const result = await connectedAccounts.updateAcl('ca_abc', {
1694 allowAllUsers: true,
1695 notAllowedUserIds: ['user_bob'],
1696 });
1697
1698 expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1699 experimental: {
1700 acl_config_for_shared: {
1701 allow_all_users: true,
1702 not_allowed_user_ids: ['user_bob'],
1703 },
1704 },
1705 });
1706 expect(result).toEqual({ id: 'ca_abc', status: 'ACTIVE', success: true });
1707 });
1708
1709 it('keeps composio.experimental.updateAcl as an alias', async () => {
1710 const experimental = new Experimental(extendedMockClient as unknown as ComposioClient);
1711 extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1712 id: 'ca_abc',
1713 status: 'ACTIVE',
1714 success: true,
1715 });
1716
1717 await experimental.updateAcl('ca_abc', { allowAllUsers: true });
1718
1719 expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1720 experimental: { acl_config_for_shared: { allow_all_users: true } },
1721 });
1722 });
1723
1724 it('omits absent fields from the inner block (PATCH semantics)', async () => {
1725 extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1726 id: 'ca_abc',
1727 status: 'ACTIVE',
1728 success: true,
1729 });
1730
1731 await connectedAccounts.updateAcl('ca_abc', { allowedUserIds: ['user_alice'] });
1732
1733 expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1734 experimental: {
1735 acl_config_for_shared: { allowed_user_ids: ['user_alice'] },
1736 },
1737 });
1738 });
1739
1740 it('preserves empty array to clear a list', async () => {
1741 extendedMockClient.connectedAccounts.patch.mockResolvedValueOnce({
1742 id: 'ca_abc',
1743 status: 'ACTIVE',
1744 success: true,
1745 });
1746
1747 await connectedAccounts.updateAcl('ca_abc', { allowedUserIds: [] });
1748
1749 expect(extendedMockClient.connectedAccounts.patch).toHaveBeenCalledWith('ca_abc', {
1750 experimental: { acl_config_for_shared: { allowed_user_ids: [] } },
1751 });
1752 });
1753
1754 it('rejects an empty params object via the refine', async () => {
1755 await expect(connectedAccounts.updateAcl('ca_abc', {})).rejects.toMatchObject({
1756 name: 'ValidationError',
1757 });
1758 expect(extendedMockClient.connectedAccounts.patch).not.toHaveBeenCalled();
1759 });
1760
1761 it('maps 400 AclOnlyForShared to ComposioAclOnlyForSharedError', async () => {
1762 extendedMockClient.connectedAccounts.patch.mockRejectedValueOnce(
1763 new BadRequestError(
1764 400,
1765 undefined,
1766 'acl_config_for_shared is only valid on SHARED connections.',
1767 {}
1768 )
1769 );
1770
1771 await expect(
1772 connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true })
1773 ).rejects.toBeInstanceOf(ComposioAclOnlyForSharedError);
1774 });
1775
1776 it('rethrows non-AclOnlyForShared errors unchanged', async () => {
1777 const otherError = new Error('connection lost');
1778 extendedMockClient.connectedAccounts.patch.mockRejectedValueOnce(otherError);
1779
1780 await expect(connectedAccounts.updateAcl('ca_abc', { allowAllUsers: true })).rejects.toBe(
1781 otherError
1782 );
1783 });
1784 });
1785
1786 describe('revoke', () => {
1787 const nanoid = 'conn_123';
1788
1789 it('should revoke a connected account and transform the response', async () => {
1790 extendedMockClient.connectedAccounts.revoke.mockResolvedValueOnce({
1791 revoked_tokens: ['access_token', 'refresh_token'],
1792 connected_account: { id: nanoid, status: 'REVOKED' },
1793 });
1794
1795 const result = await connectedAccounts.revoke(nanoid);
1796
1797 expect(extendedMockClient.connectedAccounts.revoke).toHaveBeenCalledWith(nanoid, undefined);
1798 expect(result).toEqual({
1799 revokedTokens: ['access_token', 'refresh_token'],
1800 connectedAccount: { id: nanoid, status: 'REVOKED' },
1801 });
1802 });
1803
1804 it('should forward request options', async () => {
1805 extendedMockClient.connectedAccounts.revoke.mockResolvedValueOnce({
1806 revoked_tokens: [],
1807 connected_account: { id: nanoid, status: 'REVOKED' },
1808 });
1809 const signal = new AbortController().signal;
1810
1811 await connectedAccounts.revoke(nanoid, { signal });
1812
1813 expect(extendedMockClient.connectedAccounts.revoke).toHaveBeenCalledWith(nanoid, { signal });
1814 });
1815
1816 it('should surface a 400 as ComposioConnectedAccountRevocationNotSupportedError', async () => {
1817 extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(
1818 new BadRequestError(400, undefined, 'Toolkit does not support revocation', {})
1819 );
1820
1821 const error = await connectedAccounts.revoke(nanoid).catch((caught: unknown) => caught);
1822
1823 expect(error).toBeInstanceOf(ComposioConnectedAccountRevocationNotSupportedError);
1824 expect(error).toMatchObject({
1825 message: expect.stringContaining('does not support revocation'),
1826 meta: { nanoid },
1827 });
1828 });
1829
1830 it('should surface a 409 as ComposioConnectedAccountNotRevokableError', async () => {
1831 extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(
1832 new ConflictError(409, undefined, 'Connection is not in a revokable state', {})
1833 );
1834
1835 await expect(connectedAccounts.revoke(nanoid)).rejects.toThrow(
1836 ComposioConnectedAccountNotRevokableError
1837 );
1838 });
1839
1840 it('should rethrow other errors unchanged', async () => {
1841 const serverError = new InternalServerError(500, undefined, 'boom', {});
1842 extendedMockClient.connectedAccounts.revoke.mockRejectedValueOnce(serverError);
1843
1844 await expect(connectedAccounts.revoke(nanoid)).rejects.toBe(serverError);
1845 });
1846 });
1847
1848 describe('completeAuth', () => {
1849 it('should redeem the session and transform the response', async () => {
1850 extendedMockClient.connectedAccounts.completeAuth.mockResolvedValueOnce({
1851 connected_account_id: 'ca_123',
1852 toolkit_slug: 'github',
1853 });
1854
1855 const result = await connectedAccounts.completeAuth({
1856 userId: 'user_1',
1857 sessionUri: 'session_abc',
1858 });
1859
1860 expect(extendedMockClient.connectedAccounts.completeAuth).toHaveBeenCalledWith(
1861 { user_id: 'user_1', session_uri: 'session_abc' },
1862 undefined
1863 );
1864 expect(result).toEqual({ connectedAccountId: 'ca_123', toolkitSlug: 'github' });
1865 });
1866
1867 it('should forward request options', async () => {
1868 extendedMockClient.connectedAccounts.completeAuth.mockResolvedValueOnce({
1869 connected_account_id: 'ca_123',
1870 toolkit_slug: 'github',
1871 });
1872 const signal = new AbortController().signal;
1873
1874 await connectedAccounts.completeAuth(
1875 { userId: 'user_1', sessionUri: 'session_abc' },
1876 { signal }
1877 );
1878
1879 expect(extendedMockClient.connectedAccounts.completeAuth).toHaveBeenCalledWith(
1880 { user_id: 'user_1', session_uri: 'session_abc' },
1881 { signal }
1882 );
1883 });
1884
1885 it('should reject an empty userId before calling the API', async () => {
1886 await expect(
1887 connectedAccounts.completeAuth({ userId: '', sessionUri: 'session_abc' })
1888 ).rejects.toThrow('Failed to parse connected account completeAuth params');
1889 expect(extendedMockClient.connectedAccounts.completeAuth).not.toHaveBeenCalled();
1890 });
1891
1892 it('should rethrow API errors unchanged', async () => {
1893 const notFound = new NotFoundError(404, undefined, 'Session not found', {});
1894 extendedMockClient.connectedAccounts.completeAuth.mockRejectedValueOnce(notFound);
1895
1896 await expect(
1897 connectedAccounts.completeAuth({ userId: 'user_1', sessionUri: 'session_abc' })
1898 ).rejects.toBe(notFound);
1899 });
1900 });
1901 });