Keep every connector account a second sign-in adds
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s

This commit is contained in:
2026-11-22 09:32:54 +01:00
parent fdaa5649ef
commit f8a7b0f2e7
9 changed files with 114 additions and 49 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.27.0",
"version": "0.27.1",
"module": "index.ts",
"type": "module",
"private": true,
@@ -40,10 +40,11 @@ export default async function createConnectorRequest({
label,
}: Params): Promise<ConnectorRequest> {
const now = Date.now();
const name = label || connector.name;
const open = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_REQUESTS>({
sql: `SELECT * FROM connector_requests WHERE connector_id = ? AND user_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id DESC LIMIT 1`,
values: [connector.id, user_id, now],
sql: `SELECT * FROM connector_requests WHERE connector_id = ? AND user_id = ? AND label = ? AND status = 'pending' AND expires_at > ? ORDER BY id DESC LIMIT 1`,
values: [connector.id, user_id, name, now],
})
).payload?.[0];
@@ -53,7 +54,7 @@ export default async function createConnectorRequest({
const started = await provider.startConnect({
app: connector.app,
user_id,
label: label || connector.name,
label: name,
auth_config_id: connector.auth_config_id,
});
@@ -84,7 +85,7 @@ export default async function createConnectorRequest({
user_id,
bot_id: bot_id ?? undefined,
bot_session_id: session_id ?? undefined,
label: label || connector.name,
label: name,
url: started.url,
provider_account_id: started.provider_account_id || undefined,
status: "pending",
@@ -40,15 +40,23 @@ export default async function grabConnectorRequestView({ request_id, user_id }:
});
}
const request_account = String(row.provider_account_id || "");
// Only the account this request made counts: any connected one would
// close a second sign-in with the first account's label, which is how a
// second Gmail account looked already connected.
const accountRows = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' ORDER BY id ASC`,
values: [connector.id, Number(user_id)],
sql: request_account
? `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' AND provider_account_id = ? LIMIT 1`
: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status = 'connected' AND created_at >= ? ORDER BY id ASC LIMIT 1`,
values: request_account
? [connector.id, Number(user_id), request_account]
: [connector.id, Number(user_id), Number(row.created_at || 0)],
})
).payload || [];
const matching =
accountRows.find((account) => account.provider_account_id == row.provider_account_id) || accountRows[0] || null;
const matching = accountRows[0] || null;
if (status == "pending" && matching) {
status = "connected";
@@ -18,18 +18,18 @@ type Params = {
type Result = {
/**
* Null when the user already has a connected account: there is nothing
* to sign in to.
* The sign-in link. Always made: a person can keep several accounts on
* one app (a work Gmail beside a personal one), so an account already
* connected never stands in for the new one.
*/
request: ConnectorRequestPayload | null;
accounts: ConnectorAccountRecord[];
};
/**
* Starts (or finds) a sign-in for one connector, after reading what the
* provider already has: a user who connected it before gets no second link.
* The request outlives the page that made it, so the card under a reply and
* Settings > Connectors both read it the same way.
* Starts a sign-in for one connector. The request outlives the page that
* made it, so the card under a reply and Settings > Connectors both read it
* the same way.
*/
export default async function startConnectorConnection({
user_id,
@@ -43,9 +43,6 @@ export default async function startConnectorConnection({
if (!connector.enabled) throw new AppError(`${connector.name} is turned off, so it can't be connected right now.`);
const accounts = await syncConnectorAccounts({ user_id, connector_id: connector.id, label });
const connected = accounts.filter((account) => account.status == "connected");
if (connected.length) return { request: null, accounts };
const request = await createConnectorRequest({
user_id: Number(user_id),
@@ -72,8 +72,17 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
await BunSQLite.sql({ sql: `UPDATE connector_accounts SET is_default = 1 WHERE id = ?`, values: [firstConnected] });
}
if (accounts.some((account) => account.status == "connected")) {
await settleRequests({ connector_id: connector.id, user_id: Number(user_id) });
const connected_ids = accounts
.filter((account) => account.status == "connected")
.map((account) => account.provider_account_id)
.filter(Boolean);
if (connected_ids.length) {
await settleRequests({
connector_id: connector.id,
user_id: Number(user_id),
provider_account_ids: connected_ids,
});
}
return grabUserAccounts({ connector_id: connector.id, user_id: Number(user_id) });
@@ -151,20 +160,35 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label }:
type SettleParams = {
connector_id: number;
user_id: number;
provider_account_ids: string[];
};
/**
* A connect request is done the moment an account is connected: the card
* under the reply says so instead of offering the link again.
* A connect request is done only when the account it made is connected: a
* second sign-in must not be closed by the first account that was already
* there (`provider_account_id` is what the provider returned for this link).
* A request the provider gave no id for falls back to an account created
* after the request.
*/
async function settleRequests({ connector_id, user_id }: SettleParams) {
async function settleRequests({ connector_id, user_id, provider_account_ids }: SettleParams) {
const now = Date.now();
const placeholders = provider_account_ids.map(() => "?").join(", ");
await BunSQLite.sql({
sql: `UPDATE connector_requests SET status = 'connected', updated_at = ?
WHERE connector_id = ? AND user_id = ? AND status = 'pending'
AND expires_at > ?`,
values: [now, connector_id, user_id, now],
AND expires_at > ?
AND (
(provider_account_id != '' AND provider_account_id IN (${placeholders}))
OR (provider_account_id == '' AND EXISTS (
SELECT 1 FROM connector_accounts a
WHERE a.connector_id = connector_requests.connector_id
AND a.user_id = connector_requests.user_id
AND a.status = 'connected'
AND a.created_at >= connector_requests.created_at
))
)`,
values: [now, connector_id, user_id, now, ...provider_account_ids],
});
}
@@ -132,16 +132,14 @@ describe("composioConnectorProvider", () => {
test("starts a sign-in with the app's sign-in setup and keeps what the provider returns", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url, method }) =>
url.pathname.endsWith("/auth_configs") && method == "GET"
? { body: { items: [{ id: "ac_1", auth_scheme: "OAUTH2" }] } }
: {
body: {
redirect_url: "https://connect/x",
connected_account_id: "ca_9",
expires_at: "2027-01-01T00:00:00Z",
},
},
answer: ({ url, method }) => {
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
if (url.pathname.endsWith("/tool_router/session/trs_1/link")) {
return { status: 201, body: { redirect_url: "https://connect/x", connected_account_id: "ca_9", expires_at: "2027-01-01T00:00:00Z" } };
}
return method == "GET" ? { body: { items: [{ id: "ac_1", auth_scheme: "OAUTH2" }] } } : { body: {} };
},
});
const started = await composioConnectorProvider({ key: "k", fetchImpl }).startConnect({
@@ -155,20 +153,24 @@ describe("composioConnectorProvider", () => {
expect(started.provider_account_id).toBe("ca_9");
expect(started.expires_at).toBe(Date.parse("2027-01-01T00:00:00Z"));
const link = calls.find((call) => call.url.pathname.endsWith("/connected_accounts/link"))!;
const session = calls.find((call) => call.url.pathname.endsWith("/tool_router/session"))!;
expect(link.body.toolkit_slug).toBe("gmail");
expect(session.body.multi_account).toEqual({ enable: true, max_accounts_per_toolkit: 5 });
const link = calls.find((call) => call.url.pathname.endsWith("/tool_router/session/trs_1/link"))!;
expect(link.body.toolkit).toBe("gmail");
expect(link.body.auth_config_id).toBe("ac_1");
expect(link.body.account_label).toBe("Work");
expect(link.body.callback_url).toBeUndefined();
expect(calls.some((call) => call.url.pathname.endsWith("/connected_accounts/link"))).toBe(false);
});
test("makes a managed sign-in setup when the app has none", async () => {
const { fetchImpl, calls } = stub({
answer: ({ url, method }) => {
if (!url.pathname.endsWith("/auth_configs")) {
return { body: { redirect_url: "https://connect/y" } };
}
if (url.pathname.endsWith("/tool_router/session")) return { status: 201, body: { session_id: "trs_1" } };
if (url.pathname.endsWith("/link")) return { status: 201, body: { redirect_url: "https://connect/y" } };
if (!url.pathname.endsWith("/auth_configs")) return { body: {} };
return method == "POST" ? { status: 201, body: { auth_config: { id: "ac_new" } } } : { body: { items: [] } };
},
+25 -6
View File
@@ -23,6 +23,8 @@ type Params = {
const DefaultBaseUrl = "https://backend.composio.dev/api/v3.1";
const PageLimit = 100;
/** Composio keeps one account per app unless a session allows more; 5 is its own ceiling in the docs. */
const MaxAccountsPerToolkit = 5;
const MaxPages = 20;
const Statuses: Record<string, ProviderAccountStatus> = {
@@ -230,19 +232,36 @@ export default function composioConnectorProvider({ key, base_url, fetchImpl }:
} satisfies ConnectorEndpoint;
},
async startConnect({ app, user_id, label, auth_config_id, callback_url }: StartConnectParams) {
async startConnect({ app, user_id, auth_config_id, callback_url }: StartConnectParams) {
const config = await authConfigFor({ app, auth_config_id });
// A plain connected-accounts link replaces the app's account for
// that user, so a second sign-in would take the first one away.
// A multi-account session keeps both, which is what a connection
// named "Work" beside one named "Personal" needs.
const session = await request<any>({
path: "/tool_router/session",
method: "POST",
what: `a sign-in session for ${app}`,
body: {
user_id: `cobble-user-${user_id}`,
toolkits: { enable: [app] },
multi_account: { enable: true, max_accounts_per_toolkit: MaxAccountsPerToolkit },
},
});
const session_id = session.session_id || session.id;
if (!session_id) throw new AppError(`Composio didn't open a sign-in session for ${app}.`);
const answer = await request<any>({
path: "/connected_accounts/link",
path: `/tool_router/session/${session_id}/link`,
method: "POST",
what: `a sign-in link for ${app}`,
body: {
toolkit_slug: app,
user_id: `cobble-user-${user_id}`,
toolkit: app,
auth_config_id: config,
callback_url,
...(label ? { account_label: label } : {}),
...(callback_url ? { callback_url } : {}),
},
});
@@ -39,7 +39,21 @@ export default function ConnectorConnectModal({ connector, onConnected, onCancel
title={`New ${connector.name} connection`}
description="The sign-in happens at the provider, and it keeps the credentials. Your bots only ever reach the account it makes."
>
<Form className="w-full flex-col gap-4! items-stretch" submitHandler={() => { setError(""); connect.start({ connector_id: connector.id, label }); }}>
<Form
className="w-full flex-col gap-4! items-stretch"
submitHandler={() => {
const name = label.trim();
if (!name) {
setError("Name this connection, so you can tell it apart from another account of the same app.");
return;
}
setError("");
connect.start({ connector_id: connector.id, label: name });
}}
>
<Input
id={`connector-${connector.id}-new-label`}
title="Account name"