1
+import { AuthenticationError } from '@composio/client/effect';
2
+import * as BunFileSystem from '@effect/platform-bun/BunFileSystem';
3
+import * as BunPath from '@effect/platform-bun/BunPath';
4
import { describe, expect, it } from '@effect/vitest';
2
-import { ConfigProvider, Effect, Layer, Option } from 'effect';
3
-import { rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
5
+import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from 'effect';
6
+import * as tempy from 'tempy';
7
+import { rejectedUserApiKeyHint, unauthorizedHint } from 'src/effects/rejected-user-api-key';
8
+import { NodeOs } from 'src/services/node-os';
9
import { ComposioUserContext } from 'src/services/user-context';
10
11
const PRODUCTION = { base: 'https://backend.composio.dev', web: 'https://dashboard.composio.dev/' };
14
web: 'https://staging-dashboard.composio.dev/',
15
};
16
12
-/** The hint for a stored login whose resolved backend is `baseURL` with its Dashboard at `webURL`. */
13
-const hintFor = (baseURL: string, webURL: string, env: Record<string, string> = {}) =>
14
- rejectedUserApiKeyHint.pipe(
15
- Effect.provide(
16
- Layer.mergeAll(
17
- Layer.succeed(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env })),
18
- Layer.succeed(
19
- ComposioUserContext,
20
- ComposioUserContext.of({
21
- data: {
22
- apiKey: Option.some('uak_stored'),
23
- baseURL,
24
- webURL,
25
- orgId: Option.none(),
26
- projectId: Option.none(),
27
- testUserId: Option.none(),
28
- },
29
- backendMismatch: Option.none(),
30
- isLoggedIn: () => true,
31
- logout: Effect.void,
32
- login: () => Effect.void,
33
- update: () => Effect.void,
34
- })
35
- )
36
- )
17
+/** The services the hints read: `env`, and a user context with `apiKey` on `baseURL`/`webURL`. */
18
+const userContextLayer = (
19
+ baseURL: string,
20
+ webURL: string,
21
+ env: Record<string, string> = {},
22
+ apiKey: Option.Option<string> = Option.some('uak_stored')
23
+) =>
24
+ Layer.mergeAll(
25
+ Layer.succeed(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env })),
26
+ Layer.succeed(
27
+ ComposioUserContext,
28
+ ComposioUserContext.of({
29
+ data: {
30
+ apiKey,
31
+ baseURL,
32
+ webURL,
33
+ orgId: Option.none(),
34
+ projectId: Option.none(),
35
+ testUserId: Option.none(),
36
+ },
37
+ backendMismatch: Option.none(),
38
+ isLoggedIn: () => true,
39
+ logout: Effect.void,
40
+ login: () => Effect.void,
41
+ update: () => Effect.void,
42
+ })
43
+ )
44
+ );
45
+
46
+/**
47
+ * `userContextLayer` on `baseURL`/`webURL` plus a temporary home, where `~/.composio/agent.json`
48
+ * lives, read through the real filesystem.
49
+ */
50
+const agentHomeLayer = (baseURL: string, webURL: string) => {
51
+ const homedir = tempy.temporaryDirectory({ prefix: 'unauthorized-hint' });
52
+ return Layer.mergeAll(
53
+ userContextLayer(baseURL, webURL),
54
+ BunFileSystem.layer,
55
+ BunPath.layer,
56
+ Layer.succeed(
57
+ NodeOs,
58
+ NodeOs.of({ homedir, tmpdir: homedir, arch: 'arm64', platform: 'darwin' })
59
)
60
);
61
+};
62
+
63
+/** Saves an agent identity whose user API key is `userApiKey` in `~/.composio/agent.json`. */
64
+const saveAgentIdentity = (userApiKey: string) =>
65
+ Effect.gen(function* () {
66
+ const fs = yield* FileSystem.FileSystem;
67
+ const path = yield* Path.Path;
68
+ const os = yield* NodeOs;
69
+ const dir = path.join(os.homedir, '.composio');
70
+ yield* fs.makeDirectory(dir, { recursive: true });
71
+ yield* fs.writeFileString(
72
+ path.join(dir, 'agent.json'),
73
+ JSON.stringify({
74
+ composio_agent_key: 'ak_saved',
75
+ composio: { user_api_key: userApiKey, org_id: 'org_agent' },
76
+ }),
77
+ { mode: 0o600 }
78
+ );
79
+ });
80
+
81
+/** The hint for a stored login whose resolved backend is `baseURL` with its Dashboard at `webURL`. */
82
+const hintFor = (baseURL: string, webURL: string, env: Record<string, string> = {}) =>
83
+ rejectedUserApiKeyHint.pipe(Effect.provide(userContextLayer(baseURL, webURL, env)));
84
85
describe('rejectedUserApiKeyHint', () => {
86
it.effect.each([
139
})
140
);
141
});
142
+
143
+const unauthorized = (slug: string) =>
144
+ new AuthenticationError({
145
+ message: '401 Unauthorized',
146
+ method: 'GET',
147
+ url: 'https://backend.composio.dev/api/v3.1/auth/session/info',
148
+ status: 401,
149
+ requestId: undefined,
150
+ details: { message: 'Unauthorized', code: 401, slug, status: 401 },
151
+ body: undefined,
152
+ });
153
+
154
+describe('unauthorizedHint', () => {
155
+ it.effect('[Given] the backend rejected the user API key [Then] it says to log in again', () =>
156
+ Effect.gen(function* () {
157
+ const hint = yield* unauthorizedHint(unauthorized('UserApiKey_Unauthorized')).pipe(
158
+ Effect.provide(userContextLayer(PRODUCTION.base, PRODUCTION.web))
159
+ );
160
+ expect(hint).toEqual(
161
+ Option.some('Log in again, then retry:\n> composio logout && composio login')
162
+ );
163
+ })
164
+ );
165
+
166
+ it.effect.each<{
167
+ name: string;
168
+ env: Record<string, string>;
169
+ apiKey: Option.Option<string>;
170
+ hint: Option.Option<string>;
171
+ }>([
172
+ {
173
+ name: 'a stored login',
174
+ env: {},
175
+ apiKey: Option.some('uak_stored'),
176
+ hint: Option.some(
177
+ 'If your login expired, log in again, then retry:\n> composio logout && composio login'
178
+ ),
179
+ },
180
+ {
181
+ name: 'a key from COMPOSIO_USER_API_KEY',
182
+ env: { COMPOSIO_USER_API_KEY: 'uak_env' },
183
+ apiKey: Option.some('uak_env'),
184
+ hint: Option.some(
185
+ 'If the key in COMPOSIO_USER_API_KEY is no longer valid, replace it, then retry.'
186
+ ),
187
+ },
188
+ { name: 'no user API key', env: {}, apiKey: Option.none(), hint: Option.none() },
189
+ ])('[Given] another 401 and $name [Then] the login is only the likely cause', c =>
190
+ Effect.gen(function* () {
191
+ const hint = yield* unauthorizedHint(unauthorized('Auth_InvalidApiKey')).pipe(
192
+ Effect.provide(userContextLayer(PRODUCTION.base, PRODUCTION.web, c.env, c.apiKey))
193
+ );
194
+ expect(hint).toEqual(c.hint);
195
+ })
196
+ );
197
+});
198
+
199
+describe('[Given] the stored login is the saved agent identity', () => {
200
+ // `composio logout` would need --yes without a terminal and would delete the saved agent key.
201
+ it.effect('[Then] a rejected key names reuse-only agent login and the saved key file', () =>
202
+ Effect.gen(function* () {
203
+ yield* saveAgentIdentity('uak_stored');
204
+ expect(yield* rejectedUserApiKeyHint).toBe(
205
+ 'Log in again, then retry:\n> COMPOSIO_ENVIRONMENT=staging composio agent login <composio_agent_key>\nUse the composio_agent_key from ~/.composio/agent.json.'
206
+ );
207
+ }).pipe(Effect.provide(agentHomeLayer(STAGING.base, STAGING.web)))
208
+ );
209
+
210
+ it.effect('[Then] another 401 names reuse-only agent login and the saved key file', () =>
211
+ Effect.gen(function* () {
212
+ yield* saveAgentIdentity('uak_stored');
213
+ expect(yield* unauthorizedHint(unauthorized('Auth_InvalidApiKey'))).toEqual(
214
+ Option.some(
215
+ 'If your login expired, log in again, then retry:\n> composio agent login <composio_agent_key>\nUse the composio_agent_key from ~/.composio/agent.json.'
216
+ )
217
+ );
218
+ }).pipe(Effect.provide(agentHomeLayer(PRODUCTION.base, PRODUCTION.web)))
219
+ );
220
+
221
+ it.effect('[Given] the saved agent owns another key [Then] it names the regular login', () =>
222
+ Effect.gen(function* () {
223
+ yield* saveAgentIdentity('uak_other');
224
+ expect(yield* unauthorizedHint(unauthorized('Auth_InvalidApiKey'))).toEqual(
225
+ Option.some(
226
+ 'If your login expired, log in again, then retry:\n> composio logout && composio login'
227
+ )
228
+ );
229
+ }).pipe(Effect.provide(agentHomeLayer(PRODUCTION.base, PRODUCTION.web)))
230
+ );
231
+});