|
| 1 | +import { |
| 2 | + Composio, |
| 3 | + type ConnectedAccountListResponseItem, |
| 4 | +} from "@composio/core"; |
| 5 | +import { COMPOSIO_API_KEY, COMPOSIO_CONNECTION_CALLBACK_URL } from "@/config"; |
| 6 | +import logger from "@/utils/logger"; |
| 7 | + |
| 8 | +// Auth configs rarely change in Composio; cache the toolkit→authConfigId |
| 9 | +// resolution in-process so most initiate calls skip the extra round trip. |
| 10 | +const AUTH_CONFIG_CACHE_TTL_MS = 5 * 60 * 1000; |
| 11 | + |
| 12 | +type AuthConfigCacheEntry = { authConfigId: string | null; expiresAt: number }; |
| 13 | + |
| 14 | +export class ComposioService { |
| 15 | + private composio: Composio; |
| 16 | + private authConfigCache = new Map<string, AuthConfigCacheEntry>(); |
| 17 | + |
| 18 | + constructor(args: { composio: Composio }) { |
| 19 | + this.composio = args.composio; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Resolve a toolkit slug (e.g. "googlecalendar") to its Composio authConfigId |
| 24 | + * by querying Composio. Picks the first ENABLED auth config for that toolkit. |
| 25 | + * Returns null if no enabled config exists. |
| 26 | + * |
| 27 | + * Clients must send Composio's canonical slug (case-insensitive). |
| 28 | + */ |
| 29 | + async resolveAuthConfigId(toolkit: string): Promise<string | null> { |
| 30 | + const now = Date.now(); |
| 31 | + const normalized = toolkit.toLowerCase(); |
| 32 | + const hit = this.authConfigCache.get(normalized); |
| 33 | + if (hit && hit.expiresAt > now) { |
| 34 | + return hit.authConfigId; |
| 35 | + } |
| 36 | + |
| 37 | + const list = await this.composio.authConfigs.list({ toolkit: normalized }); |
| 38 | + const enabled = list.items.find( |
| 39 | + (item) => |
| 40 | + item.toolkit.slug.toLowerCase() === normalized && |
| 41 | + item.status === "ENABLED", |
| 42 | + ); |
| 43 | + const authConfigId = enabled?.id ?? null; |
| 44 | + |
| 45 | + if (!authConfigId) { |
| 46 | + logger.warn( |
| 47 | + { |
| 48 | + toolkit: normalized, |
| 49 | + returnedItems: list.items.map((item) => ({ |
| 50 | + id: item.id, |
| 51 | + slug: item.toolkit.slug, |
| 52 | + status: item.status, |
| 53 | + isComposioManaged: item.isComposioManaged, |
| 54 | + })), |
| 55 | + totalPages: list.totalPages, |
| 56 | + }, |
| 57 | + "[Composio] resolveAuthConfigId: no ENABLED config matched", |
| 58 | + ); |
| 59 | + } else { |
| 60 | + logger.info( |
| 61 | + { toolkit: normalized, authConfigId }, |
| 62 | + "[Composio] resolveAuthConfigId: resolved", |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + this.authConfigCache.set(normalized, { |
| 67 | + authConfigId, |
| 68 | + expiresAt: now + AUTH_CONFIG_CACHE_TTL_MS, |
| 69 | + }); |
| 70 | + return authConfigId; |
| 71 | + } |
| 72 | + |
| 73 | + async initiate(args: { |
| 74 | + userId: string; |
| 75 | + authConfigId: string; |
| 76 | + callbackUrl?: string; |
| 77 | + }) { |
| 78 | + return this.composio.connectedAccounts.initiate( |
| 79 | + args.userId, |
| 80 | + args.authConfigId, |
| 81 | + { |
| 82 | + callbackUrl: args.callbackUrl ?? COMPOSIO_CONNECTION_CALLBACK_URL, |
| 83 | + }, |
| 84 | + ); |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Fetch a connected account only if it belongs to the given userId. |
| 89 | + * Returns null if it doesn't exist or isn't owned by the caller. |
| 90 | + * |
| 91 | + * Composio's retrieve endpoint no longer returns userId on the response, |
| 92 | + * so ownership is verified by listing the caller's accounts. |
| 93 | + */ |
| 94 | + async getIfOwned(args: { connectionId: string; userId: string }) { |
| 95 | + const list = await this.composio.connectedAccounts.list({ |
| 96 | + userIds: [args.userId], |
| 97 | + }); |
| 98 | + const items: ConnectedAccountListResponseItem[] = list.items; |
| 99 | + return items.find((item) => item.id === args.connectionId) ?? null; |
| 100 | + } |
| 101 | + |
| 102 | + async listForUser(userId: string) { |
| 103 | + return this.composio.connectedAccounts.list({ userIds: [userId] }); |
| 104 | + } |
| 105 | + |
| 106 | + async delete(connectionId: string) { |
| 107 | + return this.composio.connectedAccounts.delete(connectionId); |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +let cached: ComposioService | null = null; |
| 112 | +let initialized = false; |
| 113 | + |
| 114 | +export function createComposioService(): ComposioService | null { |
| 115 | + if (initialized) { |
| 116 | + return cached; |
| 117 | + } |
| 118 | + initialized = true; |
| 119 | + |
| 120 | + if (!COMPOSIO_API_KEY) { |
| 121 | + logger.warn("[Composio] COMPOSIO_API_KEY not set, connections disabled"); |
| 122 | + return null; |
| 123 | + } |
| 124 | + |
| 125 | + cached = new ComposioService({ |
| 126 | + composio: new Composio({ |
| 127 | + apiKey: COMPOSIO_API_KEY, |
| 128 | + allowTracking: false, |
| 129 | + }), |
| 130 | + }); |
| 131 | + logger.info("[Composio] Initialised service"); |
| 132 | + return cached; |
| 133 | +} |
| 134 | + |
| 135 | +// Exposed for tests — resets the singleton. |
| 136 | +export function __resetComposioServiceForTests( |
| 137 | + override: ComposioService | null = null, |
| 138 | +) { |
| 139 | + cached = override; |
| 140 | + initialized = override !== null; |
| 141 | +} |
0 commit comments