1
+#!/usr/bin/env node
2
+// Idempotent provisioning check for the live example runs.
3
+//
4
+// Verifies that the dedicated (disposable) Composio project holds the auth
5
+// configs and connected accounts the tier-2/3 examples need, creates whatever
6
+// can be created without a human (API-key auth config), and
7
+// prints the remaining one-time OAuth authorizations.
8
+//
9
+// node scripts/examples-provision.mjs # report (stderr) + exports (stdout)
10
+// out=$(node scripts/examples-provision.mjs) && eval "$out"
11
+// load COMPOSIO_EXAMPLES_* into the shell. Do NOT collapse this into
12
+// eval "$(...)": eval reports the status of the text it evaluates, so a
13
+// failed provisioning run would look like success.
14
+// node scripts/examples-provision.mjs --initiate-missing
15
+// also starts an OAuth connection request for each missing account and
16
+// prints the redirect URL to authorize it (one browser visit per toolkit)
17
+// node scripts/examples-provision.mjs --gc [--dry-run]
18
+// DESTRUCTIVE. Deletes resources example runs leak into the project:
19
+// connected accounts that never became ACTIVE, surplus serpapi demo
20
+// accounts, and MCP configs named `examples-<label>-<unix-seconds>`,
21
+// which is the name every example gives the configs it creates.
22
+// Configs from runs predating that convention are not matched.
23
+// Connected accounts are only ever deleted when they are bound to an
24
+// `examples-<slug>` auth config, which only this script creates. An
25
+// account the examples did not create is never touched, whatever user
26
+// owns it. Only resources older than 24h are removed, so a concurrent run
27
+// is safe. Preview with --dry-run.
28
+//
29
+// Auth config ids and connected account ids are not secrets; no credential
30
+// values are ever printed. The API-key demo value stored for serpapi is a
31
+// deliberately fake placeholder, not a real key.
32
+
33
+const BASE_URL = process.env.COMPOSIO_BASE_URL ?? 'https://backend.composio.dev';
34
+const API_KEY = process.env.COMPOSIO_API_KEY;
35
+const USER_ID = process.env.COMPOSIO_EXAMPLES_USER_ID ?? 'examples';
36
+const INITIATE_MISSING = process.argv.includes('--initiate-missing');
37
+const GC = process.argv.includes('--gc');
38
+const DRY_RUN = process.argv.includes('--dry-run');
39
+
40
+// The examples only ever run against the production backend with the
41
+// disposable project key. Allowlist the Composio hosts rather than denylisting
42
+// loopback spellings: the API key travels in every request, so anything that is
43
+// not a Composio backend must be refused, not just localhost.
44
+const { baseHost, baseProtocol } = (() => {
45
+ try {
46
+ const url = new URL(BASE_URL);
47
+ return { baseHost: url.hostname, baseProtocol: url.protocol };
48
+ } catch {
49
+ return { baseHost: null, baseProtocol: null };
50
+ }
51
+})();
52
+if (!baseHost || !(baseHost === 'composio.dev' || baseHost.endsWith('.composio.dev'))) {
53
+ console.error(`refusing non-Composio COMPOSIO_BASE_URL: ${BASE_URL}`);
54
+ process.exit(1);
55
+}
56
+if (baseProtocol !== 'https:') {
57
+ // The API key is sent on every request. Plain http would put it on the wire.
58
+ console.error(`refusing non-https COMPOSIO_BASE_URL: ${BASE_URL}`);
59
+ process.exit(1);
60
+}
61
+if (!API_KEY) {
62
+ console.error('COMPOSIO_API_KEY is required (dedicated examples-project key)');
63
+ process.exit(1);
64
+}
65
+
66
+// Toolkits the tier-2/3 entries depend on. OAuth toolkits need a one-time human
67
+// browser authorization. Only export ids that examples consume directly.
68
+const BROWSER_GRANT_TOOLKITS = [
69
+ { exportPrefix: 'GMAIL', slug: 'gmail' },
70
+ // googledrive exports nothing: examples reach Drive through the user's
71
+ // standing connection (COMPOSIO_EXAMPLES_USER_ID), never through ids.
72
+ { slug: 'googledrive' },
73
+ { exportPrefix: 'GITHUB', slug: 'github' },
74
+ { exportPrefix: 'SLACK', slug: 'slack' },
75
+];
76
+const DEMO_TOOLKIT = { exportPrefix: 'APIKEY', slug: 'serpapi', demoValue: 'examples-demo-key' };
77
+
78
+const report = line => console.error(line);
79
+
80
+async function api(method, path, body) {
81
+ const res = await fetch(`${BASE_URL}${path}`, {
82
+ method,
83
+ headers: { 'x-api-key': API_KEY, 'content-type': 'application/json' },
84
+ body: body === undefined ? undefined : JSON.stringify(body),
85
+ // Without this a hung backend hangs the whole run instead of failing it.
86
+ signal: AbortSignal.timeout(30_000),
87
+ // The host allowlist above only checks BASE_URL. fetch follows redirects by
88
+ // default and forwards x-api-key across origins (only Authorization is
89
+ // stripped), so a 3xx would hand the key to whatever host it names.
90
+ redirect: 'error',
91
+ });
92
+ const text = await res.text();
93
+ if (!res.ok) {
94
+ throw new Error(`${method} ${path} -> ${res.status}: ${text.slice(0, 300)}`);
95
+ }
96
+ return text ? JSON.parse(text) : undefined;
97
+}
98
+
99
+// Two pagination shapes are in play. Most v3.1 collections (auth_configs,
100
+// connected_accounts) return `next_cursor`; /mcp/servers never does and reports
101
+// current_page/total_pages instead. Follow whichever the response actually
102
+// offers, otherwise the MCP cleanup silently stops after one page.
103
+const MAX_PAGES = 50;
104
+
105
+async function listAll(path, key = 'items') {
106
+ const out = [];
107
+ let cursor;
108
+ let pageNo = 1;
109
+ for (let page = 0; page < MAX_PAGES; page++) {
110
+ const sep = path.includes('?') ? '&' : '?';
111
+ let query = 'limit=100';
112
+ if (cursor) query += `&cursor=${encodeURIComponent(cursor)}`;
113
+ else if (pageNo > 1) query += `&page_no=${pageNo}`;
114
+
115
+ const data = await api('GET', `${path}${sep}${query}`);
116
+ out.push(...(data?.[key] ?? []));
117
+
118
+ if (data?.next_cursor) {
119
+ if (data.next_cursor === cursor) {
120
+ report(`warning: ${path} repeated cursor ${cursor}; stopping to avoid a loop`);
121
+ return out;
122
+ }
123
+ cursor = data.next_cursor;
124
+ continue;
125
+ }
126
+
127
+ const totalPages = Number(data?.total_pages);
128
+ const currentPage = Number(data?.current_page ?? pageNo);
129
+ if (Number.isFinite(totalPages) && Number.isFinite(currentPage) && currentPage < totalPages) {
130
+ // Clear the cursor before falling back to page numbers. Leaving it set
131
+ // would resend the same cursor every iteration and repeat one page until
132
+ // the page cap.
133
+ cursor = undefined;
134
+ pageNo = currentPage + 1;
135
+ continue;
136
+ }
137
+ return out;
138
+ }
139
+ report(`warning: stopped paginating ${path} after ${MAX_PAGES} pages; results may be incomplete`);
140
+ return out;
141
+}
142
+
143
+const [authConfigs, accounts] = await Promise.all([
144
+ listAll('/api/v3.1/auth_configs'),
145
+ listAll(`/api/v3.1/connected_accounts?user_ids=${encodeURIComponent(USER_ID)}`),
146
+]);
147
+
148
+if (GC) {
149
+ const cutoff = Date.now() - 24 * 60 * 60 * 1000;
150
+ // Fail closed: a missing or unparseable created_at must not read as "old
151
+ // enough to delete", which `new Date(0)` would.
152
+ const stale = r => {
153
+ const created = new Date(r.created_at ?? '').getTime();
154
+ return Number.isFinite(created) && created < cutoff;
155
+ };
156
+ const gcDelete = async (kind, path, item) => {
157
+ const label = `${kind} ${item.id} (${item.toolkit?.slug ?? item.name}, created ${item.created_at})`;
158
+ if (DRY_RUN) {
159
+ report(`gc: would delete ${label}`);
160
+ return;
161
+ }
162
+ await api('DELETE', path);
163
+ report(`gc: deleted ${label}`);
164
+ };
165
+
166
+ // Ownership marker: this script is the only thing that creates auth configs
167
+ // named `examples-<slug>`, so an account bound to one of them was created by
168
+ // an example run. Match the name exactly. findAuthConfig's fallback to any
169
+ // config for the toolkit is fine for reading, but must never authorise a
170
+ // delete, or a project's own gmail config would look example-owned.
171
+ // Keying on the auth config rather than the user id matters: some examples
172
+ // connect as 'default' rather than COMPOSIO_EXAMPLES_USER_ID.
173
+ const ownedNames = new Set(
174
+ [...BROWSER_GRANT_TOOLKITS, DEMO_TOOLKIT].map(({ slug }) => `examples-${slug}`)
175
+ );
176
+ const ownedAuthConfigIds = new Set(
177
+ authConfigs.filter(c => ownedNames.has(c.name)).map(c => c.id)
178
+ );
179
+ const isExampleOwned = a => ownedAuthConfigIds.has(a.auth_config?.id);
180
+
181
+ if (ownedAuthConfigIds.size === 0) {
182
+ report('gc: no examples-* auth configs in this project; skipping account cleanup');
183
+ }
184
+
185
+ // Among example-created accounts only: ones that never became ACTIVE are dead
186
+ // weight from OAuth-initiating runs, and surplus serpapi demo accounts pile up
187
+ // from api-key runs. The newest standing account per toolkit is never touched.
188
+ const allAccounts = (await listAll('/api/v3.1/connected_accounts')).filter(isExampleOwned);
189
+ const serpapiActive = allAccounts
190
+ .filter(a => a.toolkit?.slug === 'serpapi' && a.status === 'ACTIVE')
191
+ .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
192
+ const doomedAccounts = [
193
+ ...allAccounts.filter(a => a.status !== 'ACTIVE' && stale(a)),
194
+ ...serpapiActive.slice(1).filter(stale),
195
+ ];
196
+ for (const account of doomedAccounts) {
197
+ await gcDelete('connected account', `/api/v3.1/connected_accounts/${account.id}`, account);
198
+ }
199
+
200
+ // Example runs name their MCP configs `examples-<label>-<unix-seconds>`.
201
+ // Both halves are load-bearing. The reserved `examples-` prefix is what proves
202
+ // an example created it, and the trailing timestamp keeps a hand-made
203
+ // `examples-scratch` out of the delete set. Matching a bare trailing digit run
204
+ // instead would also claim names like `release-1754923456`. Seconds, not
205
+ // milliseconds: the API caps MCP names at 30 characters.
206
+ const EXAMPLE_MCP_NAME = /^examples-[a-z0-9-]+-\d{10}$/;
207
+ const mcpServers = await listAll('/api/v3.1/mcp/servers');
208
+ for (const server of mcpServers.filter(s => EXAMPLE_MCP_NAME.test(s.name ?? '') && stale(s))) {
209
+ await gcDelete('mcp config', `/api/v3.1/mcp/${server.id}`, server);
210
+ }
211
+}
212
+
213
+const exports = { COMPOSIO_EXAMPLES_USER_ID: USER_ID };
214
+const pendingGrants = [];
215
+let ok = true;
216
+
217
+function findAuthConfig(slug) {
218
+ // Only the exactly-named config counts. Adopting a project's own config for
219
+ // the same toolkit would bind example-created accounts to a config --gc does
220
+ // not recognise, so they could never be cleaned up, and it would point the
221
+ // examples at credentials the examples do not own.
222
+ return authConfigs.find(
223
+ c => c.toolkit?.slug === slug && c.status !== 'DISABLED' && c.name === `examples-${slug}`
224
+ );
225
+}
226
+function findActiveAccount(slug, authConfigId) {
227
+ // Must agree with findAuthConfig. Accepting any ACTIVE account for the toolkit
228
+ // would pair a freshly created examples-<slug> config with an account bound to
229
+ // a different one, report the run complete, and leave the examples-owned
230
+ // config with no connection --initiate-missing would ever create.
231
+ return accounts.find(
232
+ a => a.toolkit?.slug === slug && a.status === 'ACTIVE' && a.auth_config?.id === authConfigId
233
+ );
234
+}
235
+
236
+for (const { exportPrefix, slug } of BROWSER_GRANT_TOOLKITS) {
237
+ let config = findAuthConfig(slug);
238
+ if (!config) {
239
+ const created = await api('POST', '/api/v3.1/auth_configs', {
240
+ toolkit: { slug },
241
+ auth_config: { type: 'use_composio_managed_auth', name: `examples-${slug}` },
242
+ });
243
+ config = { id: created.auth_config?.id ?? created.id };
244
+ report(`created auth config for ${slug}: ${config.id}`);
245
+ }
246
+ if (exportPrefix) {
247
+ exports[`COMPOSIO_EXAMPLES_${exportPrefix}_AUTH_CONFIG_ID`] = config.id;
248
+ }
249
+
250
+ const account = findActiveAccount(slug, config.id);
251
+ if (account) {
252
+ if (exportPrefix) {
253
+ exports[`COMPOSIO_EXAMPLES_${exportPrefix}_CONNECTED_ACCOUNT_ID`] = account.id;
254
+ }
255
+ report(`${slug}: ACTIVE connection ${account.id} (user ${USER_ID})`);
256
+ } else {
257
+ ok = false;
258
+ if (INITIATE_MISSING) {
259
+ const created = await api('POST', '/api/v3.1/connected_accounts', {
260
+ auth_config: { id: config.id },
261
+ connection: { user_id: USER_ID },
262
+ });
263
+ pendingGrants.push(
264
+ `${slug}: authorize in a browser -> ${created.connectionData?.val?.redirectUrl ?? created.redirect_url ?? created.redirect_uri ?? '(no redirect url returned)'}`
265
+ );
266
+ } else {
267
+ pendingGrants.push(
268
+ `${slug}: no ACTIVE connection for user ${USER_ID} — rerun with --initiate-missing to get an authorization URL`
269
+ );
270
+ }
271
+ }
272
+}
273
+
274
+// API-key toolkit: create the auth config automatically. The examples create
275
+// their own connected accounts to demonstrate that API. The stored value is a
276
+// placeholder; serpapi only validates it at tool-execution time and no example
277
+// executes a serpapi tool.
278
+{
279
+ const { exportPrefix, slug, demoValue } = DEMO_TOOLKIT;
280
+ let config = findAuthConfig(slug);
281
+ if (!config) {
282
+ const created = await api('POST', '/api/v3.1/auth_configs', {
283
+ toolkit: { slug },
284
+ auth_config: { type: 'use_custom_auth', authScheme: 'API_KEY', name: `examples-${slug}` },
285
+ });
286
+ config = { id: created.auth_config?.id ?? created.id };
287
+ report(`created API-key auth config for ${slug}: ${config.id}`);
288
+ }
289
+ exports[`COMPOSIO_EXAMPLES_${exportPrefix}_AUTH_CONFIG_ID`] = config.id;
290
+ exports[`COMPOSIO_EXAMPLES_${exportPrefix}_PLACEHOLDER`] = demoValue;
291
+}
292
+
293
+if (pendingGrants.length) {
294
+ report('');
295
+ report('OAuth connections still needing a one-time human authorization:');
296
+ for (const line of pendingGrants) report(` - ${line}`);
297
+}
298
+report('');
299
+report(ok ? 'provisioned state: complete' : 'provisioned state: INCOMPLETE (see above)');
300
+
301
+// stdout is meant to be eval'd, so every value is single-quoted: an id the
302
+// backend returned with a space or a shell metacharacter must not become code.
303
+const shellQuote = value => `'${String(value).replace(/'/g, `'\\''`)}'`;
304
+
305
+for (const [name, value] of Object.entries(exports)) {
306
+ if (value === undefined || value === null) {
307
+ ok = false;
308
+ report(`error: ${name} could not be resolved; not exporting it`);
309
+ continue;
310
+ }
311
+ console.log(`export ${name}=${shellQuote(value)}`);
312
+}
313
+
314
+process.exitCode = ok ? 0 : 1;