mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(composio): return the sign-in link when adding a second account (#19408)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A Composio gateway lets one person connect several accounts of the
same app, for example 3 Gmail accounts, through the Connectors "Add
account" action
> - `POST /api/tool-connections/{id}/composio/apps/{toolkit}/accounts`
with `{"action":"add"}` must return a hosted sign-in link for the new
account
> - When the app already has an active account, the call always fails
with "Composio did not return a sign-in link. Check the app in
Composio."
> - The add reply lists the app's existing accounts beside the new link.
The shared setup parser sees an active account, returns `connected`, and
drops the link
> - This pull request reads the new link directly for an add, after the
same provider-error check
> - The benefit is that people can add a second or third account to a
Composio app from Paperclip
## Linked Issues or Issue Description
**What happened?**
On a managed instance, a Composio gateway had Gmail and Google Calendar
connected for one Google account. "Add account" for a second account
returned HTTP 422 with "Composio did not return a sign-in link. Check
the app in Composio." The setup `start` action returns only
`{"status":"connected"}` for an app that has an account, so no Paperclip
path gave a link for another account.
**Expected behavior**
"Add account" returns a `connect.composio.dev/link/...` sign-in link for
a new account, also when the app already has an active account.
**Steps to reproduce**
1. Connect a Composio gateway and connect one Gmail account.
2. Call `POST /api/tool-connections/{id}/composio/apps/gmail/accounts`
with `{"action":"add"}`, or use "Add account" on the Connectors page.
3. The response is 422 "Composio did not return a sign-in link".
**Root cause**
`manageComposioAppAccount` used `composioAppSetupResult` for the add
reply. That function returns `{ status: "connected" }` as soon as any
entry for the toolkit has status `ACTIVE`, before it looks for a link.
The existing test fixture returned only `{ redirect_url }` for an add,
so it did not include the existing accounts that the live gateway
returns.
Related: #19380 (Connectors page CPU fix). That PR fixes the page that
holds the "Add account" button. This PR fixes the API call behind the
button.
## What Changed
- `server/src/services/composio-app-setup.ts`: add
`composioAddAccountLink(response)`. It runs the same provider-error
check as the other parsers, then returns the first trusted
`connect.composio.dev/link/` URL from the reply.
- `server/src/services/tool-access/catalog/aggregator-accounts.ts`: for
`action: "add"`, use `composioAddAccountLink` and return `{ status:
"authorization_required", authorizationUrl }`. Rename and remove do not
change.
- `server/src/__tests__/composio-add-account-link.test.ts`: new tests
for a reply with an active account plus a new link, a reply without a
trusted link, and a provider failure.
## Verification
- `cd server && npx vitest run
src/__tests__/composio-add-account-link.test.ts
src/__tests__/composio-app-setup.test.ts
src/__tests__/aggregator-app-discovery.test.ts`: all pass.
- Red before the fix: I changed the add reply in the `direct Composio
setup` fixture so it lists the toolkit's accounts beside the link, as
the live gateway does. On the unchanged service, "adds another account
without a task or an agent grant, even when an account is already
active" failed with `Error: Composio did not return a sign-in link.
Check the app in Composio.` With the fix, it passed. That fixture change
is not in this PR, to keep the diff small. The new unit test covers the
same reply shape.
- I did not get a live link from Composio with this change, because it
is not deployed. Before the fix, the live API call returned the 422
above.
- I could not run a full server `tsc` in my sandbox (out of memory). CI
runs it.
## Risks
- Low. Only the `add` action changes. It still rejects provider errors
first, and it accepts only trusted Composio hosted links
(`extractRemoteMcpPending`).
- An add reply that has no link still returns the same 422 as before.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use (shell, file editing, test execution).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Dotta <bippadotta@protonmail.com>
This commit is contained in:
1 parent
d99721398d
commit
68e92bcd5d
3 files changed
+337
-6
No files matched your search
@@ -0,0 +1,324 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
companies,
|
||||
companyMemberships,
|
||||
connectionGrants,
|
||||
createDb,
|
||||
issues,
|
||||
toolApplications,
|
||||
toolCatalogEntries,
|
||||
toolConnections,
|
||||
} from "@paperclipai/db";
|
||||
import { toolAccessRoutes } from "../routes/tool-access.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
import { composioAddAccountLink, composioAppSetupResult } from "../services/composio-app-setup.js";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import { aggregatorAppTelemetrySlug } from "../services/connector-telemetry.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const track = vi.fn();
|
||||
vi.mock("../telemetry.js", () => ({
|
||||
getTelemetryClient: () => ({
|
||||
track,
|
||||
isRegisteredEventName: () => true,
|
||||
hashPrivateRef: (value: string) => value,
|
||||
trackDynamic: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
const appRequestedEvents = () => track.mock.calls.filter(([name]) => name === "connection.app_requested");
|
||||
|
||||
describe("Composio add-account link", () => {
|
||||
const response = {
|
||||
result: {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: JSON.stringify({
|
||||
data: {
|
||||
results: {
|
||||
gmail: {
|
||||
toolkit: "gmail",
|
||||
status: "active",
|
||||
accounts: [{ id: "ca_1", status: "active" }],
|
||||
redirect_url: "https://connect.composio.dev/link/next",
|
||||
},
|
||||
},
|
||||
},
|
||||
error: null,
|
||||
successful: true,
|
||||
}),
|
||||
}],
|
||||
isError: false,
|
||||
},
|
||||
};
|
||||
|
||||
it("returns the new account's link even when the toolkit already has an active account", () => {
|
||||
expect(composioAppSetupResult(response, "gmail")).toEqual({ status: "connected" });
|
||||
expect(composioAddAccountLink(response)).toBe("https://connect.composio.dev/link/next");
|
||||
});
|
||||
|
||||
it("returns no link without a trusted hosted link and rejects provider failures", () => {
|
||||
expect(composioAddAccountLink({ results: { gmail: { status: "active" } } })).toBeNull();
|
||||
expect(composioAddAccountLink({ results: { gmail: { redirect_url: "https://untrusted.example/link/next" } } })).toBeNull();
|
||||
expect(() => composioAddAccountLink({ isError: true })).toThrow("could not configure");
|
||||
});
|
||||
});
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
(support.supported ? describe : describe.skip)("POST /api/tool-connections/:connectionId/composio/apps/:toolkit/accounts (add)", () => {
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let cleanup: (() => Promise<void>) | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
const database = await startEmbeddedPostgresTestDatabase("paperclip-composio-add-account-");
|
||||
db = createDb(database.connectionString);
|
||||
cleanup = database.cleanup;
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await cleanup?.();
|
||||
});
|
||||
|
||||
async function setupComposioRouteFixture(respond: (requestId: string, toolkits: { name: string; action: string }[]) => Response) {
|
||||
const [company] = await db.insert(companies).values({
|
||||
name: "Composio add-account test",
|
||||
issuePrefix: randomUUID().slice(0, 6).toUpperCase(),
|
||||
}).returning();
|
||||
const userId = randomUUID();
|
||||
await db.insert(companyMemberships).values({
|
||||
companyId: company.id,
|
||||
principalType: "user",
|
||||
principalId: userId,
|
||||
membershipRole: "admin",
|
||||
status: "active",
|
||||
});
|
||||
const [agent] = await db.insert(agents).values({
|
||||
companyId: company.id,
|
||||
name: "Default agent",
|
||||
role: "general",
|
||||
status: "idle",
|
||||
adapterType: "codex_local",
|
||||
}).returning();
|
||||
const [application] = await db.insert(toolApplications).values({
|
||||
companyId: company.id,
|
||||
applicationKey: randomUUID(),
|
||||
name: "Composio",
|
||||
type: "mcp_http",
|
||||
metadata: { sourceTemplateKey: "composio" },
|
||||
}).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({
|
||||
companyId: company.id,
|
||||
applicationId: application.id,
|
||||
uid: randomUUID(),
|
||||
name: "Composio account",
|
||||
transport: "mcp_remote",
|
||||
authKind: "none",
|
||||
credentialPolicy: "shared",
|
||||
status: "active",
|
||||
enabled: true,
|
||||
config: { sourceTemplateKey: "composio", url: "https://connect.composio.dev/mcp" },
|
||||
}).returning();
|
||||
await db.insert(connectionGrants).values({
|
||||
companyId: company.id,
|
||||
connectionId: connection.id,
|
||||
kind: "organization",
|
||||
isDefault: true,
|
||||
status: "active",
|
||||
});
|
||||
await db.insert(toolCatalogEntries).values({
|
||||
companyId: company.id,
|
||||
connectionId: connection.id,
|
||||
name: "COMPOSIO_MANAGE_CONNECTIONS",
|
||||
toolName: "COMPOSIO_MANAGE_CONNECTIONS",
|
||||
versionHash: "v1",
|
||||
status: "active",
|
||||
riskLevel: "destructive",
|
||||
});
|
||||
|
||||
const operations: { name: string; action: string }[] = [];
|
||||
const remoteHttpRequest: NonNullable<Parameters<typeof toolAccessService>[1]>["remoteHttpRequest"] = async (_url, init) => {
|
||||
const rpc = JSON.parse(String(init.body));
|
||||
expect(rpc.params.name).toBe("COMPOSIO_MANAGE_CONNECTIONS");
|
||||
const toolkits = rpc.params.arguments.toolkits as { name: string; action: string }[];
|
||||
operations.push(...toolkits);
|
||||
return respond(rpc.id, toolkits);
|
||||
};
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = {
|
||||
type: "board",
|
||||
userId,
|
||||
source: "session",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [company.id],
|
||||
};
|
||||
next();
|
||||
});
|
||||
app.use("/api", toolAccessRoutes(db, { remoteHttpRequest }));
|
||||
app.use(errorHandler);
|
||||
|
||||
return {
|
||||
company,
|
||||
agent,
|
||||
connection,
|
||||
operations,
|
||||
app,
|
||||
access: toolAccessService(db, { remoteHttpRequest }),
|
||||
};
|
||||
}
|
||||
|
||||
it("returns the new sign-in link when Gmail already has an active account", async () => {
|
||||
const f = await setupComposioRouteFixture((id) =>
|
||||
Response.json({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: JSON.stringify({
|
||||
data: {
|
||||
results: {
|
||||
gmail: {
|
||||
toolkit: "gmail",
|
||||
status: "active",
|
||||
accounts: [{ id: "ca_1", alias: "Work", status: "active", is_default: true }],
|
||||
redirect_url: "https://connect.composio.dev/link/next",
|
||||
},
|
||||
},
|
||||
},
|
||||
error: null,
|
||||
successful: true,
|
||||
}),
|
||||
}],
|
||||
isError: false,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
track.mockClear();
|
||||
const response = await request(f.app)
|
||||
.post(`/api/tool-connections/${f.connection.id}/composio/apps/gmail/accounts`)
|
||||
.send({ action: "add" });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({
|
||||
status: "authorization_required",
|
||||
authorizationUrl: "https://connect.composio.dev/link/next",
|
||||
apps: [],
|
||||
});
|
||||
expect(f.operations).toEqual([{ name: "gmail", action: "add" }]);
|
||||
expect(appRequestedEvents()).toEqual([
|
||||
["connection.app_requested", {
|
||||
provider: "composio",
|
||||
app: aggregatorAppTelemetrySlug("composio", "gmail"),
|
||||
origin: "user",
|
||||
outcome: "needs_auth",
|
||||
}],
|
||||
]);
|
||||
expect(await db.select().from(issues).where(eq(issues.companyId, f.company.id))).toHaveLength(0);
|
||||
expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns 422 and failed telemetry when Composio returns no trusted link or reports a provider error", async () => {
|
||||
const missingLink = await setupComposioRouteFixture((id) =>
|
||||
Response.json({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
structuredContent: {
|
||||
data: {
|
||||
results: {
|
||||
gmail: {
|
||||
toolkit: "gmail",
|
||||
status: "active",
|
||||
accounts: [{ id: "ca_1", status: "ACTIVE" }],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
track.mockClear();
|
||||
const missingResponse = await request(missingLink.app)
|
||||
.post(`/api/tool-connections/${missingLink.connection.id}/composio/apps/gmail/accounts`)
|
||||
.send({ action: "add" });
|
||||
expect(missingResponse.status).toBe(422);
|
||||
expect(missingResponse.body.error).toContain("did not return a sign-in link");
|
||||
expect(appRequestedEvents()).toEqual([
|
||||
["connection.app_requested", {
|
||||
provider: "composio",
|
||||
app: aggregatorAppTelemetrySlug("composio", "gmail"),
|
||||
origin: "user",
|
||||
outcome: "failed",
|
||||
}],
|
||||
]);
|
||||
|
||||
const untrustedLink = await setupComposioRouteFixture((id) =>
|
||||
Response.json({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
structuredContent: {
|
||||
data: {
|
||||
results: {
|
||||
gmail: {
|
||||
toolkit: "gmail",
|
||||
redirect_url: "https://untrusted.example/link/next",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
track.mockClear();
|
||||
const untrustedResponse = await request(untrustedLink.app)
|
||||
.post(`/api/tool-connections/${untrustedLink.connection.id}/composio/apps/gmail/accounts`)
|
||||
.send({ action: "add" });
|
||||
expect(untrustedResponse.status).toBe(422);
|
||||
expect(untrustedResponse.body.error).toContain("did not return a sign-in link");
|
||||
expect(appRequestedEvents()).toEqual([
|
||||
["connection.app_requested", {
|
||||
provider: "composio",
|
||||
app: aggregatorAppTelemetrySlug("composio", "gmail"),
|
||||
origin: "user",
|
||||
outcome: "failed",
|
||||
}],
|
||||
]);
|
||||
|
||||
const providerError = await setupComposioRouteFixture((id) =>
|
||||
Response.json({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
isError: true,
|
||||
content: [{ type: "text", text: "error" }],
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
track.mockClear();
|
||||
const errorResponse = await request(providerError.app)
|
||||
.post(`/api/tool-connections/${providerError.connection.id}/composio/apps/gmail/accounts`)
|
||||
.send({ action: "add" });
|
||||
expect(errorResponse.status).toBe(422);
|
||||
expect(errorResponse.body.error).toContain("could not configure");
|
||||
expect(appRequestedEvents()).toEqual([
|
||||
["connection.app_requested", {
|
||||
provider: "composio",
|
||||
app: aggregatorAppTelemetrySlug("composio", "gmail"),
|
||||
origin: "user",
|
||||
outcome: "failed",
|
||||
}],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -57,6 +57,11 @@ export function composioAppAccounts(response: unknown, toolkit: string): Composi
|
||||
return observed && !incomplete ? [...accounts.values()] : undefined;
|
||||
}
|
||||
|
||||
export function composioAddAccountLink(response: unknown): string | null {
|
||||
payloadsFrom(response);
|
||||
return extractRemoteMcpPending(response, "composio", "COMPOSIO_MANAGE_CONNECTIONS")?.links[0]?.url ?? null;
|
||||
}
|
||||
|
||||
/** Only the requested toolkit can establish success; other accounts are unrelated. */
|
||||
export function composioAppSetupResult(response: unknown, toolkit: string): ComposioAppSetupResult {
|
||||
const payloads = payloadsFrom(response);
|
||||
|
||||
@@ -7,7 +7,7 @@ import { resolveAggregatorApp, type AppCatalogAggregator } from "@paperclipai/sh
|
||||
import { AggregatorDiscoveryUnavailableError, discoverArcadeApps, discoverExecutorApps, type DiscoveredApp } from "../../aggregator-app-discovery.js";
|
||||
import { COMPOSIO_APP_TOOLKITS, findComposioCatalogApp } from "@paperclipai/shared/aggregator-app-catalog";
|
||||
import type { ComposioAppAccount, ComposioAppAccountInput, ComposioAppSetupInput, ComposioAppSetupResult, ComposioAppSnapshot, ComposioAppsResponse } from "@paperclipai/shared";
|
||||
import { composioAppAccounts, composioAppSetupResult } from "../../composio-app-setup.js";
|
||||
import { composioAddAccountLink, composioAppAccounts, composioAppSetupResult } from "../../composio-app-setup.js";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { and, asc, desc, eq, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
@@ -535,15 +535,17 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred
|
||||
}
|
||||
let result: ReturnType<typeof composioAppSetupResult>;
|
||||
try {
|
||||
result = composioAppSetupResult(payload, toolkit); // Reject provider errors before reporting success.
|
||||
if (input.action === "add") {
|
||||
const authorizationUrl = composioAddAccountLink(payload);
|
||||
if (!authorizationUrl) throw unprocessable("Composio did not return a sign-in link. Check the app in Composio.");
|
||||
result = { status: "authorization_required", authorizationUrl };
|
||||
} else {
|
||||
result = composioAppSetupResult(payload, toolkit); // Reject provider errors before reporting success.
|
||||
}
|
||||
} catch (error) {
|
||||
requested("failed");
|
||||
throw error;
|
||||
}
|
||||
if (input.action === "add" && !result.authorizationUrl) {
|
||||
requested("failed");
|
||||
throw unprocessable("Composio did not return a sign-in link. Check the app in Composio.");
|
||||
}
|
||||
requested("needs_auth");
|
||||
if (input.action !== "add") {
|
||||
const after = composioAppAccounts(await manage([{ name: toolkit, action: "list" }]), toolkit);
|
||||
|
||||
Reference in new issue
Block a user