Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Connected-apps service: erase an installation's data (#5278)
Milind Soni6d949807882c
diff --git a/cloudflare/composio-broker/README.md b/cloudflare/composio-broker/README.mdindex 1c73701880..ed1b3a5811 100644--- a/cloudflare/composio-broker/README.md+++ b/cloudflare/composio-broker/README.md@@ -49,6 +49,7 @@ Composio --signed POST--> /v1/composio/webhook --> D1 queue per installation <--| `PUT /v1/installation/cloud` `{grant}` | installation token | Marks the installation as a paid Cloud's from an Admin-signed grant. || `POST /v1/installation/share` `{for}` | installation token | A one-time code (10 minutes, only its hash kept) that lets the installation `for` act as this installation's Composio user. || `POST /v1/installation/adopt` `{code}` | installation token | Redeems a code minted for this installation: from then on it acts as that Composio user (`shared_user_id`). Refused with 409 `has_connections` while it has active connected accounts of its own, which stay reachable. The code is spent either way. |+| `DELETE /v1/installation` | installation token | Erases the installation and what it created at Composio. See [Erasing an installation](#erasing-an-installation-and-what-the-broker-keeps). || `GET /v1/stats/app-events?days=<1-90>` | `Bearer STATS_TOKEN` | Fleet totals per day (queued, delivered, duplicates, drops, expired, unrouted) and current counts. Counts only, never event contents or installation ids. || cron `23 * * * *` | | Expires events not collected within 7 days, disables at Composio the triggers of installations that have not polled for 14 days (re-enabled on their next poll), keeps daily counts for 90 days. |@@ -165,3 +166,42 @@ changes nothing.(step 1) before the code that uses it reaches `main`, because CI deploysevery push to `main`. Without it, the hourly sweep of idle installationsfails after it has expired old events.++## Erasing an installation and what the broker keeps++`DELETE /v1/installation`, with the installation's own token:++| Answer | Means |+| --- | --- |+| `200 {erased: true, sharedUserKept}` | Everything is gone and the token no longer works. |+| `202 {erased: false, more: true}` | Call again. One call makes at most 30 Composio deletes, to stay inside a Worker's per-request limits. |+| `401` | Bad token, or already erased. |+| `429`, `502`, `503` | Nothing is lost: the token still works, so call again. Finished work is not redone. |++It removes share codes the installation minted or was named in, then at+Composio its triggers and connected accounts (`revoke_on_delete=true`), then in+one D1 transaction its rows in `trigger_bindings`, `events`, `event_drops`,+`app_event_days`, `user_shares` and last `installations`. It needs migrations+through `0004`; before that it answers 503 and changes nothing.++A trigger another installation also binds stays at Composio. A Composio user+another live installation still acts as (a desktop and its Cloud) keeps its+connected accounts and unbound triggers: `sharedUserKept` is `true`, and they go+when the last installation using that user is erased. An installation that+adopted a shared user also clears its own original Composio user.++Kept without an erase:++| Data | Kept |+| --- | --- |+| `installations` | Indefinitely: only an erase removes a row. |+| `events` | Unread: 7 days. Read: body cleared at once, the id kept for 7 days to spot duplicates. |+| `trigger_bindings`, `event_drops` | Until the trigger is deleted. |+| `app_event_days` | 90 days. Counts only. |+| `user_shares` | Until used; an expired code, until the next code is minted. Hash only. |+| Composio connected accounts and triggers | Until disconnected or deleted. A trigger is only paused after 14 days without a poll. |++An erase does not reach Composio's tool router Sessions (the broker has no call+that deletes one), the `''` row of `app_event_days` (deliveries no installation+owned), Worker logs (which carry installation ids), or a copy of the token on+the customer's side.diff --git a/cloudflare/composio-broker/src/app-events.ts b/cloudflare/composio-broker/src/app-events.tsindex bc237a94d4..83c079ac3b 100644--- a/cloudflare/composio-broker/src/app-events.ts+++ b/cloudflare/composio-broker/src/app-events.ts@@ -61,7 +61,7 @@ function text(value: unknown): string | undefined {return typeof value === "string" && value.length > 0 && value.length <= 200 ? value : undefined;}-function base64Bytes(value: string, url: boolean) {+export function base64Bytes(value: string, url: boolean) {const pattern = url ? /^[A-Za-z0-9_-]+$/ : /^[A-Za-z0-9+/]+={0,2}$/;if (!pattern.test(value)) return null;const standard = url ? value.replaceAll("-", "+").replaceAll("_", "/") : value;@@ -72,7 +72,7 @@ function base64Bytes(value: string, url: boolean) {}}-async function hmacKey(secret: string, usage: "sign" | "verify" = "verify") {+export async function hmacKey(secret: string, usage: "sign" | "verify" = "verify") {return crypto.subtle.importKey("raw", utf8(secret), { name: "HMAC", hash: "SHA-256" }, false, [usage]);}diff --git a/cloudflare/composio-broker/src/common.ts b/cloudflare/composio-broker/src/common.tsindex 13d45e7775..dd9bcf9bc2 100644--- a/cloudflare/composio-broker/src/common.ts+++ b/cloudflare/composio-broker/src/common.ts@@ -144,6 +144,7 @@ export function composioRequest(env: Env, path: string, init?: RequestInit) {const connectedAccountResponseSchema = z.object({id: z.string().optional(),+ user_id: z.string().nullable().optional(),alias: z.string().nullable().optional(),status: z.string().optional(),updated_at: z.string().optional(),diff --git a/cloudflare/composio-broker/src/erase.test.ts b/cloudflare/composio-broker/src/erase.test.tsnew file mode 100644index 0000000000..1e8507ac41--- /dev/null+++ b/cloudflare/composio-broker/src/erase.test.ts@@ -0,0 +1,339 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { brokerHarness, message, type Installation } from "./test-harness";++let h: ReturnType<typeof brokerHarness>;++afterEach(() => vi.unstubAllGlobals());++function harness(migrations?: number) {+ h = brokerHarness(migrations === undefined ? {} : { migrations });+ vi.stubGlobal("fetch", h.composio.fetchImpl);+ return h;+}++const TABLES = {+ installations: "id",+ trigger_bindings: "installation_id",+ events: "installation_id",+ event_drops: "installation_id",+ app_event_days: "installation_id",+};++const erase = (owner: Installation) => h.call(owner, "/v1/installation", { method: "DELETE" });+const post = (owner: Installation, path: string, body: unknown) => h.call(owner, path, { method: "POST", body: JSON.stringify(body) });+const alive = async (owner: Installation) => (await h.call(owner, "/v1/me")).status === 200;++function rowCounts(installationId: string) {+ const counts: Record<string, number> = {};+ for (const [table, column] of Object.entries(TABLES)) {+ counts[table] = h.d1.rows(`SELECT 1 FROM ${table} WHERE ${column} = ?`, installationId).length;+ }+ counts.user_shares = h.d1.rows("SELECT 1 FROM user_shares WHERE from_installation = ?1 OR for_installation = ?1", installationId).length;+ return counts;+}++const NOTHING = { installations: 0, trigger_bindings: 0, events: 0, event_drops: 0, app_event_days: 0, user_shares: 0 };++/** One row in every table, an acked event and a share code in each direction, the way the routes leave them. */+async function populated(partner: Installation) {+ const owner = await h.install();+ const account = h.account(owner, "gmail");+ const { body: trigger } = await h.createTrigger(owner, account);+ expect((await h.deliver(message(trigger.triggerId, owner.userId))).status).toBe(200);+ const { events } = await (await h.poll(owner)).json() as { events: Array<{ seq: number }> };+ await h.poll(owner, `after=${events[0]!.seq}`);+ expect((await h.deliver(message(trigger.triggerId, owner.userId))).status).toBe(200);+ h.d1.db.prepare("INSERT INTO event_drops (installation_id, composio_trigger_id, reason, dropped, last_dropped_at) VALUES (?, ?, 'queue_full', 1, 1)").run(owner.id, trigger.triggerId);+ expect((await post(owner, "/v1/installation/share", { for: partner.id })).status).toBe(201);+ expect((await post(partner, "/v1/installation/share", { for: owner.id })).status).toBe(201);+ return { owner, account, triggerId: trigger.triggerId };+}++async function shared() {+ const desktop = await h.install(), cloud = await h.install();+ const gmail = h.account(desktop, "gmail");+ const { code } = await (await post(desktop, "/v1/installation/share", { for: cloud.id })).json() as { code: string };+ expect((await post(cloud, "/v1/installation/adopt", { code })).status).toBe(200);+ return { desktop, cloud, gmail };+}++describe("DELETE /v1/installation", () => {+ it("erases every table's rows and what the installation created at Composio, then the token is dead", async () => {+ harness();+ const partner = await h.install();+ const { owner, account, triggerId } = await populated(partner);+ const before = rowCounts(owner.id);+ expect(before.installations).toBe(1);+ expect(before.trigger_bindings).toBe(1);+ expect(before.events).toBe(2);+ expect(before.event_drops).toBe(1);+ expect(before.app_event_days).toBe(1);+ expect(before.user_shares).toBe(2);+ const orphan = h.composio.accounts.find((candidate) => candidate.id === account)!;+ expect(orphan.user_id).toBe(owner.userId);++ const erased = await erase(owner);+ expect(erased.status).toBe(200);+ await expect(erased.json()).resolves.toEqual({ erased: true, sharedUserKept: false });++ expect(rowCounts(owner.id)).toEqual(NOTHING);+ expect(h.composio.instances.has(triggerId)).toBe(false);+ expect(h.composio.accounts).toEqual([]);+ const accountDelete = h.composio.calls.find((call) => call.method === "DELETE" && call.path === `/connected_accounts/${account}`);+ expect(accountDelete?.query.get("revoke_on_delete")).toBe("true");++ expect(await alive(owner)).toBe(false);+ expect((await erase(owner)).status).toBe(401);+ });++ it("deletes triggers before the connected accounts they read from", async () => {+ harness();+ const owner = await h.install();+ const account = h.account(owner);+ await h.createTrigger(owner, account);+ await erase(owner);+ const order = h.composio.calls.filter((call) => call.method === "DELETE").map((call) => call.path.split("/")[1]);+ expect(order).toEqual(["trigger_instances", "connected_accounts"]);+ });++ it("removes an instance of its Composio user that no installation binds", async () => {+ harness();+ const owner = await h.install();+ const account = h.account(owner);+ const { body: trigger } = await h.createTrigger(owner, account);+ h.d1.db.prepare("DELETE FROM trigger_bindings WHERE composio_trigger_id = ?").run(trigger.triggerId);+ expect((await erase(owner)).status).toBe(200);+ expect(h.composio.instances.size).toBe(0);+ });++ it("leaves another installation's rows, accounts, triggers and codes alone", async () => {+ harness();+ const partner = await h.install();+ const { owner } = await populated(partner);+ const other = await populated(partner);+ const untouched = rowCounts(other.owner.id);+ const shares = h.d1.rows("SELECT code_hash FROM user_shares WHERE from_installation = ?", other.owner.id);++ expect((await erase(owner)).status).toBe(200);++ expect(rowCounts(other.owner.id)).toEqual(untouched);+ expect(h.d1.rows("SELECT code_hash FROM user_shares WHERE from_installation = ?", other.owner.id)).toEqual(shares);+ expect(h.composio.accounts.map((account) => account.id)).toEqual([other.account]);+ expect([...h.composio.instances.keys()]).toEqual([other.triggerId]);+ expect(await alive(other.owner)).toBe(true);+ expect(await alive(partner)).toBe(true);+ });++ it("refuses a missing, malformed or unknown token and erases nothing", async () => {+ harness();+ const owner = await h.install();+ const account = h.account(owner);+ expect((await h.fetch("/v1/installation", { method: "DELETE" })).status).toBe(401);+ expect((await h.fetch("/v1/installation", { method: "DELETE", headers: { authorization: "Bearer nope" } })).status).toBe(401);+ expect((await erase({ ...owner, token: "f".repeat(64) })).status).toBe(401);+ expect(rowCounts(owner.id).installations).toBe(1);+ expect(h.composio.accounts.map((candidate) => candidate.id)).toEqual([account]);+ expect(h.composio.calls.filter((call) => call.method === "DELETE")).toEqual([]);+ });++ it("answers 429 when rate limited, before touching anything", async () => {+ harness();+ const owner = await h.install();+ const account = h.account(owner);+ h.env.SESSION_LIMITER.limit = async () => ({ success: false });+ expect((await erase(owner)).status).toBe(429);+ expect(h.composio.accounts.map((candidate) => candidate.id)).toEqual([account]);+ expect(rowCounts(owner.id).installations).toBe(1);+ });+});++describe("a Composio user another installation also uses", () => {+ it("keeps the connected accounts when the desktop erases first, then removes them with the last installation", async () => {+ harness();+ const { desktop, cloud, gmail } = await shared();+ const { body: sharedTrigger } = await h.createTrigger(desktop, gmail, { query: "both" });+ expect((await h.createTrigger(cloud, gmail, { query: "both" })).body.triggerId).toBe(sharedTrigger.triggerId);+ const { body: desktopOnly } = await h.createTrigger(desktop, gmail, { query: "desktop only" });+ const { body: cloudOnly } = await h.createTrigger(cloud, gmail, { query: "cloud only" });++ const erased = await erase(desktop);+ expect(erased.status).toBe(200);+ await expect(erased.json()).resolves.toEqual({ erased: true, sharedUserKept: true });++ expect(rowCounts(desktop.id)).toEqual(NOTHING);+ expect(h.composio.calls.some((call) => call.method === "DELETE" && call.path.startsWith("/connected_accounts/"))).toBe(false);+ expect(h.composio.accounts.map((account) => account.id)).toEqual([gmail]);+ expect(h.composio.instances.has(sharedTrigger.triggerId)).toBe(true);+ expect(h.composio.instances.has(cloudOnly.triggerId)).toBe(true);+ expect(h.composio.instances.has(desktopOnly.triggerId)).toBe(false);+ const status = await (await h.call(cloud, "/v1/connectors?services=gmail")).json() as { services: Record<string, { connected: boolean }> };+ expect(status.services.gmail?.connected).toBe(true);+ expect(await alive(cloud)).toBe(true);++ const last = await erase(cloud);+ await expect(last.json()).resolves.toEqual({ erased: true, sharedUserKept: false });+ expect(h.composio.accounts).toEqual([]);+ expect(h.composio.instances.size).toBe(0);+ expect(h.d1.rows("SELECT * FROM installations")).toEqual([]);+ });++ it("keeps the shared user when the Cloud erases first, and removes the Cloud's own leftover accounts", async () => {+ harness();+ const { desktop, cloud, gmail } = await shared();+ const leftover = h.account(cloud, "notion", "INITIATED");++ const erased = await erase(cloud);+ await expect(erased.json()).resolves.toEqual({ erased: true, sharedUserKept: true });++ expect(h.composio.accounts.map((account) => account.id)).toEqual([gmail]);+ expect(h.composio.calls.some((call) => call.method === "DELETE" && call.path === `/connected_accounts/${leftover}`)).toBe(true);+ expect(await alive(desktop)).toBe(true);+ });++ it("treats a disabled installation as no longer using the user", async () => {+ harness();+ const { desktop, cloud } = await shared();+ h.d1.db.prepare("UPDATE installations SET disabled_at = 1 WHERE id = ?").run(cloud.id);+ await expect((await erase(desktop)).json()).resolves.toEqual({ erased: true, sharedUserKept: false });+ expect(h.composio.accounts).toEqual([]);+ });++ it("spends a code still out, so nobody adopts a user being erased", async () => {+ harness();+ const desktop = await h.install(), cloud = await h.install();+ h.account(desktop, "gmail");+ const { code } = await (await post(desktop, "/v1/installation/share", { for: cloud.id })).json() as { code: string };+ expect((await erase(desktop)).status).toBe(200);+ expect((await post(cloud, "/v1/installation/adopt", { code })).status).toBe(404);+ expect(h.composio.accounts).toEqual([]);+ });++ it("does not delete an account Composio lists under another user", async () => {+ harness();+ const owner = await h.install(), stranger = await h.install();+ const theirs = h.account(stranger, "gmail");+ const listing = h.composio.fetchImpl;+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(String(input));+ if (url.pathname.endsWith("/connected_accounts") && (init?.method ?? "GET") === "GET") {+ return Response.json({ items: [{ id: theirs, user_id: stranger.userId, status: "ACTIVE", toolkit: { slug: "gmail" } }], next_cursor: null });+ }+ return listing(input, init);+ });+ expect((await erase(owner)).status).toBe(200);+ expect(h.composio.accounts.map((account) => account.id)).toEqual([theirs]);+ });++ it("does not delete an account or trigger Composio lists without saying whose it is", async () => {+ harness();+ const owner = await h.install(), stranger = await h.install();+ const theirs = h.account(stranger, "gmail");+ const trigger = "ti_unattributed";+ const listing = h.composio.fetchImpl;+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(String(input));+ if ((init?.method ?? "GET") === "GET" && url.pathname.endsWith("/connected_accounts")) {+ return Response.json({ items: [{ id: theirs, status: "ACTIVE", toolkit: { slug: "gmail" } }], next_cursor: null });+ }+ if ((init?.method ?? "GET") === "GET" && url.pathname.endsWith("/trigger_instances/active")) {+ return Response.json({ items: [{ id: trigger, trigger_name: "GMAIL_NEW_GMAIL_MESSAGE" }], next_cursor: null });+ }+ return listing(input, init);+ });+ expect((await erase(owner)).status).toBe(200);+ expect(h.composio.accounts.map((account) => account.id)).toEqual([theirs]);+ expect(h.composio.calls.filter((call) => call.method === "DELETE")).toEqual([]);+ });+});++describe("a Composio failure can be retried", () => {+ const DELETE_TRIGGER = (call: { method: string; path: string }) => call.method === "DELETE" && call.path.startsWith("/trigger_instances/manage/");+ const DELETE_ACCOUNT = (call: { method: string; path: string }) => call.method === "DELETE" && call.path.startsWith("/connected_accounts/");+ const LIST_ACCOUNTS = (call: { method: string; path: string }) => call.method === "GET" && call.path === "/connected_accounts";++ for (const [name, status, match, expected] of [+ ["deleting a trigger", 500, DELETE_TRIGGER, 502],+ ["deleting a connected account", 500, DELETE_ACCOUNT, 502],+ ["listing connected accounts", 500, LIST_ACCOUNTS, 503],+ ] as const) {+ it(`keeps the token and answers an error when ${name} fails, and the retry finishes`, async () => {+ harness();+ const partner = await h.install();+ const { owner, triggerId } = await populated(partner);+ h.composio.fail(status, match);++ const failed = await erase(owner);+ expect(failed.status).toBe(expected);+ await expect(failed.json()).resolves.toHaveProperty("error");+ expect(await alive(owner)).toBe(true);+ expect(rowCounts(owner.id).installations).toBe(1);+ expect(rowCounts(owner.id).events).toBe(2);++ expect((await erase(owner)).status).toBe(200);+ expect(rowCounts(owner.id)).toEqual(NOTHING);+ expect(h.composio.instances.has(triggerId)).toBe(false);+ expect(h.composio.accounts).toEqual([]);+ expect(await alive(owner)).toBe(false);+ });+ }++ it("keeps the token when Composio cannot be reached at all", async () => {+ harness();+ const owner = await h.install();+ h.account(owner);+ vi.stubGlobal("fetch", async () => { throw new Error("connection reset"); });+ expect((await erase(owner)).status).toBe(503);+ expect(await alive(owner)).toBe(true);+ vi.stubGlobal("fetch", h.composio.fetchImpl);+ expect((await erase(owner)).status).toBe(200);+ expect(await alive(owner)).toBe(false);+ });++ it("treats what Composio already removed as done", async () => {+ harness();+ const owner = await h.install();+ const account = h.account(owner);+ const { body: trigger } = await h.createTrigger(owner, account);+ h.composio.instances.delete(trigger.triggerId);+ expect((await erase(owner)).status).toBe(200);+ expect(await alive(owner)).toBe(false);+ expect(h.composio.accounts).toEqual([]);+ });++ it("finishes a large erase over several calls, the token working until the last", async () => {+ harness();+ const owner = await h.install();+ for (let index = 0; index < 35; index += 1) {+ const account = h.account(owner, `toolkit${index}`);+ const instance = `ti_many_${index}`;+ h.composio.instances.set(instance, { id: instance, trigger_name: "GMAIL_EMAIL_SENT", connected_account_id: account, user_id: owner.userId, trigger_config: {}, disabled_at: null });+ h.d1.db.prepare("INSERT INTO trigger_bindings (installation_id, composio_trigger_id, toolkit, trigger_slug, connected_account_id, created_at) VALUES (?, ?, 'gmail', 'GMAIL_EMAIL_SENT', ?, 1)").run(owner.id, instance, account);+ }+ let calls = 0;+ let response: Response;+ do {+ calls += 1;+ expect(await alive(owner)).toBe(true);+ const before = h.composio.calls.filter((call) => call.method === "DELETE").length;+ response = await erase(owner);+ expect(h.composio.calls.filter((call) => call.method === "DELETE").length - before).toBeLessThanOrEqual(30);+ if (response.status === 202) await expect(response.json()).resolves.toEqual({ erased: false, more: true });+ } while (response.status === 202 && calls < 10);+ expect(response.status).toBe(200);+ expect(calls).toBeGreaterThan(1);+ expect(rowCounts(owner.id)).toEqual(NOTHING);+ expect(h.composio.accounts).toEqual([]);+ expect(h.composio.instances.size).toBe(0);+ });++ it("answers an error and changes nothing on a database that has not run migration 0004", async () => {+ harness(3);+ const owner = await h.install();+ const account = h.account(owner);+ expect((await erase(owner)).status).toBe(503);+ expect(await alive(owner)).toBe(true);+ expect(h.composio.accounts.map((candidate) => candidate.id)).toEqual([account]);+ expect(h.composio.calls.filter((call) => call.method === "DELETE")).toEqual([]);+ });+});diff --git a/cloudflare/composio-broker/src/erase.ts b/cloudflare/composio-broker/src/erase.tsnew file mode 100644index 0000000000..91f2793bcf--- /dev/null+++ b/cloudflare/composio-broker/src/erase.ts@@ -0,0 +1,103 @@+// Erases one installation: what it holds in D1, and what it created at Composio. Composio goes first and the+// installation row last, so a failed Composio call leaves the token working for a retry.+import {+ ACCOUNT_ID,+ actingUser,+ composioRequest,+ json,+ listConnectedAccounts,+ upstreamError,+ type InstallationRow,+} from "./common";+import { deleteRemote, listRemoteInstances, otherBindings } from "./triggers";++/** Workers on the free plan get 50 subrequests and 50 D1 queries per request: a larger erase is finished by further calls. */+const DELETES_PER_CALL = 30;+/** The users among `users` no other live installation acts as. Only their connected accounts may be deleted: a desktop+ * and its Cloud that share a Composio user lose each other's apps otherwise. */+async function usersNoOneElseActsAs(env: Env, installationId: string, users: string[]) {+ const { results } = await env.DB.prepare(+ `SELECT DISTINCT COALESCE(shared_user_id, composio_user_id) AS user FROM installations+ WHERE id != ?1 AND disabled_at IS NULL AND COALESCE(shared_user_id, composio_user_id) IN (?2, ?3)`,+ ).bind(installationId, users[0], users[users.length - 1]).all<{ user: string }>();+ const inUse = new Set(results.map((row) => row.user));+ return users.filter((user) => !inUse.has(user));+}++async function removeBoundTriggers(env: Env, installationId: string) {+ const { results } = await env.DB.prepare(+ `SELECT b.composio_trigger_id AS id, EXISTS (+ SELECT 1 FROM trigger_bindings o WHERE o.composio_trigger_id = b.composio_trigger_id AND o.installation_id != b.installation_id+ ) AS shared+ FROM trigger_bindings b WHERE b.installation_id = ? ORDER BY b.composio_trigger_id LIMIT ?`,+ ).bind(installationId, DELETES_PER_CALL).all<{ id: string; shared: number }>();+ const removed: string[] = [];+ let failure: string | undefined;+ for (const { id, shared } of results) {+ const result = shared ? "done" : await deleteRemote(env, id);+ if (typeof result === "object") {+ failure = result.error;+ break;+ }+ removed.push(id);+ }+ if (removed.length) {+ await env.DB.prepare(`DELETE FROM trigger_bindings WHERE installation_id = ?1 AND composio_trigger_id IN (${removed.map((_, index) => `?${index + 2}`).join(", ")})`)+ .bind(installationId, ...removed).run();+ }+ return { failure, more: results.length === DELETES_PER_CALL, deletes: results.filter((row) => !row.shared).length };+}++/** "done", "more" when this call's allowance ran out, or the 502 to answer with. */+async function eraseAtComposio(env: Env, installationId: string, users: string[]): Promise<"done" | "more" | Response> {+ const bound = await removeBoundTriggers(env, installationId);+ if (bound.failure) return json({ error: bound.failure }, 502);+ if (bound.more) return "more";+ let deletes = bound.deletes;+ for (const user of users) {+ for (const instance of await listRemoteInstances(env, user)) {+ if (instance.user_id !== user) continue;+ if (deletes >= DELETES_PER_CALL) return "more";+ if (await otherBindings(env, installationId, instance.id, false) > 0) continue;+ const result = await deleteRemote(env, instance.id);+ if (typeof result === "object") return json({ error: result.error }, 502);+ deletes += 1;+ }+ for (const account of await listConnectedAccounts(env, user, [])) {+ if (!account.id || !ACCOUNT_ID.test(account.id) || account.user_id !== user) continue;+ if (deletes >= DELETES_PER_CALL) return "more";+ const response = await composioRequest(env, `/connected_accounts/${encodeURIComponent(account.id)}?revoke_on_delete=true`, { method: "DELETE" });+ if (!response.ok && response.status !== 404) {+ return json({ error: await upstreamError(response, `Composio could not delete a connected account (${response.status})`) }, 502);+ }+ await response.body?.cancel();+ deletes += 1;+ }+ }+ return "done";+}++/** 200 once nothing is left and the token is dead; 202 to call again; an error leaves the token working. */+export async function eraseInstallation(installation: InstallationRow, env: Env) {+ const { id } = installation;+ // Before the check below: a code still out could hand a user being erased to another installation.+ await env.DB.prepare("DELETE FROM user_shares WHERE from_installation = ?1 OR for_installation = ?1").bind(id).run();+ const users = [...new Set([actingUser(installation), installation.composio_user_id])];+ const erasable = await usersNoOneElseActsAs(env, id, users);+ if (erasable.length) {+ await env.DB.prepare("DELETE FROM user_shares WHERE composio_user_id IN (?1, ?2)").bind(erasable[0], erasable[erasable.length - 1]).run();+ }+ const outcome = await eraseAtComposio(env, id, erasable);+ if (outcome === "more") return json({ erased: false, more: true }, 202);+ if (outcome !== "done") return outcome;+ await env.DB.batch([+ env.DB.prepare("DELETE FROM trigger_bindings WHERE installation_id = ?").bind(id),+ env.DB.prepare("DELETE FROM events WHERE installation_id = ?").bind(id),+ env.DB.prepare("DELETE FROM event_drops WHERE installation_id = ?").bind(id),+ env.DB.prepare("DELETE FROM app_event_days WHERE installation_id = ?").bind(id),+ env.DB.prepare("DELETE FROM user_shares WHERE from_installation = ?1 OR for_installation = ?1").bind(id),+ env.DB.prepare("DELETE FROM installations WHERE id = ?").bind(id),+ ]);+ console.log(JSON.stringify({ message: "installation erased", installationId: id }));+ return json({ erased: true, sharedUserKept: erasable.length < users.length });+}diff --git a/cloudflare/composio-broker/src/index.ts b/cloudflare/composio-broker/src/index.tsindex db55e03eb6..1a0db80704 100644--- a/cloudflare/composio-broker/src/index.ts+++ b/cloudflare/composio-broker/src/index.ts@@ -17,6 +17,7 @@ import {eventInstallation,type InstallationRow,} from "./common";+import { eraseInstallation } from "./erase";import { adoptSharedUser, me, shareUser } from "./sharing";import { createTrigger, deleteTrigger, getTriggerType, listTriggers, listTriggerTypes, updateTrigger } from "./triggers";@@ -721,6 +722,10 @@ async function route(request: Request, env: Env, ctx: ExecutionContext) {const appEvents = await appEventRoute(request, url, installation, env, ctx);if (appEvents) return appEvents;if (request.method === "GET" && url.pathname === "/v1/me") return me(installation);+ if (request.method === "DELETE" && url.pathname === "/v1/installation") {+ await limitSessionRequests(installation, env);+ return eraseInstallation(installation, env);+ }if (request.method === "POST" && url.pathname === "/v1/installation/share") return shareUser(request, installation, env);if (request.method === "POST" && url.pathname === "/v1/installation/adopt") {const adopted = await adoptSharedUser(request, installation, env);diff --git a/cloudflare/composio-broker/src/test-harness.ts b/cloudflare/composio-broker/src/test-harness.tsindex 4efedde098..d119c45fc1 100644--- a/cloudflare/composio-broker/src/test-harness.ts+++ b/cloudflare/composio-broker/src/test-harness.ts@@ -131,6 +131,13 @@ export function fakeComposio() {const slugs = url.searchParams.get("toolkit_slugs")?.split(",");return reply({ items: accounts.filter((account) => account.user_id === user && (!slugs || slugs.includes(account.toolkit.slug))), next_cursor: null });}+ const accountId = path.match(/^\/connected_accounts\/([^/]+)$/)?.[1];+ if (method === "DELETE" && accountId) {+ const index = accounts.findIndex((account) => account.id === decodeURIComponent(accountId));+ if (index < 0) return reply({ error: { message: "Connected account not found" } }, 404);+ accounts.splice(index, 1);+ return reply({ status: "success" });+ }if (method === "GET" && path === "/auth_configs") return reply({ items: [], next_cursor: null });const sessionPayload = (session: FakeSession) => ({session_id: session.id,diff --git a/cloudflare/composio-broker/src/triggers.ts b/cloudflare/composio-broker/src/triggers.tsindex c69df273d9..9d9d12da54 100644--- a/cloudflare/composio-broker/src/triggers.ts+++ b/cloudflare/composio-broker/src/triggers.ts@@ -219,7 +219,7 @@ export async function setRemoteEnabled(env: Env, triggerId: string, enabled: booreturn { error: await upstreamError(response, `Composio could not ${enabled ? "enable" : "disable"} the trigger (${response.status})`) };}-async function deleteRemote(env: Env, triggerId: string): Promise<RemoteResult> {+export async function deleteRemote(env: Env, triggerId: string): Promise<RemoteResult> {const response = await composioRequest(env, `/trigger_instances/manage/${encodeURIComponent(triggerId)}`, { method: "DELETE" });if (response.ok || response.status === 404) {await response.body?.cancel();@@ -228,7 +228,7 @@ async function deleteRemote(env: Env, triggerId: string): Promise<RemoteResult>return { error: await upstreamError(response, `Composio could not delete the trigger (${response.status})`) };}-async function listRemoteInstances(env: Env, userId: string): Promise<RemoteInstance[]> {+export async function listRemoteInstances(env: Env, userId: string): Promise<RemoteInstance[]> {const instances: RemoteInstance[] = [];const seen = new Set<string>();let cursor: string | undefined;@@ -258,7 +258,7 @@ async function binding(env: Env, installationId: string, triggerId: string) {/** Bindings other installations hold on the same instance: a desktop and its Cloud that act as one Composio user may* both listen to it. The remote instance is changed only for the last one. */-async function otherBindings(env: Env, installationId: string, triggerId: string, enabledOnly: boolean) {+export async function otherBindings(env: Env, installationId: string, triggerId: string, enabledOnly: boolean) {const row = await env.DB.prepare(`SELECT COUNT(*) AS n FROM trigger_bindings WHERE composio_trigger_id = ? AND installation_id != ?${enabledOnly ? " AND disabled_at IS NULL" : ""}`,).bind(triggerId, installationId).first<{ n: number }>();diff --git a/server/composio-broker-access.test.ts b/server/composio-broker-access.test.tsnew file mode 100644index 0000000000..740782903c--- /dev/null+++ b/server/composio-broker-access.test.ts@@ -0,0 +1,59 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { brokerAccess, eraseManagedBrokerInstallation, setManagedBrokerAccess } from "./composio-broker-access.ts";++const access = { url: "https://broker.example", token: "a".repeat(64) };+const answer = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });++function broker(...answers: Response[]) {+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) => answers.shift() ?? answer(500, {}));+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++beforeEach(() => setManagedBrokerAccess(access));+afterEach(() => {+ vi.unstubAllGlobals();+ setManagedBrokerAccess(null);+});++describe("eraseManagedBrokerInstallation", () => {+ it("calls the erase route with the installation token, then forgets the token", async () => {+ const fetchMock = broker(answer(200, { erased: true, sharedUserKept: false }));+ const clearStored = vi.fn();+ await expect(eraseManagedBrokerInstallation(clearStored)).resolves.toEqual({ sharedUserKept: false });+ const [url, init] = fetchMock.mock.calls[0]!;+ expect(url).toBe("https://broker.example/v1/installation");+ expect(init).toMatchObject({ method: "DELETE", redirect: "error", headers: { authorization: `Bearer ${access.token}` } });+ expect(brokerAccess()).toBeNull();+ expect(clearStored).toHaveBeenCalledOnce();+ });++ it("calls again while the service says there is more, and reports connected apps kept for a shared user", async () => {+ const fetchMock = broker(answer(202, { erased: false, more: true }), answer(202, { erased: false, more: true }), answer(200, { erased: true, sharedUserKept: true }));+ await expect(eraseManagedBrokerInstallation()).resolves.toEqual({ sharedUserKept: true });+ expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(brokerAccess()).toBeNull();+ });++ it("keeps the token when the service fails, so the call can be repeated", async () => {+ broker(answer(502, { error: "Composio could not delete the trigger (500)" }));+ const clearStored = vi.fn();+ await expect(eraseManagedBrokerInstallation(clearStored)).rejects.toThrow("Composio could not delete the trigger");+ expect(brokerAccess()).toEqual(access);+ expect(clearStored).not.toHaveBeenCalled();+ });++ it("treats a refused token as already erased: an earlier answer may have been lost", async () => {+ broker(answer(401, { error: "unauthorized" }));+ await expect(eraseManagedBrokerInstallation()).resolves.toEqual({ sharedUserKept: false });+ expect(brokerAccess()).toBeNull();+ });++ it("does nothing without a managed service", async () => {+ setManagedBrokerAccess(null);+ const fetchMock = broker();+ await expect(eraseManagedBrokerInstallation()).rejects.toThrow("unavailable");+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/server/composio-broker-access.ts b/server/composio-broker-access.tsindex 1fd827a5ba..acd3f2aa93 100644--- a/server/composio-broker-access.ts+++ b/server/composio-broker-access.ts@@ -56,3 +56,35 @@ export function brokerAccess(): BrokerAccess | null {if (!managedBrokerToken.test(token)) throw new Error("The connected-apps service token is invalid");return { url: normalizeManagedBrokerUrl(url), token };}++const ERASE_MAX_CALLS = 40;+const ERASE_CALL_TIMEOUT_MS = 120_000;+const eraseResponseSchema = z.object({ erased: z.boolean().optional(), sharedUserKept: z.boolean().optional(), error: z.string().optional() });++/**+ * Erases this installation at the managed service and forgets its token here. A failure throws with the token kept, so+ * the call can be repeated. `clearStored` removes a token this process keeps on disk: a Cloud home's+ * CLOUD_CONNECTED_APPS_FILE. `sharedUserKept` says connected apps stayed because another installation uses them.+ */+export async function eraseManagedBrokerInstallation(clearStored?: () => void): Promise<{ sharedUserKept: boolean }> {+ const access = brokerAccess();+ if (!access) throw new Error("The connected-apps service is unavailable.");+ for (let call = 0; call < ERASE_MAX_CALLS; call += 1) {+ const response = await fetch(`${access.url}/v1/installation`, {+ method: "DELETE",+ headers: { authorization: `Bearer ${access.token}` },+ redirect: "error",+ signal: AbortSignal.timeout(ERASE_CALL_TIMEOUT_MS),+ });+ if (response.status === 202) { await response.body?.cancel(); continue; }+ const body = eraseResponseSchema.safeParse(await response.json().catch(() => null));+ // 401: the token is already dead, as when an earlier call's answer was lost.+ if (response.status === 401 || (response.ok && body.data?.erased === true)) {+ setManagedBrokerAccess(null);+ clearStored?.();+ return { sharedUserKept: body.data?.sharedUserKept === true };+ }+ throw new Error(body.data?.error ?? `The connected-apps service did not erase this installation (HTTP ${response.status}).`);+ }+ throw new Error("The connected-apps service did not finish erasing this installation. Try again.");+}