1
+import http from 'node:http';
2
+import fs from 'node:fs/promises';
3
+import os from 'node:os';
4
+import path from 'node:path';
5
+import open from 'open';
6
+import { Effect, Option } from 'effect';
7
+import { resolveCliConfigDirectorySync } from 'src/services/cli-user-config';
8
+import { requestNativeUiPermissionDecision } from 'src/services/native-ui-sidecar';
9
+import { ComposioUserContext } from 'src/services/user-context';
10
+
11
+export const ENHANCED_LINK_URL_OVERWRITE = 'https://connect.composio.dev/enhanced';
12
+
13
+const CACHE_FILE_NAME = 'tool-permissions-cache.json';
14
+const CACHE_TTL_MS = 5 * 60 * 1000;
15
+const NO_CONNECTED_ACCOUNT = '__none__';
16
+
17
+export type PermissionDefaultMode = 'allow_all' | 'ask_every_call' | 'ask_once_per_session';
18
+export type PermissionOverrideState = 'always_allow' | 'always_deny' | 'ask_once' | 'ask_always';
19
+export type PermissionDecision = 'allow_once' | 'allow_session' | 'deny';
20
+
21
+export interface ToolRouterPermissionsConfig {
22
+ readonly default: PermissionDefaultMode;
23
+ readonly overrides?: Readonly<Record<string, PermissionOverrideState>>;
24
+}
25
+
26
+export interface ConsumerPermissionSnapshot {
27
+ readonly orgId: string;
28
+ readonly projectId: string;
29
+ readonly consumerUserId: string;
30
+ readonly enhancedControlsEnabled: boolean;
31
+ readonly permissions?: ToolRouterPermissionsConfig;
32
+ readonly connectedAccountIds: ReadonlyArray<string>;
33
+ readonly fetchedAt: number;
34
+}
35
+
36
+interface CacheFile {
37
+ readonly entries: Readonly<Record<string, ConsumerPermissionSnapshot>>;
38
+}
39
+
40
+interface PermissionResolveResponse {
41
+ readonly experimental?: {
42
+ readonly permissions?: ToolRouterPermissionsConfig;
43
+ };
44
+}
45
+
46
+interface ConsumerConfigResponse {
47
+ readonly enhanced_controls?: boolean;
48
+ readonly enhancedControls?: boolean;
49
+}
50
+
51
+interface GateParams {
52
+ readonly toolSlug: string;
53
+ readonly connectedAccountId?: string;
54
+ readonly connectedAccountWordId?: string;
55
+ readonly snapshot?: ConsumerPermissionSnapshot;
56
+}
57
+
58
+const sessionAllowCache = new Set<string>();
59
+
60
+const cachePath = () => path.join(resolveCliConfigDirectorySync(), CACHE_FILE_NAME);
61
+const cacheKey = (params: { orgId: string; projectId: string; consumerUserId: string }) =>
62
+ [params.orgId, params.projectId, params.consumerUserId].join(':');
63
+const normalizeBaseUrl = (baseURL: string) => baseURL.replace(/\/$/, '');
64
+
65
+const uniq = (values: ReadonlyArray<string | undefined>) => [
66
+ ...new Set(values.filter((value): value is string => Boolean(value))),
67
+];
68
+
69
+const readCacheFile = async (): Promise<CacheFile> => {
70
+ try {
71
+ const raw = await fs.readFile(cachePath(), 'utf8');
72
+ const parsed = JSON.parse(raw) as CacheFile;
73
+ return parsed && typeof parsed === 'object' && parsed.entries ? parsed : { entries: {} };
74
+ } catch {
75
+ return { entries: {} };
76
+ }
77
+};
78
+
79
+const writeCacheEntry = async (entry: ConsumerPermissionSnapshot): Promise<void> => {
80
+ await fs.mkdir(path.dirname(cachePath()), { recursive: true });
81
+ const current = await readCacheFile();
82
+ await fs.writeFile(
83
+ cachePath(),
84
+ `${JSON.stringify(
85
+ {
86
+ entries: {
87
+ ...current.entries,
88
+ [cacheKey(entry)]: entry,
89
+ },
90
+ } satisfies CacheFile,
91
+ null,
92
+ 2
93
+ )}\n`,
94
+ 'utf8'
95
+ );
96
+};
97
+
98
+const readCachedEntry = async (params: {
99
+ orgId: string;
100
+ projectId: string;
101
+ consumerUserId: string;
102
+}): Promise<ConsumerPermissionSnapshot | undefined> => {
103
+ const cache = await readCacheFile();
104
+ return cache.entries[cacheKey(params)];
105
+};
106
+
107
+const isFreshForAccounts = (
108
+ entry: ConsumerPermissionSnapshot | undefined,
109
+ connectedAccountIds: ReadonlyArray<string>
110
+): entry is ConsumerPermissionSnapshot => {
111
+ if (!entry) return false;
112
+ if (Date.now() - entry.fetchedAt > CACHE_TTL_MS) return false;
113
+ const cachedIds = new Set(entry.connectedAccountIds);
114
+ return connectedAccountIds.every(id => cachedIds.has(id));
115
+};
116
+
117
+const readEnhancedControlsFlag = (payload: ConsumerConfigResponse): boolean =>
118
+ payload.enhanced_controls === true || payload.enhancedControls === true;
119
+
120
+const fetchJson = async <T>({
121
+ baseURL,
122
+ apiKey,
123
+ orgId,
124
+ projectId,
125
+ path,
126
+ method = 'GET',
127
+ body,
128
+}: {
129
+ readonly baseURL: string;
130
+ readonly apiKey: string;
131
+ readonly orgId: string;
132
+ readonly projectId: string;
133
+ readonly path: string;
134
+ readonly method?: 'GET' | 'POST';
135
+ readonly body?: unknown;
136
+}): Promise<T> => {
137
+ const response = await fetch(`${normalizeBaseUrl(baseURL)}${path}`, {
138
+ method,
139
+ redirect: 'error',
140
+ headers: {
141
+ 'x-user-api-key': apiKey,
142
+ 'x-org-id': orgId,
143
+ 'x-project-id': projectId,
144
+ 'User-Agent': '@composio/cli',
145
+ Accept: 'application/json',
146
+ 'Content-Type': 'application/json',
147
+ },
148
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
149
+ });
150
+ if (!response.ok) {
151
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
152
+ }
153
+ return (await response.json()) as T;
154
+};
155
+
156
+export const refreshConsumerPermissionSnapshot = (params: {
157
+ readonly orgId: string;
158
+ readonly projectId: string;
159
+ readonly consumerUserId: string;
160
+ readonly connectedAccountIds?: ReadonlyArray<string>;
161
+}) =>
162
+ Effect.gen(function* () {
163
+ const userContext = yield* ComposioUserContext;
164
+ const apiKey = Option.getOrUndefined(userContext.data.apiKey);
165
+ if (!apiKey) return undefined;
166
+
167
+ const connectedAccountIds = uniq(params.connectedAccountIds ?? []);
168
+ const config = yield* Effect.tryPromise(() =>
169
+ fetchJson<ConsumerConfigResponse>({
170
+ baseURL: userContext.data.baseURL,
171
+ apiKey,
172
+ orgId: params.orgId,
173
+ projectId: params.projectId,
174
+ path: '/api/v3.1/org/consumer/config',
175
+ })
176
+ );
177
+ const enhancedControlsEnabled = readEnhancedControlsFlag(config);
178
+ const permissions =
179
+ enhancedControlsEnabled && connectedAccountIds.length > 0
180
+ ? yield* Effect.tryPromise(() =>
181
+ fetchJson<PermissionResolveResponse>({
182
+ baseURL: userContext.data.baseURL,
183
+ apiKey,
184
+ orgId: params.orgId,
185
+ projectId: params.projectId,
186
+ path: '/api/v3.1/consumer/permissions/resolve',
187
+ method: 'POST',
188
+ body: {
189
+ connected_account_ids: connectedAccountIds,
190
+ default: 'ask_every_call',
191
+ },
192
+ })
193
+ ).pipe(Effect.map(response => response.experimental?.permissions))
194
+ : undefined;
195
+
196
+ const snapshot: ConsumerPermissionSnapshot = {
197
+ orgId: params.orgId,
198
+ projectId: params.projectId,
199
+ consumerUserId: params.consumerUserId,
200
+ enhancedControlsEnabled,
201
+ permissions,
202
+ connectedAccountIds,
203
+ fetchedAt: Date.now(),
204
+ };
205
+ yield* Effect.tryPromise(() => writeCacheEntry(snapshot));
206
+ return snapshot;
207
+ }).pipe(
208
+ Effect.catchAll(error =>
209
+ Effect.gen(function* () {
210
+ yield* Effect.logDebug('Failed to refresh consumer permission cache', error);
211
+ return undefined;
212
+ })
213
+ )
214
+ );
215
+
216
+export const getConsumerPermissionSnapshot = (params: {
217
+ readonly orgId: string;
218
+ readonly projectId: string;
219
+ readonly consumerUserId: string;
220
+ readonly connectedAccountIds?: ReadonlyArray<string>;
221
+}) =>
222
+ Effect.gen(function* () {
223
+ const connectedAccountIds = uniq(params.connectedAccountIds ?? []);
224
+ const cached = yield* Effect.tryPromise(() => readCachedEntry(params)).pipe(
225
+ Effect.catchAll(() => Effect.succeed(undefined))
226
+ );
227
+
228
+ if (isFreshForAccounts(cached, connectedAccountIds)) {
229
+ yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds }).pipe(
230
+ Effect.forkDaemon,
231
+ Effect.catchAll(() => Effect.void)
232
+ );
233
+ return cached;
234
+ }
235
+
236
+ const refreshed = yield* refreshConsumerPermissionSnapshot({ ...params, connectedAccountIds });
237
+ return refreshed ?? cached;
238
+ });
239
+
240
+const permissionField = (toolSlug: string, connectedAccountId?: string) =>
241
+ `${toolSlug}:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`;
242
+const accountPermissionField = (connectedAccountId?: string) =>
243
+ `*:${connectedAccountId ?? NO_CONNECTED_ACCOUNT}`;
244
+
245
+const resolvePermissionState = (
246
+ params: GateParams
247
+): PermissionOverrideState | PermissionDefaultMode => {
248
+ const permissions = params.snapshot?.permissions;
249
+ const override =
250
+ permissions?.overrides?.[permissionField(params.toolSlug, params.connectedAccountId)] ??
251
+ permissions?.overrides?.[accountPermissionField(params.connectedAccountId)];
252
+ return override ?? permissions?.default ?? 'allow_all';
253
+};
254
+
255
+const sessionCacheKey = (params: GateParams) =>
256
+ `${params.snapshot?.orgId ?? 'unknown'}:${params.snapshot?.projectId ?? 'unknown'}:${params.snapshot?.consumerUserId ?? 'unknown'}:${permissionField(params.toolSlug, params.connectedAccountId)}`;
257
+
258
+const escapeHtml = (value: string): string =>
259
+ value.replace(/[&<>"']/g, char => {
260
+ switch (char) {
261
+ case '&':
262
+ return '&';
263
+ case '<':
264
+ return '<';
265
+ case '>':
266
+ return '>';
267
+ case '"':
268
+ return '"';
269
+ default:
270
+ return ''';
271
+ }
272
+ });
273
+
274
+const html = (params: { toolSlug: string; accountLabel?: string; port: number; token: string }) => {
275
+ const toolSlug = escapeHtml(params.toolSlug);
276
+ const accountLabel = params.accountLabel ? escapeHtml(params.accountLabel) : undefined;
277
+ return `<!doctype html>
278
+<html>
279
+<head>
280
+ <meta charset="utf-8" />
281
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
282
+ <title>Allow ${toolSlug}?</title>
283
+ <style>
284
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: radial-gradient(circle at 20% 20%, #7c3aed33, transparent 35%), #080812; color: white; }
285
+ main { width: min(520px, calc(100vw - 32px)); padding: 28px; border: 1px solid #ffffff22; border-radius: 24px; background: #ffffff12; box-shadow: 0 24px 80px #0008; backdrop-filter: blur(24px); }
286
+ h1 { margin: 0 0 10px; font-size: 24px; }
287
+ p { color: #d6d6e7; line-height: 1.5; }
288
+ .actions { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 22px; }
289
+ a { color: white; text-decoration: none; padding: 11px 14px; border-radius: 999px; background: #ffffff1c; }
290
+ a.primary { background: #7c3aed; }
291
+ </style>
292
+</head>
293
+<body>
294
+ <main>
295
+ <h1>Allow ${toolSlug}?</h1>
296
+ <p>Composio CLI is requesting permission to execute this tool${accountLabel ? ` for ${accountLabel}` : ''}.</p>
297
+ <div class="actions">
298
+ <a class="primary" href="http://127.0.0.1:${params.port}/allow-session?token=${params.token}">Allow for this session</a>
299
+ <a href="http://127.0.0.1:${params.port}/allow-once?token=${params.token}">Allow once</a>
300
+ <a href="http://127.0.0.1:${params.port}/deny?token=${params.token}">Deny</a>
301
+ </div>
302
+ </main>
303
+</body>
304
+</html>`;
305
+};
306
+
307
+const requestPermissionInBrowser = (params: {
308
+ readonly toolSlug: string;
309
+ readonly accountLabel?: string;
310
+}): Promise<PermissionDecision> =>
311
+ new Promise((resolve, reject) => {
312
+ const token = crypto.randomUUID();
313
+ const server = http.createServer((req, res) => {
314
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
315
+ if (url.searchParams.get('token') !== token) {
316
+ res.writeHead(403).end('Forbidden');
317
+ return;
318
+ }
319
+ const decision =
320
+ url.pathname === '/allow-session'
321
+ ? 'allow_session'
322
+ : url.pathname === '/allow-once'
323
+ ? 'allow_once'
324
+ : url.pathname === '/deny'
325
+ ? 'deny'
326
+ : undefined;
327
+ if (!decision) {
328
+ res.writeHead(404).end('Not found');
329
+ return;
330
+ }
331
+ res.writeHead(200, { 'Content-Type': 'text/html' }).end('<p>You can close this tab.</p>');
332
+ server.close();
333
+ resolve(decision);
334
+ });
335
+
336
+ const timeout = setTimeout(() => {
337
+ server.close();
338
+ resolve('deny');
339
+ }, 30_000);
340
+
341
+ server.on('close', () => clearTimeout(timeout));
342
+ server.on('error', reject);
343
+ server.listen(0, '127.0.0.1', async () => {
344
+ try {
345
+ const address = server.address();
346
+ const port = typeof address === 'object' && address ? address.port : undefined;
347
+ if (!port) throw new Error('Unable to allocate permission callback port.');
348
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-permission-'));
349
+ const filePath = path.join(dir, 'index.html');
350
+ await fs.writeFile(filePath, html({ ...params, port, token }), 'utf8');
351
+ await open(filePath);
352
+ } catch (error) {
353
+ server.close();
354
+ reject(error);
355
+ }
356
+ });
357
+ });
358
+
359
+const requestPermissionDecision = async (params: {
360
+ readonly toolSlug: string;
361
+ readonly accountLabel?: string;
362
+}): Promise<PermissionDecision> => {
363
+ const nativeDecision = await requestNativeUiPermissionDecision(params);
364
+ if (nativeDecision === 'allow_once' || nativeDecision === 'allow_session') return nativeDecision;
365
+ if (nativeDecision === 'deny' || nativeDecision === 'dismissed') return 'deny';
366
+ return requestPermissionInBrowser(params);
367
+};
368
+
369
+export const gateToolExecution = (params: GateParams) =>
370
+ Effect.gen(function* () {
371
+ if (!params.snapshot?.enhancedControlsEnabled || !params.snapshot.permissions) return;
372
+
373
+ const state = resolvePermissionState(params);
374
+ if (state === 'allow_all' || state === 'always_allow') return;
375
+ if (state === 'always_deny') {
376
+ return yield* Effect.fail(
377
+ new Error(`Tool execution denied by permissions: ${params.toolSlug}`)
378
+ );
379
+ }
380
+
381
+ const cacheKey = sessionCacheKey(params);
382
+ const readsSessionCache = state === 'ask_once' || state === 'ask_once_per_session';
383
+ if (readsSessionCache && sessionAllowCache.has(cacheKey)) return;
384
+
385
+ const decision = yield* Effect.tryPromise(() =>
386
+ requestPermissionDecision({
387
+ toolSlug: params.toolSlug,
388
+ accountLabel: params.connectedAccountWordId,
389
+ })
390
+ );
391
+
392
+ if (decision === 'deny') {
393
+ return yield* Effect.fail(new Error(`Tool execution denied by user: ${params.toolSlug}`));
394
+ }
395
+ if (decision === 'allow_session' || (readsSessionCache && decision === 'allow_once')) {
396
+ sessionAllowCache.add(cacheKey);
397
+ }
398
+ });