@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 161 lines 5.9 KB
Raw
1 import * as BunPath from '@effect/platform-bun/BunPath';
2 import { Effect, Option, Context, Layer } from 'effect';
3 import * as FileSystem from 'effect/FileSystem';
4 import * as Path from 'effect/Path';
5 import { NodeOs } from 'src/services/node-os';
6 import { NodeProcess } from 'src/services/node-process';
7 import { APP_CONFIG } from 'src/config';
8 import { getAncestors } from 'src/utils/get-ancestors';
9 import * as constants from 'src/constants';
10 import { type ProjectKeys, projectKeysFromJSON } from 'src/models/project-keys';
11
12 /**
13 * Keys allowed in `.composio/.env` files.
14 * Only project context keys are permitted -- NOT API_KEY or BASE_URL,
15 * to prevent credential injection via malicious repo clones.
16 */
17 const ALLOWED_ENV_KEYS = new Set(['COMPOSIO_ORG_ID', 'COMPOSIO_PROJECT_ID']);
18
19 /**
20 * Parse a `.env` file into a key-value map.
21 * Only keys in the ALLOWED_ENV_KEYS set are returned.
22 */
23 const parseEnvFile = (content: string): Map<string, string> => {
24 const result = new Map<string, string>();
25 for (const line of content.split('\n')) {
26 const trimmed = line.trim();
27 if (trimmed === '' || trimmed.startsWith('#')) continue;
28 const eqIndex = trimmed.indexOf('=');
29 if (eqIndex === -1) continue;
30 const key = trimmed.slice(0, eqIndex).trim();
31 let value = trimmed.slice(eqIndex + 1).trim();
32 // Strip surrounding quotes (single or double) consistent with dotenv convention
33 if (
34 (value.startsWith('"') && value.endsWith('"')) ||
35 (value.startsWith("'") && value.endsWith("'"))
36 ) {
37 value = value.slice(1, -1);
38 }
39 if (ALLOWED_ENV_KEYS.has(key)) {
40 result.set(key, value);
41 }
42 }
43 return result;
44 };
45
46 /**
47 * Service that resolves the current developer project context using a precedence chain.
48 * Read-only -- it does NOT write files and is never used for consumer-project routing.
49 *
50 * Precedence (highest first):
51 * 1. System env vars (COMPOSIO_ORG_ID, COMPOSIO_PROJECT_ID)
52 * 2. Per-directory .composio/.env (only allowed keys)
53 * 3. Per-directory .composio/project.json (walk up from CWD, stop at homedir)
54 */
55 const makeProjectContext = Effect.gen(function* () {
56 const fs = yield* FileSystem.FileSystem;
57 const path = yield* Path.Path;
58 const proc = yield* NodeProcess;
59 const os = yield* NodeOs;
60
61 return {
62 /**
63 * Resolves the current org+project context.
64 * Returns Option.none() if no context is configured.
65 */
66 resolve: Effect.gen(function* () {
67 // 1. Check env vars (highest priority)
68 const envOrgId = yield* APP_CONFIG.ORG_ID;
69 const envProjectId = yield* APP_CONFIG.PROJECT_ID;
70 if (envOrgId !== undefined && envProjectId !== undefined) {
71 yield* Effect.logDebug('ProjectContext: resolved from env vars');
72 return Option.some<ProjectKeys>({
73 orgId: envOrgId,
74 projectId: envProjectId,
75 projectName: Option.none(),
76 orgName: Option.none(),
77 email: Option.none(),
78 testUserId: Option.none(),
79 });
80 }
81
82 // 2. Walk up from CWD, stop at homedir (not filesystem root)
83 const stopAt = os.homedir;
84
85 for (const dir of yield* getAncestors(proc.cwd)) {
86 const composioDir = path.join(dir, constants.PROJECT_COMPOSIO_DIR);
87
88 // 2a. Check .composio/.env
89 const envFilePath = path.join(composioDir, constants.PROJECT_ENV_FILE_NAME);
90 const envExists = yield* fs
91 .exists(envFilePath)
92 .pipe(Effect.catch(() => Effect.succeed(false)));
93 if (envExists) {
94 const envContent = yield* fs
95 .readFileString(envFilePath)
96 .pipe(Effect.catch(() => Effect.succeed('')));
97 const envMap = parseEnvFile(envContent);
98 const envFileOrgId = envMap.get('COMPOSIO_ORG_ID');
99 const envFileProjectId = envMap.get('COMPOSIO_PROJECT_ID');
100 if (envFileOrgId && envFileProjectId) {
101 yield* Effect.logDebug(`ProjectContext: resolved from ${envFilePath}`);
102 return Option.some<ProjectKeys>({
103 orgId: envFileOrgId,
104 projectId: envFileProjectId,
105 projectName: Option.none(),
106 orgName: Option.none(),
107 email: Option.none(),
108 testUserId: Option.none(),
109 });
110 }
111 }
112
113 // 2b. Check .composio/project.json
114 const projectJsonPath = path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME);
115 const jsonExists = yield* fs
116 .exists(projectJsonPath)
117 .pipe(Effect.catch(() => Effect.succeed(false)));
118 if (jsonExists) {
119 const content = yield* fs
120 .readFileString(projectJsonPath)
121 .pipe(Effect.catch(() => Effect.succeed('')));
122 if (content) {
123 const keysOpt = yield* projectKeysFromJSON(content).pipe(
124 Effect.map(Option.some),
125 Effect.catch(error =>
126 Effect.gen(function* () {
127 yield* Effect.logDebug(
128 `ProjectContext: corrupt project.json at ${projectJsonPath}, skipping:`,
129 error
130 );
131 return Option.none();
132 })
133 )
134 );
135 if (Option.isSome(keysOpt)) {
136 yield* Effect.logDebug(`ProjectContext: resolved from ${projectJsonPath}`);
137 return keysOpt;
138 }
139 }
140 }
141
142 // Stop at homedir to avoid reading from system directories
143 if (dir === stopAt) break;
144 }
145
146 // 3. Nothing found
147 yield* Effect.logDebug('ProjectContext: no context found');
148 return Option.none<ProjectKeys>();
149 }).pipe(Effect.provideService(Path.Path, path)),
150 };
151 });
152
153 export type ProjectContextShape = Effect.Success<typeof makeProjectContext>;
154
155 export class ProjectContext extends Context.Service<ProjectContext, ProjectContextShape>()(
156 'services/ProjectContext'
157 ) {
158 static readonly Default = Layer.effect(ProjectContext, makeProjectContext).pipe(
159 Layer.provide(BunPath.layer)
160 );
161 }