@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 140 lines 4.08 KB
Raw
1 #!/usr/bin/env bun
2
3 import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
4
5 /**
6 * Mock of the Composio API routes `composio whoami` reads with a user API key.
7 * `ACCEPTED_USER_API_KEY` gets a session; any other key gets the backend's 401
8 * for a revoked user API key. Point the CLI at it via COMPOSIO_BASE_URL.
9 */
10
11 export const ACCEPTED_USER_API_KEY = 'uak_mock_whoami_accepted';
12 export const REJECTED_USER_API_KEY = 'uak_mock_whoami_rejected';
13
14 // Valid against the client's `GET /api/v3.1/auth/session/info` response schema.
15 export const SESSION_INFO = {
16 project: {
17 auto_id: 1,
18 id: '00000000-0000-4000-8000-000000000001',
19 org_id: '00000000-0000-4000-8000-000000000002',
20 name: 'Whoami E2E Project',
21 email: 'project@whoami-e2e.test',
22 nano_id: 'pr_whoami_e2e',
23 created_at: '2024-01-01T00:00:00.000Z',
24 updated_at: '2024-01-01T00:00:00.000Z',
25 webhook_url: null,
26 event_webhook_url: null,
27 webhook_secret: null,
28 triggers_enabled: true,
29 last_subscribed_at: null,
30 deleted: false,
31 is_new_webhook: true,
32 webhook_version: 'V2',
33 org: { id: 'ok_whoami_e2e', name: 'Whoami E2E Org', plan: 'FREE' },
34 },
35 api_key: null,
36 org_member: {
37 id: '00000000-0000-4000-8000-000000000003',
38 email: 'whoami@whoami-e2e.test',
39 name: 'Whoami E2E',
40 role: 'admin',
41 metadata: {},
42 },
43 } as const;
44
45 // The backend's error envelope for a revoked or unknown user API key.
46 export const REJECTED_USER_API_KEY_BODY = {
47 error: {
48 message: 'Invalid or revoked user API key',
49 code: 1803,
50 slug: 'UserApiKey_Unauthorized',
51 status: 401,
52 },
53 } as const;
54
55 export interface MockWhoamiServer {
56 readonly hostBaseUrl: string;
57 readonly dockerBaseUrl: string;
58 /** `METHOD /path` plus the user API key it was sent with, in arrival order. */
59 readonly requests: string[];
60 readonly close: () => Promise<void>;
61 }
62
63 const sendJson = (res: ServerResponse, statusCode: number, body: unknown): void => {
64 res.writeHead(statusCode, { 'Content-Type': 'application/json' });
65 res.end(JSON.stringify(body));
66 };
67
68 const userApiKeyOf = (req: IncomingMessage): string | undefined => {
69 const header = req.headers['x-user-api-key'];
70 return Array.isArray(header) ? header[0] : header;
71 };
72
73 export async function startMockWhoamiServer(options?: {
74 host?: string;
75 port?: number;
76 }): Promise<MockWhoamiServer> {
77 const host = options?.host ?? '0.0.0.0';
78 const port = options?.port ?? 0;
79 const requests: string[] = [];
80
81 const server = createServer((req, res) => {
82 const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`);
83 const method = req.method ?? 'GET';
84 const userApiKey = userApiKeyOf(req);
85 requests.push(`${method} ${url.pathname} ${userApiKey ?? '(no user API key)'}`);
86
87 if (method === 'POST' && url.pathname === '/api/v3/cli/analytics') {
88 sendJson(res, 204, {});
89 return;
90 }
91
92 if (userApiKey !== ACCEPTED_USER_API_KEY) {
93 sendJson(res, 401, REJECTED_USER_API_KEY_BODY);
94 return;
95 }
96
97 if (method === 'GET' && url.pathname === '/api/v3.1/auth/session/info') {
98 sendJson(res, 200, SESSION_INFO);
99 return;
100 }
101
102 if (method === 'GET' && url.pathname === '/api/v3.1/org/consumer/config') {
103 sendJson(res, 200, { enhanced_controls: false });
104 return;
105 }
106
107 sendJson(res, 404, { error: `Unhandled mock route: ${method} ${url.pathname}` });
108 });
109
110 await new Promise<void>((resolve, reject) => {
111 server.once('error', reject);
112 server.listen({ host, port }, () => {
113 server.off('error', reject);
114 resolve();
115 });
116 });
117
118 const address = server.address();
119 if (address === null || typeof address === 'string') {
120 throw new Error('Failed to bind mock whoami server to a TCP port');
121 }
122
123 const close = () =>
124 new Promise<void>((resolve, reject) => {
125 server.close(error => {
126 if (error) {
127 reject(error);
128 return;
129 }
130 resolve();
131 });
132 });
133
134 return {
135 hostBaseUrl: `http://127.0.0.1:${address.port}`,
136 dockerBaseUrl: `http://host.docker.internal:${address.port}`,
137 requests,
138 close,
139 };
140 }