Refuse a connector account the provider no longer has, and stop adopting duplicates
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 10:56:35 +01:00
parent 7c92d0b4be
commit 5ea9b608be
10 changed files with 157 additions and 25 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.3",
"version": "0.27.4",
"module": "index.ts",
"type": "module",
"private": true,
+11 -3
View File
@@ -6,7 +6,10 @@ import syncConnectorConnection from "@/src/functions/backend/db/connectors/sync-
/**
* Keeps every connection's app list current, reads the tools of the apps
* someone actually gave to a bot or workspace (never all of them: a
* provider lists hundreds), and checks the accounts a sign-in left waiting.
* provider lists hundreds), and keeps accounts in line with the provider:
* the ones a sign-in left waiting, and connected ones an hour later, so an
* account deleted at the provider shows as revoked (and offers Reconnect)
* without waiting for a run to fail.
* Each connection is synced with its own key, so a refused one only affects
* the apps it read.
*/
@@ -37,13 +40,18 @@ export default async function syncConnectors() {
await syncConnector({ connector_id: connector.id });
}
const now = Date.now();
const stale_after = now - 60 * 60 * 1000;
const waiting =
(
await BunSQLite.sql<{ connector_id: number; user_id: number }>({
sql: `SELECT connector_id, user_id FROM connector_requests WHERE status = 'pending' AND expires_at > ?
UNION
SELECT connector_id, user_id FROM connector_accounts WHERE status != 'connected'`,
values: [Date.now()],
SELECT connector_id, user_id FROM connector_accounts WHERE status != 'connected'
UNION
SELECT connector_id, user_id FROM connector_accounts
WHERE status = 'connected' AND (last_checked_at IS NULL OR last_checked_at < ?)`,
values: [now, stale_after],
})
).payload || [];
@@ -2,21 +2,42 @@ import { describe, expect, test } from "bun:test";
import shouldAdoptConnectorAccount from "@/src/functions/backend/db/connectors/should-adopt-connector-account";
describe("shouldAdoptConnectorAccount", () => {
test("adopts a connected account whether or not a request claims it", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false })).toBe(true);
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true })).toBe(true);
test("adopts a connected account into the app's free card", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false, free_slot: true })).toBe(
true,
);
});
test("leaves a second connected account at the provider once the card is taken", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: false, free_slot: false })).toBe(
false,
);
});
test("adopts a connected account a request here started, even with no free card", () => {
expect(shouldAdoptConnectorAccount({ status: "connected", reconnect: false, claimed: true, free_slot: false })).toBe(
true,
);
});
test("adopts a pending account a request here started", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true })).toBe(true);
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: true, free_slot: false })).toBe(
true,
);
});
test("adopts a pending account that reconnects a row", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false })).toBe(true);
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: true, claimed: false, free_slot: false })).toBe(
true,
);
});
test("skips a pending account nothing here started", () => {
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: false })).toBe(false);
expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false })).toBe(false);
expect(shouldAdoptConnectorAccount({ status: "pending", reconnect: false, claimed: false, free_slot: true })).toBe(
false,
);
expect(shouldAdoptConnectorAccount({ status: "expired", reconnect: false, claimed: false, free_slot: true })).toBe(
false,
);
});
});
@@ -6,15 +6,23 @@ type Params = {
reconnect: boolean;
/** A pending request here started this sign-in. */
claimed: boolean;
/**
* Whether the app has no live account here yet: one card per app is
* filled by the provider's account, and any other account arrives through
* its own sign-in (claimed).
*/
free_slot: boolean;
};
/**
* Whether a provider account becomes a local row. A connected one always does.
* A pending one does only when a request here started it or reconnects it: an
* abandoned sign-in at the provider must not arrive as a second account, which
* is how a reconnect once left a never connected duplicate beside the account
* it replaced.
* Whether a provider account becomes a local row. One a request here started
* (or is reconnecting) always does. A connected one the app doesn't know
* gets the app's one free card, so leftovers from earlier sign-ins at the
* provider can't pile up as four rows of the same mailbox; a second account
* appears by signing in again, which claims its own row.
*/
export default function shouldAdoptConnectorAccount({ status, reconnect, claimed }: Params) {
return reconnect || status == "connected" || claimed;
export default function shouldAdoptConnectorAccount({ status, reconnect, claimed, free_slot }: Params) {
if (reconnect || claimed) return true;
return status == "connected" && free_slot;
}
@@ -23,7 +23,12 @@ type Params = {
* local rows in line: new sign-ins are added (the first connected one is the
* default), ones the provider reports expired say so, and ones it no longer
* lists are marked revoked without losing their label. Pending connect
* requests are closed as soon as an account is connected.
* requests are closed as soon as the account they made is connected.
*
* One card per app unless the user signed in again: an account the provider
* holds but no request here made fills the app's free card once and is left
* at the provider after that, so a pile of earlier sign-ins cannot arrive as
* four rows of the same mailbox.
*/
export default async function syncConnectorAccounts({ user_id, connector_id, label }: Params) {
const connector = await grabConnector({ connector_id });
@@ -57,7 +62,12 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
const seen = new Set(accounts.map((account) => account.provider_account_id));
const now = Date.now();
const hasConnected = local.some((row) => row.status == "connected");
/**
* The app's one free card: a live row still listed by the provider holds
* it. An account arriving without a sign-in here (an older attempt at
* the provider) may fill it once, never pile up beside it.
*/
let free_slot = !local.some((row) => row.status == "connected" && seen.has(String(row.provider_account_id || "")));
for (const row of local) {
if (seen.has(String(row.provider_account_id || ""))) continue;
@@ -68,7 +78,7 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
});
}
let firstConnected: number | null = hasConnected ? null : 0;
let firstConnected: number | null = free_slot ? 0 : null;
for (const account of accounts) {
const provider_account_id = String(account.provider_account_id);
@@ -79,6 +89,7 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
status: account.status,
reconnect: Boolean(reconnect_id),
claimed: claimed.has(provider_account_id),
free_slot,
})
)
continue;
@@ -93,6 +104,8 @@ export default async function syncConnectorAccounts({ user_id, connector_id, lab
if (account.status != "connected") continue;
if (free_slot) free_slot = false;
if (firstConnected === 0) {
const created = (
await BunSQLite.sql<{ id: number }>({
@@ -190,9 +203,11 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r
* A reconnect the provider gave no id for still lands on the row it
* replaces: one dead row with this account's name is that row, and a
* second one with the same name would be the duplicate this prevents.
* When the provider's name differs from the label the user chose, the one
* dead row for this app is still the row a new sign-in takes over.
*/
const name = account.label || fallback_label || "";
const dead = name
const named_dead = name
? ((
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') AND lower(label) = lower(?) ORDER BY id ASC`,
@@ -200,6 +215,14 @@ async function upsertAccount({ connector_id, user_id, account, fallback_label, r
})
).payload || [])
: [];
const dead = named_dead.length
? named_dead
: ((
await BunSQLite.sql<BUN_SQLITE_COBBLE_CONNECTOR_ACCOUNTS>({
sql: `SELECT * FROM connector_accounts WHERE connector_id = ? AND user_id = ? AND status IN ('revoked', 'expired') ORDER BY id ASC`,
values: [connector_id, user_id],
})
).payload || []);
if (dead.length == 1) {
const row = dead[0]!;
@@ -0,0 +1,14 @@
import { expect, test } from "bun:test";
import connectorAccountGoneMessage from "./connector-account-gone";
test("names the account, the provider and where to reconnect", () => {
const message = connectorAccountGoneMessage({
connector_name: "Gmail",
label: "Benoti Sanchez Gmail",
provider_title: "Composio",
});
expect(message).toContain('The Gmail account "Benoti Sanchez Gmail"');
expect(message).toContain("no longer exists at Composio");
expect(message).toContain("Settings > Connectors");
});
@@ -0,0 +1,16 @@
type Params = {
connector_name: string;
label: string;
provider_title: string;
};
/**
* A row can outlive the account it names: a sign-in is deleted at the
* provider (a second one replaced it, a connection was cleared there) while
* the local row still says connected. Pinning that id would make the provider
* fall back to whatever account it does have, so the run would answer from a
* mailbox nobody chose. The tool refuses instead, naming the fix.
*/
export default function connectorAccountGoneMessage({ connector_name, label, provider_title }: Params) {
return `The ${connector_name} account "${label}" no longer exists at ${provider_title}, so this didn't run. Reconnect it in Settings > Connectors.`;
}
@@ -1,8 +1,11 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CONNECTOR_SESSIONS } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { ConnectorProviders } from "@/src/dict/connector-dict";
import AppError from "@/src/utils/app-error";
import { decrypt, encrypt } from "@/src/utils/crypt";
import type { ConnectorAccountRecord, ConnectorRecord } from "@/src/types";
import connectorAccountGoneMessage from "./connector-account-gone";
import type { ConnectorProvider } from "./connector-provider";
/**
@@ -45,6 +48,43 @@ async function readCachedHeaders({ headers }: { headers: string | null }): Promi
}
}
/**
* A row can name an account the provider no longer has (a second sign-in
* replaced it, a connection was cleared there). A session pinned to that id
* is not refused: the provider answers from whichever account it does have,
* so a bot read a mailbox the user never chose. The row is marked revoked
* (its card then offers Reconnect) and the call stops instead.
*/
async function assertAccountStillThere({ connector, provider, user_id, account, now }: Params & { now: number }) {
let accounts: Awaited<ReturnType<ConnectorProvider["accounts"]>>;
try {
accounts = await provider.accounts({ app: connector.app, user_id });
} catch {
// The provider is the one to say why the session failed; a list that
// can't be read is not proof the account is gone.
return;
}
if (accounts.some((entry) => entry.provider_account_id == account.provider_account_id)) return;
await BunSQLite.sql({
sql: `UPDATE connector_accounts SET status = 'revoked', last_checked_at = ?, updated_at = ? WHERE id = ?`,
values: [now, now, Number(account.id)],
});
const provider_title =
ConnectorProviders.find((entry) => entry.value == connector.provider)?.title || connector.provider;
throw new AppError(
connectorAccountGoneMessage({
connector_name: connector.name,
label: account.label,
provider_title,
}),
);
}
export default async function ensureConnectorEndpoint({
connector,
provider,
@@ -73,6 +113,8 @@ export default async function ensureConnectorEndpoint({
}
}
await assertAccountStillThere({ connector, provider, user_id, account, now });
const tools = connector.tools
.map((tool) => tool.name)
.filter((name) => !connector.excluded_tools.includes(name));
@@ -37,7 +37,7 @@ export default function ConnectorConnectModal({ connector, onConnected, onCancel
}}
icon={<ConnectorLogo logo={connector.logo} name={connector.name} />}
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."
description="The sign-in happens at the provider, and it keeps the credentials. Sign in with the account you want your bots to act as: the name here is only a label for it."
>
<Form
className="w-full flex-col gap-4! items-stretch"
@@ -63,7 +63,7 @@ export default function ConnectorConnectModal({ connector, onConnected, onCancel
value={label}
autoComplete="off"
onChange={(e) => setLabel(e.target.value)}
info="What you'll call it, so you can tell two accounts of the same app apart."
info="What you'll call it, so you can tell two accounts of the same app apart. It doesn't choose the account: the one you sign in with at the provider is the one your bots use."
/>
{connect.sign_in ? (