mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
fix(connections): leave no connection behind when a first sign-in is cancelled (#22714)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use apps through connections. Most app connections use an OAuth sign-in. > - Paperclip saves a draft connection before it opens the provider sign-in page. > - When the user cancels or abandons that sign-in, the draft stays. The Apps list counts it as a connection that "needs attention". > - The user did not ask for that connection, and the user must not clean it up by hand. > - This pull request hides drafts that never finished their first sign-in and removes the draft when the user clicks Cancel. > - The benefit is that a cancelled sign-in leaves no visible connection, and a retry makes exactly one connection. ## Linked Issues or Issue Description Refs #22634 **What happened?** A workspace has one working "Google Workspace for the organization" connection. The user clicks "Add account", chooses services, and clicks Continue. The page shows "Opening Google Workspace…". The user clicks Cancel before finishing at Google. The Apps page then shows "2 connections · 1 needs attention". **What did you expect to happen?** A cancelled sign-in leaves no visible connection. The same applies when the user closes the page, reloads it, closes the Google tab, or refuses consent at Google. A retry after a cancel makes exactly one connection. A cancelled reconnect of a working connection does not change that connection. **Steps to reproduce** 1. Connect one Google Workspace account. 2. Open Apps, then Google Workspace, then "Add account". 3. Click "Continue to sign in", choose services, and click Continue. 4. On the "Opening Google Workspace" page, click Cancel. 5. Look at the Google Workspace card on the Apps page. ## What Changed - Root cause: `connectApp` saves an OAuth draft (`status: "draft"`) before sign-in (`server/src/services/tool-access.ts`, the connection insert in the connect path). Cancel only navigated away. The Apps list counted every draft as "needs attention" (`ui/src/pages/apps/Browse.tsx`, `connectionState` and the attention count). - New module `server/src/services/tool-access/connections/first-sign-in.ts`. It decides if an OAuth draft never held a credential. It checks for OAuth tokens on the connection and its grants, legacy inline tokens (the removal module's list), a provider consent time, an external credential, and the markers a real connection keeps when it needs a new sign-in. If any check is not clear, the connection counts as real. - The connection list endpoint sets `firstSignInPending: true` on those drafts. The shared `ToolConnection` type has the new field. - New route `POST /tool-connections/:connectionId/sign-in/cancel`. It checks company access and configure permission. It removes the draft with the normal removal teardown (grants, OAuth states, bindings) only if the draft never held a credential. For any other connection it changes nothing and returns `abandoned: false`. A removal writes the activity entry `tool_connection.sign_in_cancelled`. The route is in the OpenAPI registry. - The Apps list does not show connections with `firstSignInPending`, and it does not show an app whose only connections are such drafts. The check is one pass with `Set` lookups. - Cancel works in one transaction: it deletes the pending sign-in states, locks the connection, checks it again, and parks it as `disabled` with the marker `oauth_sign_in_cancelled`. If the connection must stay, the transaction rolls back. Then the normal removal archives the parked draft. Setup never reuses a parked draft, so a retry during the removal gets its own row. - One predicate, `connectionRemovedOrSignInCancelled`, guards authorization start, access finish and machine sign-in. The direct, Cloud and Vercel Connect callbacks and the access finish step lock the connection before they write a grant or activate it, and return 409 `oauth_sign_in_cancelled` for a parked draft. - `docs/api/tool-connections.md` documents the cancel route and the list flag. - The setup page calls the cancel route when the user clicks Cancel on the sign-in screen. It does this only for a draft that this page made. It does not do this for a resume, a reconnect, or a task-linked setup. - Design for abandoned drafts (tab closed, reload, consent refused): they are not listed, and the next attempt reuses them through the existing draft reuse in setup. No background cleanup job is added. ## Verification - `server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts` runs the real routes against embedded Postgres and a local OAuth provider. It covers: a draft is marked and hidden; a provider token exchange held open across Cancel ends in 409; Cancel and a retry at the same time leave exactly one active connection; a parked draft is hidden and refuses a new sign-in start; a legacy draft with an inline token is not cancelled; Cancel removes it, deletes its OAuth state, logs activity, and a late callback fails; a retry after Cancel gives exactly one live connection (organization and personal); Cancel does not change an active connection or a connection that needs a new sign-in; a draft refused at the provider stays hidden and Cancel removes it; another company cannot cancel the draft. - `ui/src/pages/apps/Browse.test.tsx`: a pending draft is not listed and does not add "needs attention". - `ui/src/pages/apps/AppsConnect.test.tsx`: Google Workspace setup, Continue, then Cancel calls the cancel route for the new draft. - Red/green: the new Browse and setup tests fail without the UI change. The server test fails on master because the route and flag do not exist. - Local runs: the new server file, `openapi-routes.test.ts`, `tool-access-oauth-protocol.integration.test.ts`, `Browse.test.tsx`, `AppsConnect.test.tsx`, `activity-format.test.ts`, and `src/features/connections` pass. Server typecheck passes. `pnpm verify` exits 2 because of the pinned inputs file, so CI supplies broad coverage. - Not done: a real browser test against Google. ## Risks - Low risk. The cancel route fails toward no change: it removes nothing that shows any sign of a credential. - Cancel and a late provider callback agree under the connection row lock. If the callback commits first, Cancel changes nothing. If Cancel commits first, the callback returns 409 and saves nothing. This covers the direct, Cloud and Vercel Connect callbacks and the access finish step. - If the removal after Cancel fails, the draft stays parked and hidden, and a second Cancel finishes it. - A connection that was removed before and is now added again keeps its old consent record. If that new sign-in is cancelled, it stays as a visible draft, as it does today. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code with tool use (shell, file edits, test runs). ## 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: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6a07420f26
commit
b908678ea3
21 files changed
+657
-57
No files matched your search
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Tool Connections
|
||||
summary: Remove a connection or one of its grants, read what happened at the provider, and read what to set up in AWS for an AWS role connection
|
||||
summary: Remove a connection or one of its grants, cancel a first sign-in, read what happened at the provider, and read what to set up in AWS for an AWS role connection
|
||||
---
|
||||
|
||||
Removing a connection or a grant always completes in Paperclip. The response says what happened at the provider when Paperclip can ask the provider to end access.
|
||||
@@ -16,6 +16,20 @@ The caller needs `connections:configure` for the connection. Only a board user c
|
||||
|
||||
The `200` response is the archived connection with a `removal` object. `removal` holds counts of what was torn down, for example `secretsRevoked` and `grantsRevoked`. With `deleteStoredContent=true`, the response also has `contentDeletion`.
|
||||
|
||||
## Cancel a First Sign-In
|
||||
|
||||
```
|
||||
POST /api/tool-connections/{connectionId}/sign-in/cancel
|
||||
```
|
||||
|
||||
Use this when a user cancels the provider sign-in for a new connection. The caller needs `connections:configure` for the connection.
|
||||
|
||||
Paperclip removes the connection only if it is an OAuth draft that never held a credential. The removal is the same teardown as `DELETE`, and the activity log gets `tool_connection.sign_in_cancelled`. The `200` response is `{ "abandoned": true, "connection": ... }` with the archived connection.
|
||||
|
||||
For any other connection, Paperclip changes nothing. This includes an active connection and a connection that needs a new sign-in after it worked before. The `200` response is `{ "abandoned": false, "connection": ... }` with the unchanged connection.
|
||||
|
||||
`GET /api/companies/{companyId}/tools/connections` sets `firstSignInPending: true` on an OAuth draft that never held a credential. The Apps page does not show these drafts, and the next setup for the same app reuses them.
|
||||
|
||||
## Remove a Grant
|
||||
|
||||
```
|
||||
|
||||
@@ -191,6 +191,7 @@ export interface ToolConnection {
|
||||
healthStatus: ToolConnectionHealthStatus;
|
||||
/** Managed GitHub grant state; transient health failures do not require sign-in. */
|
||||
requiresReauthorization?: boolean;
|
||||
firstSignInPending?: boolean;
|
||||
healthMessage?: string | null;
|
||||
healthCheckedAt: Date | null;
|
||||
lastHealthAt?: Date | string | null;
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { activityLog, companies, companyMemberships, createDb, toolConnections, toolOauthStates } from "@paperclipai/db";
|
||||
import { and, eq, ne } from "drizzle-orm";
|
||||
import { toolAccessRoutes } from "../routes/tool-access.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
describe("cancelling an unfinished first sign-in", () => {
|
||||
let fixture: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let keyDir: string;
|
||||
let provider: Server;
|
||||
let origin: string;
|
||||
let holdToken: Promise<void> | null = null;
|
||||
let tokenRequested: (() => void) | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
keyDir = await mkdtemp(join(tmpdir(), "tool-cancelled-sign-in-"));
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(keyDir, "key"));
|
||||
vi.stubEnv("PAPERCLIP_PUBLIC_URL", "http://127.0.0.1:3100");
|
||||
vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_ID", "");
|
||||
vi.stubEnv("PAPERCLIP_TOOL_OAUTH_CLIENT_SECRET", "");
|
||||
fixture = await startEmbeddedPostgresTestDatabase("tool-cancelled-sign-in-");
|
||||
db = createDb(fixture.connectionString);
|
||||
provider = createServer(async (req, res) => {
|
||||
let body = "";
|
||||
for await (const chunk of req) body += chunk;
|
||||
const path = new URL(req.url!, origin).pathname;
|
||||
const json = (value: unknown, status = 200) => {
|
||||
res.writeHead(status, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify(value));
|
||||
};
|
||||
if (path.startsWith("/.well-known/oauth-protected-resource")) return json({ resource: `${origin}/mcp`, authorization_servers: [origin] });
|
||||
if (path === "/.well-known/oauth-authorization-server") {
|
||||
return json({
|
||||
issuer: origin, authorization_endpoint: `${origin}/authorize`, token_endpoint: `${origin}/token`,
|
||||
registration_endpoint: `${origin}/register`, code_challenge_methods_supported: ["S256"],
|
||||
token_endpoint_auth_methods_supported: ["none"], scopes_supported: ["tools.write", "offline_access"],
|
||||
grant_types_supported: ["authorization_code", "refresh_token"],
|
||||
});
|
||||
}
|
||||
if (path === "/register") return json({ ...JSON.parse(body), client_id: "fixture-client" });
|
||||
if (path === "/token") {
|
||||
if (holdToken) { tokenRequested?.(); await holdToken; }
|
||||
return json({ access_token: "fixture-access", refresh_token: "fixture-refresh", expires_in: 3600, token_type: "Bearer", scope: "tools.write offline_access" });
|
||||
}
|
||||
if (path === "/mcp") {
|
||||
if (req.headers.authorization !== "Bearer fixture-access") {
|
||||
res.setHeader("www-authenticate", `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"`);
|
||||
return json({}, 401);
|
||||
}
|
||||
const rpc = JSON.parse(body);
|
||||
if (rpc.method === "notifications/initialized") { res.writeHead(202).end(); return; }
|
||||
return json({ jsonrpc: "2.0", id: rpc.id, result: rpc.method === "initialize"
|
||||
? { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "fixture", version: "1" } }
|
||||
: { tools: [{ name: "read_fixture", description: "Read", inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true } }] } });
|
||||
}
|
||||
json({}, 404);
|
||||
});
|
||||
await new Promise<void>((resolve) => provider.listen(0, "127.0.0.1", resolve));
|
||||
origin = `http://127.0.0.1:${(provider.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await new Promise<void>((resolve) => provider?.close(() => resolve()));
|
||||
await fixture?.cleanup();
|
||||
vi.unstubAllEnvs();
|
||||
if (keyDir) await rm(keyDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function setup(grantKind: "organization" | "user" = "organization", source: "local_implicit" | "session" = "local_implicit") {
|
||||
const userId = `cancel-user-${randomUUID()}`;
|
||||
const [company] = await db.insert(companies).values({ name: "Cancelled sign-in", issuePrefix: `C${randomUUID().slice(0, 5)}` }).returning();
|
||||
await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: userId, status: "active", membershipRole: "admin" });
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = source === "local_implicit"
|
||||
? { type: "board", userId, source, isInstanceAdmin: true }
|
||||
: { type: "board", userId, source, isInstanceAdmin: false, companyIds: [company.id],
|
||||
memberships: [{ companyId: company.id, membershipRole: "admin", status: "active" }] };
|
||||
next();
|
||||
});
|
||||
app.use("/api", toolAccessRoutes(db, { deploymentMode: "local_trusted", deploymentExposure: "private", paperclipCloudConnector: null }));
|
||||
app.use(errorHandler);
|
||||
const connect = async () => {
|
||||
const connected = await request(app).post(`/api/companies/${company.id}/tools/apps/connect`)
|
||||
.send({ link: `${origin}/mcp`, name: "Local OAuth", grantKind }).expect(201);
|
||||
return { connectionId: connected.body.connectionId as string, state: new URL(connected.body.auth.startUrl).searchParams.get("state")! };
|
||||
};
|
||||
const listed = async () => (await request(app).get(`/api/companies/${company.id}/tools/connections`).expect(200)).body.connections as Array<{ id: string; status: string; firstSignInPending?: boolean }>;
|
||||
const visible = async () => (await listed()).filter((connection) => connection.status !== "archived" && !connection.firstSignInPending);
|
||||
return { app, company, connect, listed, visible };
|
||||
}
|
||||
|
||||
it("marks a never-finished sign-in as pending and removes it on cancel", async () => {
|
||||
const { app, company, connect, listed, visible } = await setup();
|
||||
const { connectionId, state } = await connect();
|
||||
expect((await listed()).find((connection) => connection.id === connectionId)).toMatchObject({ status: "draft", firstSignInPending: true });
|
||||
expect(await visible()).toEqual([]);
|
||||
|
||||
const cancelled = await request(app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`).expect(200);
|
||||
expect(cancelled.body).toMatchObject({ abandoned: true, connection: { id: connectionId, status: "archived" } });
|
||||
expect(await db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, connectionId))).toEqual([]);
|
||||
expect((await listed()).filter((connection) => connection.status !== "archived")).toEqual([]);
|
||||
const [logged] = await db.select().from(activityLog).where(and(eq(activityLog.companyId, company.id), eq(activityLog.action, "tool_connection.sign_in_cancelled")));
|
||||
expect(logged).toMatchObject({ entityType: "tool_connection", entityId: connectionId });
|
||||
await request(app).get("/api/tools/oauth/callback").query({ state, code: "late-code", iss: origin }).expect(400);
|
||||
});
|
||||
|
||||
it.each(["organization", "user"] as const)("retries a cancelled %s sign-in into exactly one connection", async (grantKind) => {
|
||||
const { app, company, connect, visible } = await setup(grantKind);
|
||||
const first = await connect();
|
||||
await request(app).post(`/api/tool-connections/${first.connectionId}/sign-in/cancel`).expect(200);
|
||||
const retry = await connect();
|
||||
await request(app).get("/api/tools/oauth/callback").query({ state: retry.state, code: "fixture-code", iss: origin }).expect(200);
|
||||
|
||||
const shown = await visible();
|
||||
expect(shown).toHaveLength(1);
|
||||
expect(shown[0]).toMatchObject({ id: retry.connectionId, status: "active" });
|
||||
const live = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, company.id), ne(toolConnections.status, "archived")));
|
||||
expect(live.map((row) => row.id)).toEqual([retry.connectionId]);
|
||||
});
|
||||
|
||||
it("leaves a connection that once signed in unchanged when its reconnect is cancelled", async () => {
|
||||
const { app, connect, listed } = await setup();
|
||||
const { connectionId, state } = await connect();
|
||||
await request(app).get("/api/tools/oauth/callback").query({ state, code: "fixture-code", iss: origin }).expect(200);
|
||||
const [active] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId));
|
||||
expect(active.status).toBe("active");
|
||||
|
||||
const untouched = await request(app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`).expect(200);
|
||||
expect(untouched.body).toMatchObject({ abandoned: false, connection: { id: connectionId, status: "active" } });
|
||||
|
||||
await db.update(toolConnections).set({ status: "draft", enabled: false, credentialRefs: [], credentialSecretRefs: [] }).where(eq(toolConnections.id, connectionId));
|
||||
expect((await listed()).find((connection) => connection.id === connectionId)?.firstSignInPending).toBeUndefined();
|
||||
const needsReconnect = await request(app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`).expect(200);
|
||||
expect(needsReconnect.body).toMatchObject({ abandoned: false, connection: { id: connectionId, status: "draft" } });
|
||||
const [after] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId));
|
||||
expect(after.status).toBe("draft");
|
||||
});
|
||||
|
||||
it("keeps a sign-in refused at the provider hidden and cancellable", async () => {
|
||||
const { app, connect, listed, visible } = await setup();
|
||||
const { connectionId, state } = await connect();
|
||||
await request(app).get("/api/tools/oauth/callback").query({ state, error: "access_denied", iss: origin }).expect(400);
|
||||
expect((await listed()).find((connection) => connection.id === connectionId)).toMatchObject({ status: "draft", firstSignInPending: true });
|
||||
expect(await visible()).toEqual([]);
|
||||
await request(app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`).expect(200).expect(({ body }) => expect(body.abandoned).toBe(true));
|
||||
});
|
||||
|
||||
it("keeps a retry that starts while the cancel is still removing the draft", async () => {
|
||||
const { app, company, connect, visible } = await setup();
|
||||
const first = await connect();
|
||||
const [cancelled, retry] = await Promise.all([
|
||||
request(app).post(`/api/tool-connections/${first.connectionId}/sign-in/cancel`).expect(200),
|
||||
connect(),
|
||||
]);
|
||||
expect(cancelled.body.abandoned).toBe(true);
|
||||
await request(app).get("/api/tools/oauth/callback").query({ state: retry.state, code: "fixture-code", iss: origin }).expect(200);
|
||||
const live = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, company.id), ne(toolConnections.status, "archived")));
|
||||
expect(live.map((row) => [row.id, row.status])).toEqual([[retry.connectionId, "active"]]);
|
||||
expect((await visible()).map((connection) => connection.id)).toEqual([retry.connectionId]);
|
||||
});
|
||||
|
||||
it("refuses a sign-in that finishes after the user cancelled it", async () => {
|
||||
const { app, connect, visible } = await setup();
|
||||
const { connectionId, state } = await connect();
|
||||
let release!: () => void;
|
||||
holdToken = new Promise<void>((resolve) => { release = resolve; });
|
||||
const requested = new Promise<void>((resolve) => { tokenRequested = resolve; });
|
||||
try {
|
||||
const callback = request(app).get("/api/tools/oauth/callback").query({ state, code: "fixture-code", iss: origin }).then((response) => response);
|
||||
await requested;
|
||||
await request(app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`).expect(200).expect(({ body }) => expect(body.abandoned).toBe(true));
|
||||
release();
|
||||
expect((await callback).status).toBe(409);
|
||||
} finally {
|
||||
holdToken = null;
|
||||
tokenRequested = null;
|
||||
}
|
||||
const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId));
|
||||
expect(row.status).toBe("archived");
|
||||
expect(await visible()).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a draft whose cancel is still being removed hidden and closed to sign-in", async () => {
|
||||
const { app, company, connect, listed, visible } = await setup();
|
||||
const { connectionId } = await connect();
|
||||
await db.update(toolConnections).set({ status: "disabled", enabled: false, lastError: "oauth_sign_in_cancelled" }).where(eq(toolConnections.id, connectionId));
|
||||
expect((await listed()).find((connection) => connection.id === connectionId)?.firstSignInPending).toBe(true);
|
||||
expect(await visible()).toEqual([]);
|
||||
await request(app).post(`/api/tools/oauth/${connectionId}/start`).send({}).expect(409);
|
||||
for (const grantKind of ["user", "organization"]) {
|
||||
await request(app).post(`/api/companies/${company.id}/tools/apps/${connectionId}/finalize-oauth-access`).send({ grantKind }).expect(409);
|
||||
}
|
||||
await request(app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`).expect(200).expect(({ body }) => expect(body).toMatchObject({ abandoned: true, connection: { status: "archived" } }));
|
||||
});
|
||||
|
||||
it("keeps a saved machine sign-in draft listed and in place", async () => {
|
||||
const { app, connect, listed } = await setup();
|
||||
const { connectionId } = await connect();
|
||||
const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId));
|
||||
const config = { ...row.config, oauth: { ...(row.config.oauth as Record<string, unknown>), grantType: "client_credentials" } };
|
||||
await db.update(toolConnections).set({ config, transportConfig: config }).where(eq(toolConnections.id, connectionId));
|
||||
expect((await listed()).find((connection) => connection.id === connectionId)?.firstSignInPending).toBeUndefined();
|
||||
await request(app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`).expect(200).expect(({ body }) => expect(body.abandoned).toBe(false));
|
||||
});
|
||||
|
||||
it("treats a legacy draft with an inline token as a real connection", async () => {
|
||||
const { app, connect } = await setup();
|
||||
const { connectionId } = await connect();
|
||||
const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId));
|
||||
const config = { ...row.config, oauth: { ...(row.config.oauth as Record<string, unknown>), access_token: "legacy-inline" } };
|
||||
await db.update(toolConnections).set({ config, transportConfig: config }).where(eq(toolConnections.id, connectionId));
|
||||
const response = await request(app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`).expect(200);
|
||||
expect(response.body.abandoned).toBe(false);
|
||||
const [after] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId));
|
||||
expect(after.status).toBe("draft");
|
||||
});
|
||||
|
||||
it("does not let another company cancel the draft", async () => {
|
||||
const owner = await setup();
|
||||
const other = await setup("organization", "session");
|
||||
const { connectionId } = await owner.connect();
|
||||
const response = await request(other.app).post(`/api/tool-connections/${connectionId}/sign-in/cancel`);
|
||||
expect([403, 404]).toContain(response.status);
|
||||
const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId));
|
||||
expect(row.status).toBe("draft");
|
||||
});
|
||||
});
|
||||
@@ -12875,6 +12875,15 @@ registerCurrentRoute({
|
||||
responses: { 200: r.ok(), ...MACHINE_SIGN_IN_ERRORS },
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
"x-paperclip-transport": "rest",
|
||||
"x-paperclip-connection-management": "connections:configure",
|
||||
method: "post",
|
||||
path: "/api/tool-connections/{connectionId}/sign-in/cancel",
|
||||
tags: ["tool-access"],
|
||||
summary: "Remove a connection whose first sign-in was cancelled; a connection that ever signed in is left unchanged",
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
"x-paperclip-transport": "rest",
|
||||
"x-paperclip-connection-management": "connections:configure",
|
||||
|
||||
@@ -2552,6 +2552,38 @@ function connectorEnrollmentPrincipal(req: Request): string {
|
||||
res.json({ ...connection, removal, ...(contentDeletion ? { contentDeletion } : {}) });
|
||||
});
|
||||
|
||||
router.post("/tool-connections/:connectionId/sign-in/cancel", managementGuard("connections:configure", "POST /tool-connections/:connectionId/sign-in/cancel", { personal: true }), async (req, res) => {
|
||||
const existing = await getAccessibleResource(req, res, svc.getConnection(req.params.connectionId as string), "Tool connection not found");
|
||||
if (!existing) return;
|
||||
await assertToolConnectionConfigureAccess(req, existing);
|
||||
const applicationBefore = await svc.getApplication(existing.applicationId);
|
||||
const result = await svc.abandonFirstSignIn(existing.id, existing.companyId, connectionRequestActor(req));
|
||||
if (!result.abandoned) {
|
||||
res.json({ abandoned: false, connection: result.connection });
|
||||
return;
|
||||
}
|
||||
await logActivity(db, {
|
||||
companyId: existing.companyId,
|
||||
...connectionRequestActor(req),
|
||||
action: "tool_connection.sign_in_cancelled",
|
||||
entityType: "tool_connection",
|
||||
entityId: existing.id,
|
||||
details: { transport: existing.transport, ...result.removal },
|
||||
});
|
||||
const applicationAfter = await svc.getApplication(existing.applicationId);
|
||||
if (applicationBefore.status !== "archived" && applicationAfter.status === "archived") {
|
||||
await logActivity(db, {
|
||||
companyId: applicationAfter.companyId,
|
||||
...connectionRequestActor(req),
|
||||
action: "tool_application.archived",
|
||||
entityType: "tool_application",
|
||||
entityId: applicationAfter.id,
|
||||
details: { type: applicationAfter.type, name: applicationAfter.name, reason: "sign_in_cancelled" },
|
||||
});
|
||||
}
|
||||
res.json({ abandoned: true, connection: result.connection });
|
||||
});
|
||||
|
||||
async function requestStoredContentDeletion(req: Request, connection: { id: string; companyId: string }) {
|
||||
const actor = getActorInfo(req);
|
||||
const { deletion, created } = await contentDeletion.request(connection, {
|
||||
|
||||
@@ -13,6 +13,7 @@ import { createConnectionCredentialValidation } from "./tool-access/connections/
|
||||
import { createConnectionGrants } from "./tool-access/connections/grants.js";
|
||||
import { createConnectionInstalls } from "./tool-access/connections/installs.js";
|
||||
import { createConnectionRemoval } from "./tool-access/connections/removal.js";
|
||||
import { createFirstSignInDrafts } from "./tool-access/connections/first-sign-in.js";
|
||||
import { createToolRemoteHttp } from "./tool-access/remote-http.js";
|
||||
import { classifyRisk, normalizeToolDescriptor, type McpToolDescriptor } from "./tool-access/catalog/descriptors.js";
|
||||
export { classifyRisk, isGmailToolPermanentlyBlocked, isGoogleWorkspaceToolAllowed, type McpToolDescriptor } from "./tool-access/catalog/descriptors.js";
|
||||
@@ -791,6 +792,7 @@ export function toolAccessService(
|
||||
const runtimeSupervisor = createToolRuntimeSupervisor(db, options);
|
||||
const connectionGrantsService = createConnectionGrants(db, { getConnectionRow, assertSecretRefs, vercelConnect, currentCloudConnector, secrets });
|
||||
const removeConnection = createConnectionRemoval(db, { options, secrets, runtimeSupervisor, vercelConnect, currentCloudConnector, getConnectionRow });
|
||||
const firstSignInDrafts = createFirstSignInDrafts(db, { removeConnection });
|
||||
/**
|
||||
* Connection setup resolves connector definitions synchronously. Refresh the
|
||||
* plugin-provided part of the catalog from the plugins table first, so a
|
||||
@@ -4796,6 +4798,7 @@ export function toolAccessService(
|
||||
await annotateAiGrantHealth(connections);
|
||||
await annotateGitHubAuthorization(connections, viewerUserId);
|
||||
await annotateSavedOAuthClientSecret(connections, viewerUserId);
|
||||
await firstSignInDrafts.annotateFirstSignInPending(companyId, rows, connections);
|
||||
return connections;
|
||||
},
|
||||
|
||||
@@ -5007,6 +5010,8 @@ export function toolAccessService(
|
||||
|
||||
archiveConnection: removeConnection,
|
||||
|
||||
abandonFirstSignIn: firstSignInDrafts.abandonFirstSignIn,
|
||||
|
||||
checkHealth: checkConnectionHealth,
|
||||
|
||||
refreshCatalog,
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { connectionGrants, toolConnections, toolOauthStates } from "@paperclipai/db";
|
||||
import type { ToolConnection, ToolConnectionRemovalResult } from "@paperclipai/shared";
|
||||
import { conflict, notFound } from "../../../errors.js";
|
||||
import type { ActorInfo, ToolAccessMutationDb } from "../types.js";
|
||||
import { asRecord, oauthConfig } from "../oauth/metadata.js";
|
||||
import { oauthSecretRef } from "../oauth/client-settings.js";
|
||||
import { toConnection } from "./projection.js";
|
||||
import { INLINE_OAUTH_TOKEN_FIELDS } from "./removal.js";
|
||||
|
||||
type ConnectionRow = typeof toolConnections.$inferSelect;
|
||||
type GrantEvidence = Pick<typeof connectionGrants.$inferSelect, "connectionId" | "credentialSecretRefs" | "providerTenant" | "externalCredential">;
|
||||
|
||||
const OAUTH_TOKEN_PATHS = new Set(["oauth.access_token", "oauth.refresh_token"]);
|
||||
const SIGN_IN_CANCELLED = "oauth_sign_in_cancelled";
|
||||
|
||||
function signInCancelled(connection: Pick<ConnectionRow, "status" | "lastError">): boolean {
|
||||
return connection.status === "disabled" && connection.lastError === SIGN_IN_CANCELLED;
|
||||
}
|
||||
|
||||
export function connectionRemovedOrSignInCancelled(connection: Pick<ConnectionRow, "status" | "lastError">): boolean {
|
||||
return connection.status === "archived" || signInCancelled(connection);
|
||||
}
|
||||
|
||||
function holdsInlineOAuthToken(config: unknown): boolean {
|
||||
const oauth = asRecord(asRecord(config).oauth);
|
||||
return INLINE_OAUTH_TOKEN_FIELDS.some((field) => field in oauth);
|
||||
}
|
||||
|
||||
export function connectionHasOAuthCredential(connection: ConnectionRow, grants: GrantEvidence[]): boolean {
|
||||
const oauth = oauthConfig(connection);
|
||||
return Boolean(oauth.connectedAt || oauth.reauthorizationRequiredAt)
|
||||
|| Boolean(oauthSecretRef(connection, "oauth.access_token") || oauthSecretRef(connection, "oauth.refresh_token"))
|
||||
|| (connection.credentialRefs ?? []).some((ref) => OAUTH_TOKEN_PATHS.has(ref.name))
|
||||
|| holdsInlineOAuthToken(connection.config)
|
||||
|| holdsInlineOAuthToken(connection.transportConfig)
|
||||
|| grants.some((grant) =>
|
||||
Boolean(grant.externalCredential)
|
||||
|| Boolean(asRecord(asRecord(grant.providerTenant).oauth).consentedAt)
|
||||
|| (grant.credentialSecretRefs ?? []).some((ref) => OAUTH_TOKEN_PATHS.has(ref.configPath)));
|
||||
}
|
||||
|
||||
export function connectionAwaitsFirstSignIn(connection: ConnectionRow, grants: GrantEvidence[]): boolean {
|
||||
if (signInCancelled(connection)) return true;
|
||||
return connection.status === "draft"
|
||||
&& connection.authKind === "oauth"
|
||||
&& oauthConfig(connection).grantType !== "client_credentials"
|
||||
&& connection.lastError !== "connection_identity_rollback_failed"
|
||||
&& !connectionHasOAuthCredential(connection, grants);
|
||||
}
|
||||
|
||||
export async function lockConnectionForSignIn(
|
||||
tx: ToolAccessMutationDb,
|
||||
connection: Pick<ConnectionRow, "id" | "companyId">,
|
||||
) {
|
||||
const [locked] = await tx.select({ status: toolConnections.status, lastError: toolConnections.lastError }).from(toolConnections)
|
||||
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
|
||||
.for("update");
|
||||
if (locked && connectionRemovedOrSignInCancelled(locked)) {
|
||||
throw conflict("This sign-in was cancelled. Start the connection again.", { code: SIGN_IN_CANCELLED });
|
||||
}
|
||||
}
|
||||
|
||||
type Dependencies = {
|
||||
removeConnection(connectionId: string, companyId?: string, actor?: ActorInfo): Promise<ToolConnectionRemovalResult>;
|
||||
};
|
||||
|
||||
async function grantEvidence(db: ToolAccessMutationDb, companyId: string, connectionIds: string[]): Promise<GrantEvidence[]> {
|
||||
if (connectionIds.length === 0) return [];
|
||||
return db
|
||||
.select({
|
||||
connectionId: connectionGrants.connectionId,
|
||||
credentialSecretRefs: connectionGrants.credentialSecretRefs,
|
||||
providerTenant: connectionGrants.providerTenant,
|
||||
externalCredential: connectionGrants.externalCredential,
|
||||
})
|
||||
.from(connectionGrants)
|
||||
.where(and(eq(connectionGrants.companyId, companyId), inArray(connectionGrants.connectionId, connectionIds)));
|
||||
}
|
||||
|
||||
class KeptConnection {
|
||||
row: ConnectionRow | null = null;
|
||||
}
|
||||
|
||||
export function createFirstSignInDrafts(db: Db, { removeConnection }: Dependencies) {
|
||||
async function annotateFirstSignInPending(companyId: string, rows: ConnectionRow[], connections: ToolConnection[]) {
|
||||
const candidates = rows.filter((row) => connectionAwaitsFirstSignIn(row, []));
|
||||
if (candidates.length === 0) return;
|
||||
const grants = await grantEvidence(db, companyId, candidates.map((row) => row.id));
|
||||
const grantsByConnection = new Map<string, GrantEvidence[]>();
|
||||
for (const grant of grants) grantsByConnection.set(grant.connectionId, [...(grantsByConnection.get(grant.connectionId) ?? []), grant]);
|
||||
const pending = new Set(candidates
|
||||
.filter((row) => connectionAwaitsFirstSignIn(row, grantsByConnection.get(row.id) ?? []))
|
||||
.map((row) => row.id));
|
||||
for (const connection of connections) {
|
||||
if (pending.has(connection.id)) connection.firstSignInPending = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function abandonFirstSignIn(
|
||||
connectionId: string,
|
||||
companyId: string,
|
||||
actor?: ActorInfo,
|
||||
): Promise<{ abandoned: false; connection: ToolConnection } | ({ abandoned: true } & ToolConnectionRemovalResult)> {
|
||||
const kept = new KeptConnection();
|
||||
try {
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.delete(toolOauthStates).where(and(eq(toolOauthStates.companyId, companyId), eq(toolOauthStates.connectionId, connectionId)));
|
||||
const [row] = await tx.select().from(toolConnections)
|
||||
.where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, companyId)))
|
||||
.for("update");
|
||||
if (!row) throw notFound("Tool connection not found");
|
||||
if (!connectionAwaitsFirstSignIn(row, await grantEvidence(tx, companyId, [row.id]))) {
|
||||
kept.row = row;
|
||||
throw kept;
|
||||
}
|
||||
await tx.update(toolConnections).set({ status: "disabled", enabled: false, lastError: SIGN_IN_CANCELLED, updatedAt: new Date() })
|
||||
.where(and(eq(toolConnections.id, row.id), eq(toolConnections.companyId, companyId)));
|
||||
});
|
||||
} catch (error) {
|
||||
if (error === kept && kept.row) return { abandoned: false, connection: toConnection(kept.row) };
|
||||
throw error;
|
||||
}
|
||||
return { abandoned: true, ...(await removeConnection(connectionId, companyId, actor)) };
|
||||
}
|
||||
|
||||
return { annotateFirstSignInPending, abandonFirstSignIn };
|
||||
}
|
||||
@@ -45,7 +45,7 @@ function asRecord(value: unknown): Record<string, unknown> {
|
||||
const CONNECTION_OWNED_SECRET_KEY_PREFIX = "tool_app.";
|
||||
|
||||
/** Token fields a legacy row may have inlined into `config.oauth`. */
|
||||
const INLINE_OAUTH_TOKEN_FIELDS = [
|
||||
export const INLINE_OAUTH_TOKEN_FIELDS = [
|
||||
"access_token",
|
||||
"refresh_token",
|
||||
"accessToken",
|
||||
|
||||
@@ -15,6 +15,7 @@ import { secretService } from "../../secrets.js";
|
||||
import type { OAuthCredentialStore } from "./credential-store.js";
|
||||
|
||||
import type { FinishConnectionSetup } from "../catalog/contracts.js";
|
||||
import { connectionRemovedOrSignInCancelled, lockConnectionForSignIn } from "../connections/first-sign-in.js";
|
||||
|
||||
type Dependencies = {
|
||||
getConnectionRow(idOrUid: string, companyId?: string): Promise<typeof toolConnections.$inferSelect>;
|
||||
@@ -52,7 +53,7 @@ async function finalizeOAuthAccess(
|
||||
};
|
||||
if (connection.authKind !== "oauth")
|
||||
throw badRequest("This connection does not use browser sign-in");
|
||||
if (connection.status === "archived")
|
||||
if (connectionRemovedOrSignInCancelled(connection))
|
||||
throw conflict("Archived app connections cannot be finished");
|
||||
const actorUserId = connectionActorUserId(actor);
|
||||
if (!actorUserId)
|
||||
@@ -118,6 +119,7 @@ async function finalizeOAuthAccess(
|
||||
throw conflict("This connection already uses a company identity");
|
||||
}
|
||||
connection = await writeToolConnectionHealthChange(db, connection, async tx => {
|
||||
await lockConnectionForSignIn(tx, connection);
|
||||
await notifyGitHubCredentialChange(tx, connection);
|
||||
const [updated] = await tx
|
||||
.update(toolConnections)
|
||||
@@ -259,9 +261,7 @@ async function finalizeOAuthAccess(
|
||||
await tx.select({ id: toolApplications.id }).from(toolApplications)
|
||||
.where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, companyId)))
|
||||
.for("update");
|
||||
await tx.select({ id: toolConnections.id }).from(toolConnections)
|
||||
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId)))
|
||||
.for("update");
|
||||
await lockConnectionForSignIn(tx, connection);
|
||||
const [existingOrganizationGrant] = await tx
|
||||
.select()
|
||||
.from(connectionGrants)
|
||||
|
||||
@@ -24,6 +24,7 @@ import { assertSupportedConnection } from "../connections/setup-policy.js";
|
||||
import { actorBinding } from "../actor.js";
|
||||
import { assertOAuthRedirectConstraints, randomOauthToken, base64UrlSha256 } from "./authorization-constraints.js";
|
||||
import type { createPersonalConnectionIdentity } from "../connections/personal-identity.js";
|
||||
import { connectionRemovedOrSignInCancelled } from "../connections/first-sign-in.js";
|
||||
|
||||
type Dependencies = {
|
||||
now: () => Date;
|
||||
@@ -77,7 +78,7 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies
|
||||
assertSupportedConnection(connection);
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
await assertExperimentalConnectorSetupEnabled(connection.config.sourceTemplateKey, connection.status !== "draft");
|
||||
if (connection.status === "archived")
|
||||
if (connectionRemovedOrSignInCancelled(connection))
|
||||
throw conflict("Archived app connections cannot start sign in");
|
||||
const sourceTemplateKey =
|
||||
typeof connection.config.sourceTemplateKey === "string"
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
} from "./metadata.js";
|
||||
import { normalizeOAuthProviderError } from "./provider-errors.js";
|
||||
import type { OAuthTransport } from "./types.js";
|
||||
import { connectionRemovedOrSignInCancelled } from "../connections/first-sign-in.js";
|
||||
|
||||
type Dependencies = OAuthTransport & {
|
||||
now: () => Date;
|
||||
@@ -372,7 +373,7 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) {
|
||||
|
||||
async function machineSignInConnection(companyId: string, connectionId: string) {
|
||||
const connection = await getConnectionRow(connectionId, companyId);
|
||||
if (connection.status === "archived") {
|
||||
if (connectionRemovedOrSignInCancelled(connection)) {
|
||||
throw unprocessable("This connection was removed. Set up machine sign-in again to reconnect.", {
|
||||
code: "client_credentials_connection_removed",
|
||||
});
|
||||
@@ -433,7 +434,7 @@ export function createClientCredentialsService(db: Db, deps: Dependencies) {
|
||||
const [locked] = await tx.select().from(toolConnections)
|
||||
.where(and(eq(toolConnections.id, previous.id), eq(toolConnections.companyId, previous.companyId)))
|
||||
.for("update");
|
||||
if (!locked || locked.status === "archived" || signInState(locked) !== signInState(previous)) {
|
||||
if (!locked || connectionRemovedOrSignInCancelled(locked) || signInState(locked) !== signInState(previous)) {
|
||||
throw machineSignInChangedError();
|
||||
}
|
||||
const written: Record<string, ToolCredentialSecretRef> = {};
|
||||
|
||||
@@ -16,6 +16,7 @@ import { connectionGrants, companyMemberships, principalPermissionGrants, issueT
|
||||
import type { ConnectionGrantKind, ConnectToolAppResult } from "@paperclipai/shared";
|
||||
import { getConnectableAppDefinition, recommendedDefaultsForApp } from "@paperclipai/shared";
|
||||
import { badRequest, forbidden, HttpError, unprocessable } from "../../../errors.js";
|
||||
import { lockConnectionForSignIn } from "../connections/first-sign-in.js";
|
||||
import { secretService } from "../../secrets.js";
|
||||
import { isPaperclipCloudConnectorStrategy, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
|
||||
|
||||
@@ -260,9 +261,7 @@ export function createCloudOAuthCallback(db: Db, dependencies: Dependencies) {
|
||||
await tx.select({ id: toolApplications.id }).from(toolApplications)
|
||||
.where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, connection.companyId)))
|
||||
.for("update");
|
||||
await tx.select({ id: toolConnections.id }).from(toolConnections)
|
||||
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
|
||||
.for("update");
|
||||
await lockConnectionForSignIn(tx, connection);
|
||||
const existingRefs =
|
||||
existingCredentialGrant?.credentialSecretRefs ??
|
||||
(personalCredential || agentCredential
|
||||
|
||||
@@ -16,6 +16,7 @@ import { connectionGrants, companyMemberships, principalPermissionGrants, issueT
|
||||
import type { ConnectToolAppResult } from "@paperclipai/shared";
|
||||
import { getConnectableAppDefinition, recommendedDefaultsForApp } from "@paperclipai/shared";
|
||||
import { badRequest, forbidden, HttpError, unprocessable } from "../../../errors.js";
|
||||
import { lockConnectionForSignIn } from "../connections/first-sign-in.js";
|
||||
import { secretService } from "../../secrets.js";
|
||||
|
||||
import type { OAuthStateStore } from "./state.js";
|
||||
@@ -207,9 +208,7 @@ export function createDirectOAuthCallback(db: Db, dependencies: Dependencies) {
|
||||
await tx.select({ id: toolApplications.id }).from(toolApplications)
|
||||
.where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, connection.companyId)))
|
||||
.for("update");
|
||||
await tx.select({ id: toolConnections.id }).from(toolConnections)
|
||||
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
|
||||
.for("update");
|
||||
await lockConnectionForSignIn(tx, connection);
|
||||
const subjectCredentialSecretRefs =
|
||||
existingUserGrant?.credentialSecretRefs ?? [];
|
||||
const accessRef = await createOrRotateOAuthSecret(
|
||||
@@ -533,9 +532,7 @@ export function createDirectOAuthCallback(db: Db, dependencies: Dependencies) {
|
||||
await tx.select({ id: toolApplications.id }).from(toolApplications)
|
||||
.where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, connection.companyId)))
|
||||
.for("update");
|
||||
await tx.select({ id: toolConnections.id }).from(toolConnections)
|
||||
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
|
||||
.for("update");
|
||||
await lockConnectionForSignIn(tx, connection);
|
||||
const txSecrets = secretService(tx);
|
||||
const txSecretContext = { dbClient: tx, secretClient: txSecrets };
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { connectionGrants, companyMemberships, toolApplications, toolConnections
|
||||
import type { ConnectionGrantKind, ConnectToolAppResult } from "@paperclipai/shared";
|
||||
import { getConnectableAppDefinition, recommendedDefaultsForApp } from "@paperclipai/shared";
|
||||
import { badRequest, forbidden, HttpError } from "../../../errors.js";
|
||||
import { lockConnectionForSignIn } from "../connections/first-sign-in.js";
|
||||
import { deriveVercelConnectSubject, vercelGrantReference, vercelTokenRequest, VercelConnectClientError, type VercelConnectClient } from "../../vercel-connect.js";
|
||||
|
||||
import type { OAuthStateStore } from "./state.js";
|
||||
@@ -163,42 +164,51 @@ export function createVercelOAuthCallback(db: Db, dependencies: Dependencies) {
|
||||
revokedByUserId: null,
|
||||
updatedAt: now(),
|
||||
};
|
||||
if (existingGrant) {
|
||||
await db
|
||||
.update(connectionGrants)
|
||||
.set(grantValues)
|
||||
.where(eq(connectionGrants.id, existingGrant.id));
|
||||
} else {
|
||||
await db.insert(connectionGrants).values({
|
||||
companyId: connection.companyId,
|
||||
connectionId: connection.id,
|
||||
kind: grantKind,
|
||||
subjectUserId: stateRow.subjectUserId,
|
||||
...grantValues,
|
||||
createdByUserId:
|
||||
connectionActorUserId(input.actor),
|
||||
});
|
||||
}
|
||||
const preActivationLifecycle = {
|
||||
status: connection.status,
|
||||
enabled: connection.enabled,
|
||||
};
|
||||
[connection] = await writeToolConnectionHealthChange(db, connection, tx => tx
|
||||
.update(toolConnections)
|
||||
.set({
|
||||
status: "active",
|
||||
enabled: true,
|
||||
credentialRefs: [],
|
||||
credentialSecretRefs: [],
|
||||
updatedAt: now(),
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(toolConnections.id, connection.id),
|
||||
eq(toolConnections.companyId, connection.companyId),
|
||||
),
|
||||
)
|
||||
.returning());
|
||||
const activating = connection;
|
||||
[connection] = await writeToolConnectionHealthChange(db, connection, async tx => {
|
||||
if (existingGrant) {
|
||||
await tx.select({ id: connectionGrants.id }).from(connectionGrants)
|
||||
.where(eq(connectionGrants.id, existingGrant.id))
|
||||
.for("update");
|
||||
}
|
||||
await lockConnectionForSignIn(tx, activating);
|
||||
if (existingGrant) {
|
||||
await tx
|
||||
.update(connectionGrants)
|
||||
.set(grantValues)
|
||||
.where(eq(connectionGrants.id, existingGrant.id));
|
||||
} else {
|
||||
await tx.insert(connectionGrants).values({
|
||||
companyId: activating.companyId,
|
||||
connectionId: activating.id,
|
||||
kind: grantKind,
|
||||
subjectUserId: stateRow.subjectUserId,
|
||||
...grantValues,
|
||||
createdByUserId:
|
||||
connectionActorUserId(input.actor),
|
||||
});
|
||||
}
|
||||
return tx
|
||||
.update(toolConnections)
|
||||
.set({
|
||||
status: "active",
|
||||
enabled: true,
|
||||
credentialRefs: [],
|
||||
credentialSecretRefs: [],
|
||||
updatedAt: now(),
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(toolConnections.id, activating.id),
|
||||
eq(toolConnections.companyId, activating.companyId),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
});
|
||||
emitConnectionUpdated(
|
||||
connection,
|
||||
preActivationLifecycle,
|
||||
|
||||
@@ -459,7 +459,7 @@
|
||||
"packages/shared/src/types/tailscale.ts": "d02a917945d7779009a2dea4c4b535e9478e0680",
|
||||
"packages/shared/src/types/task-workspace.ts": "a23afa13d2cb58dc2eb72692ed28c16ed6fb84fb",
|
||||
"packages/shared/src/types/teams-catalog.ts": "632fe75f8e5a4cfc455843c2a1a2daff28a022be",
|
||||
"packages/shared/src/types/tool-access.ts": "f8224dd6845eec6b4e8760d7fd6f568d3830e367",
|
||||
"packages/shared/src/types/tool-access.ts": "6c12f314791cad2d273c8893cbfc68807a0f5d84",
|
||||
"packages/shared/src/types/user-profile.ts": "1ac26e033a79fab21dc267fd983959814c8b680f",
|
||||
"packages/shared/src/types/voice-sessions.ts": "95e3b62cdd51f62290e68536728ddd7297bc0459",
|
||||
"packages/shared/src/types/work-product.ts": "26f9129f606a207ce7a218ccef40f96747283086",
|
||||
|
||||
@@ -450,6 +450,8 @@ export const toolsApi = {
|
||||
api.delete<ToolConnection & { removal: ToolConnectionRemovalSummary; contentDeletion?: ToolConnectionContentDeletion }>(
|
||||
`/tool-connections/${connectionId}${options.deleteStoredContent ? "?deleteStoredContent=true" : ""}`,
|
||||
),
|
||||
cancelFirstSignIn: (connectionId: string) =>
|
||||
api.post<{ abandoned: boolean; connection: ToolConnection }>(`/tool-connections/${connectionId}/sign-in/cancel`, {}),
|
||||
getStoredContent: (connectionId: string) =>
|
||||
api.get<ToolConnectionStoredContent>(`/tool-connections/${connectionId}/stored-content`),
|
||||
deleteStoredContent: (connectionId: string) =>
|
||||
|
||||
@@ -891,6 +891,31 @@ function StandardConnectionSetupFlow({
|
||||
oauthPopupRef.current = null;
|
||||
return true;
|
||||
}, []);
|
||||
const firstSignInDraftRef = useRef<string | null>(null);
|
||||
const trackFirstSignInDraft = useCallback((connection: Pick<ToolConnection, "id" | "status"> | undefined) => {
|
||||
firstSignInDraftRef.current = connection?.status === "draft" && !resumeConnectionId && !reconnectConnectionId && !connectionIntentId
|
||||
? connection.id
|
||||
: null;
|
||||
}, [connectionIntentId, reconnectConnectionId, resumeConnectionId]);
|
||||
const [cancellingSignIn, setCancellingSignIn] = useState(false);
|
||||
const cancelFirstSignInDraft = useCallback(async (): Promise<boolean> => {
|
||||
const connectionId = firstSignInDraftRef.current;
|
||||
if (!connectionId || !selectedCompanyId) return true;
|
||||
setCancellingSignIn(true);
|
||||
try {
|
||||
await toolsApi.cancelFirstSignIn(connectionId);
|
||||
} catch (error) {
|
||||
pushToast({ title: "Couldn’t cancel sign-in", body: `${describeError(error).body} Click Cancel to try again.`, tone: "error" });
|
||||
return false;
|
||||
} finally {
|
||||
setCancellingSignIn(false);
|
||||
}
|
||||
firstSignInDraftRef.current = null;
|
||||
setConnectResult((current) => current?.connectionId === connectionId ? null : current);
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.tools.applications(selectedCompanyId) });
|
||||
return true;
|
||||
}, [pushToast, queryClient, selectedCompanyId]);
|
||||
useEffect(() => {
|
||||
if (pendingOAuthLookupRef.current && pendingOAuthLookupRef.current.scope !== oauthLookupScope) {
|
||||
cancelOAuthLookup();
|
||||
@@ -1516,6 +1541,7 @@ function StandardConnectionSetupFlow({
|
||||
});
|
||||
const mutateOAuthStart = oauthStartMutation.mutate;
|
||||
const startOAuth = useCallback((connection: ToolConnection) => {
|
||||
trackFirstSignInDraft(connection);
|
||||
if (connection.config?.sourceTemplateKey === "google-workspace" && !workspaceSelectionRef.current) {
|
||||
setWorkspaceConnection(connection);
|
||||
setWorkspaceConsent(() => () => {
|
||||
@@ -1530,7 +1556,7 @@ function StandardConnectionSetupFlow({
|
||||
reserveOAuthPopup();
|
||||
if (!connectionIntentId) setDialogOAuthConnectionId(connection.id);
|
||||
mutateOAuthStart(connection);
|
||||
}, [mutateOAuthStart, onPhaseChange, reserveOAuthPopup, host, connectionIntentId]);
|
||||
}, [mutateOAuthStart, onPhaseChange, reserveOAuthPopup, host, connectionIntentId, trackFirstSignInDraft]);
|
||||
|
||||
/**
|
||||
* Commit the Access step's agent reach for a connection. Shared by the
|
||||
@@ -1691,6 +1717,7 @@ function StandardConnectionSetupFlow({
|
||||
setGenericOAuthPending(!entry);
|
||||
const startUrl = result.auth.startUrl?.trim();
|
||||
if (startUrl && !connectionIntentId) {
|
||||
trackFirstSignInDraft(result.connection);
|
||||
setDialogOAuthConnectionId(result.connectionId);
|
||||
void prepareAndOpenOAuth({ authorizationUrl: startUrl, handoff: result.auth.handoff });
|
||||
} else startOAuth(result.connection);
|
||||
@@ -2471,6 +2498,7 @@ function StandardConnectionSetupFlow({
|
||||
defaults={curatedOAuthDefaults}
|
||||
settingsValid={additionalSettingsValid && instructionsValid}
|
||||
onOpenAuthorization={openAuthorizationTab}
|
||||
cancelling={cancellingSignIn}
|
||||
onRetry={async () => {
|
||||
if (pendingOAuthLookupRef.current) return;
|
||||
directOAuthAccessConfirmedRef.current = true;
|
||||
@@ -2558,9 +2586,11 @@ function StandardConnectionSetupFlow({
|
||||
setOAuthError(null);
|
||||
backToGallery();
|
||||
}}
|
||||
onCancel={() => {
|
||||
onCancel={async () => {
|
||||
if (cancellingSignIn) return;
|
||||
cancelOAuthLookup();
|
||||
oauthHandoffAbortRef.current?.abort();
|
||||
if (!await cancelFirstSignInDraft()) return;
|
||||
(onCancel ?? (() => navigate("/apps")))();
|
||||
}}
|
||||
/>
|
||||
@@ -2585,6 +2615,7 @@ function StandardConnectionSetupFlow({
|
||||
authorizationUrl={authorizationFallbackUrl}
|
||||
defaults={connectionDefaults}
|
||||
onOpenAuthorization={openAuthorizationTab}
|
||||
cancelling={cancellingSignIn}
|
||||
onRetry={() => {
|
||||
setOAuthError(null);
|
||||
const connection = connectResult?.connection;
|
||||
@@ -2604,9 +2635,11 @@ function StandardConnectionSetupFlow({
|
||||
setOAuthPhase("entry");
|
||||
setOAuthError(null);
|
||||
}}
|
||||
onCancel={() => {
|
||||
onCancel={async () => {
|
||||
if (cancellingSignIn) return;
|
||||
cancelOAuthLookup();
|
||||
oauthHandoffAbortRef.current?.abort();
|
||||
if (!await cancelFirstSignInDraft()) return;
|
||||
(onCancel ?? (() => navigate("/apps")))();
|
||||
}}
|
||||
/>
|
||||
@@ -3028,6 +3061,7 @@ export function OAuthConnectStateScreen({
|
||||
defaults,
|
||||
onRetry,
|
||||
settingsValid = true,
|
||||
cancelling = false,
|
||||
onOpenAuthorization,
|
||||
onBack,
|
||||
onCancel,
|
||||
@@ -3060,6 +3094,7 @@ export function OAuthConnectStateScreen({
|
||||
/** The stated default and its Advanced disclosure (PAP-659 C0). */
|
||||
defaults?: ReactNode;
|
||||
settingsValid?: boolean;
|
||||
cancelling?: boolean;
|
||||
onOpenAuthorization?: () => void;
|
||||
onRetry: () => void;
|
||||
onBack: () => void;
|
||||
@@ -3147,7 +3182,7 @@ export function OAuthConnectStateScreen({
|
||||
|
||||
<div className="mt-6 flex items-center gap-2">
|
||||
{phase === "error" || phase === "entry" ? (
|
||||
<Button type="button" onClick={onRetry} disabled={!settingsValid}>
|
||||
<Button type="button" onClick={onRetry} disabled={!settingsValid || cancelling}>
|
||||
{phase === "entry"
|
||||
? resuming ? `Finish with ${serverName}` : `Continue to ${serverName}`
|
||||
: "Try again"}
|
||||
@@ -3159,7 +3194,7 @@ export function OAuthConnectStateScreen({
|
||||
</Button>
|
||||
)}
|
||||
{authorizationUrl ? <Button variant="outline" asChild><a href={authorizationUrl} target="_blank" rel="noopener noreferrer" onClick={onOpenAuthorization}>Open sign-in in a new tab</a></Button> : null}
|
||||
<Button type="button" variant="ghost" onClick={onBack}>Back</Button>
|
||||
<Button type="button" variant="ghost" onClick={onBack} disabled={cancelling}>Back</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -136,6 +136,7 @@ const ACTIVITY_ROW_VERBS: Record<string, string> = {
|
||||
"tool_connection.created": "created",
|
||||
"tool_connection.updated": "updated",
|
||||
"tool_connection.archived": "removed",
|
||||
"tool_connection.sign_in_cancelled": "cancelled sign-in for",
|
||||
"tool_connection.catalog_refresh": "refreshed actions for",
|
||||
"tool_connection.installs_synced": "changed agent installs for",
|
||||
"tool_connection.install_access_extended": "extended agent access for",
|
||||
|
||||
@@ -33,6 +33,7 @@ const getConnectionMock = vi.hoisted(() => vi.fn());
|
||||
const getConnectionInstallsMock = vi.hoisted(() => vi.fn());
|
||||
const connectAppMock = vi.hoisted(() => vi.fn());
|
||||
const startOAuthMock = vi.hoisted(() => vi.fn());
|
||||
const cancelFirstSignInMock = vi.hoisted(() => vi.fn());
|
||||
const finishAppMock = vi.hoisted(() => vi.fn());
|
||||
const getAwsSetupMock = vi.hoisted(() => vi.fn());
|
||||
const putConnectionInstallsMock = vi.hoisted(() => vi.fn());
|
||||
@@ -98,6 +99,7 @@ vi.mock("@/api/tools", () => ({
|
||||
connectApp: (companyId: string, input: unknown) => connectAppMock(companyId, input),
|
||||
getAwsSetup: (connectionId: string, accessLevel?: string) => getAwsSetupMock(connectionId, accessLevel),
|
||||
startOAuth: (connectionId: string, input?: unknown) => startOAuthMock(connectionId, input),
|
||||
cancelFirstSignIn: (connectionId: string) => cancelFirstSignInMock(connectionId),
|
||||
finishApp: (companyId: string, connectionId: string, input: unknown) =>
|
||||
finishAppMock(companyId, connectionId, input),
|
||||
putConnectionInstalls: (connectionId: string, installs: unknown) =>
|
||||
@@ -2344,6 +2346,71 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it("removes the unfinished connection when Google sign-in is cancelled", async () => {
|
||||
experimentalMock.mockResolvedValue({ enableGoogleWorkspaceConnector: true });
|
||||
mockSearch.value = "source=google-workspace&stage=setup";
|
||||
const workspace = getAppStoreDefinition("google-workspace")!;
|
||||
listGalleryMock.mockResolvedValue({ apps: [{
|
||||
...workspace, ownershipAvailability: { ...workspace.ownershipAvailability, platform_shared: true },
|
||||
}] });
|
||||
const draft = { id: "workspace-draft", applicationId: "app-workspace", authKind: "oauth", credentialPolicy: "shared", status: "draft",
|
||||
enabled: false, config: { sourceTemplateKey: "google-workspace", connectionMethodKey: "paperclip-workspace" }, transportConfig: {} };
|
||||
connectAppMock.mockResolvedValue({ connectionId: draft.id, connection: draft, catalog: [],
|
||||
auth: { kind: "oauth", startUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=fixture" } });
|
||||
cancelFirstSignInMock.mockResolvedValue({ abandoned: true, connection: { ...draft, status: "archived" } });
|
||||
await render();
|
||||
await act(async () => buttonByText("Continue to sign in")!.click());
|
||||
await flushReact();
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
await act(async () => {
|
||||
Array.from(dialog.querySelectorAll("button")).find(button => button.textContent === "Continue")!.click();
|
||||
});
|
||||
await flushReact();
|
||||
expect(connectAppMock).toHaveBeenCalledTimes(1);
|
||||
expect(container.textContent).toContain("Opening Google Workspace");
|
||||
await act(async () => buttonByText("Cancel")!.click());
|
||||
await flushReact();
|
||||
expect(cancelFirstSignInMock).toHaveBeenCalledExactlyOnceWith("workspace-draft");
|
||||
expect(mockNavigate).toHaveBeenCalledWith("/apps");
|
||||
});
|
||||
|
||||
it("stays on the sign-in page and lets Cancel retry when the cancel request fails", async () => {
|
||||
experimentalMock.mockResolvedValue({ enableGoogleWorkspaceConnector: true });
|
||||
mockSearch.value = "source=google-workspace&stage=setup";
|
||||
const workspace = getAppStoreDefinition("google-workspace")!;
|
||||
listGalleryMock.mockResolvedValue({ apps: [{
|
||||
...workspace, ownershipAvailability: { ...workspace.ownershipAvailability, platform_shared: true },
|
||||
}] });
|
||||
const draft = { id: "workspace-draft", applicationId: "app-workspace", authKind: "oauth", credentialPolicy: "shared", status: "draft",
|
||||
enabled: false, config: { sourceTemplateKey: "google-workspace", connectionMethodKey: "paperclip-workspace" }, transportConfig: {} };
|
||||
connectAppMock.mockResolvedValue({ connectionId: draft.id, connection: draft, catalog: [],
|
||||
auth: { kind: "oauth", startUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=fixture" } });
|
||||
let failCancel!: (error: Error) => void;
|
||||
cancelFirstSignInMock.mockImplementationOnce(() => new Promise((_resolve, reject) => { failCancel = reject; }))
|
||||
.mockResolvedValueOnce({ abandoned: true, connection: { ...draft, status: "archived" } });
|
||||
await render();
|
||||
await act(async () => buttonByText("Continue to sign in")!.click());
|
||||
await flushReact();
|
||||
const dialog = document.querySelector('[role="dialog"]')!;
|
||||
await act(async () => {
|
||||
Array.from(dialog.querySelectorAll("button")).find(button => button.textContent === "Continue")!.click();
|
||||
});
|
||||
await flushReact();
|
||||
await act(async () => buttonByText("Cancel")!.click());
|
||||
await flushReact();
|
||||
expect(buttonByText("Back")?.disabled).toBe(true);
|
||||
await act(async () => failCancel(new Error("Network unavailable")));
|
||||
await flushReact();
|
||||
expect(buttonByText("Back")?.disabled).toBe(false);
|
||||
expect(mockNavigate).not.toHaveBeenCalledWith("/apps");
|
||||
expect(container.textContent).toContain("Opening Google Workspace");
|
||||
await act(async () => buttonByText("Cancel")!.click());
|
||||
await flushReact();
|
||||
expect(cancelFirstSignInMock).toHaveBeenCalledTimes(2);
|
||||
expect(cancelFirstSignInMock).toHaveBeenLastCalledWith("workspace-draft");
|
||||
expect(mockNavigate).toHaveBeenCalledWith("/apps");
|
||||
});
|
||||
|
||||
it("renders Google Calendar as one minimal, unboxed setup screen", async () => {
|
||||
mockParams.appKey = "google-calendar";
|
||||
listGalleryMock.mockResolvedValue({ apps: [GOOGLE_CALENDAR] });
|
||||
|
||||
@@ -4,7 +4,7 @@ import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { focusManager, QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { Browse } from "./Browse";
|
||||
import { Browse, pendingFirstSignInOnlyApplicationIds } from "./Browse";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { aiConnectionRouterAppDefinition, CONNECTABLE_APP_DEFINITIONS, getAppStoreDefinition } from "@paperclipai/shared";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
@@ -1581,6 +1581,48 @@ describe("Connectors landing page", () => {
|
||||
expect(notion.textContent).toContain("draft@example.com");
|
||||
});
|
||||
|
||||
it("does not list a connection whose first sign-in never finished", async () => {
|
||||
listApplicationsMock.mockResolvedValue({ applications: [application()] });
|
||||
listConnectionsMock.mockResolvedValue({
|
||||
connections: [connection(), connection({ id: "conn-cancelled", name: "cancelled@example.com", status: "draft", firstSignInPending: true })],
|
||||
});
|
||||
await renderBrowse();
|
||||
const notion = container.querySelector<HTMLElement>('[data-app-slug="notion"]')!;
|
||||
expect(notion.textContent).toContain("devinfoley@gmail.com");
|
||||
expect(notion.textContent).not.toContain("cancelled@example.com");
|
||||
expect(notion.textContent).not.toContain("needs attention");
|
||||
expect(notion.textContent).not.toContain("2 connections");
|
||||
});
|
||||
|
||||
it("finds apps with only unfinished sign-ins in one pass over a large list", () => {
|
||||
const connections = Array.from({ length: 5000 }, (_, index) => ({
|
||||
applicationId: `app-${index % 2500}`,
|
||||
status: index < 2500 ? "draft" as const : "active" as const,
|
||||
firstSignInPending: index < 2500 || undefined,
|
||||
}));
|
||||
connections.push({ applicationId: "app-only-pending", status: "draft", firstSignInPending: true });
|
||||
let reads = 0;
|
||||
const counted = new Proxy(connections, {
|
||||
get(target, key, receiver) {
|
||||
if (typeof key === "string" && /^\d+$/.test(key)) reads += 1;
|
||||
return Reflect.get(target, key, receiver);
|
||||
},
|
||||
});
|
||||
expect([...pendingFirstSignInOnlyApplicationIds(counted)]).toEqual(["app-only-pending"]);
|
||||
expect(reads).toBeLessThanOrEqual(connections.length);
|
||||
});
|
||||
|
||||
it("does not list a custom app whose only connection never finished its first sign-in", async () => {
|
||||
listApplicationsMock.mockResolvedValue({ applications: [application({ id: "app-custom", name: "Abandoned server",
|
||||
applicationKey: "app-gallery:link:one", status: "draft", metadata: { source: "link" } })] });
|
||||
listConnectionsMock.mockResolvedValue({
|
||||
connections: [connection({ id: "conn-custom", applicationId: "app-custom", name: "Abandoned server", status: "draft",
|
||||
firstSignInPending: true, config: {} })],
|
||||
});
|
||||
await renderBrowse();
|
||||
expect(container.textContent).not.toContain("Abandoned server");
|
||||
});
|
||||
|
||||
it.each(["provider_setup", "identity_link", undefined, "complete"])(
|
||||
"keeps unfinished verifying chat setup visible for step %s", async (step) => {
|
||||
chatListMock.mockResolvedValue([
|
||||
|
||||
@@ -288,6 +288,19 @@ function upstreamAccountState(connection: ToolConnection, snapshot: UpstreamAppS
|
||||
: { kind: "attention", label: "Needs sign-in", message: "Sign in again to restore access." };
|
||||
}
|
||||
|
||||
export function pendingFirstSignInOnlyApplicationIds(
|
||||
connections: readonly Pick<ToolConnection, "applicationId" | "status" | "firstSignInPending">[],
|
||||
): Set<string> {
|
||||
const pending = new Set<string>();
|
||||
const listed = new Set<string>();
|
||||
for (const connection of connections) {
|
||||
if (connection.firstSignInPending) pending.add(connection.applicationId);
|
||||
else if (connection.status !== "archived") listed.add(connection.applicationId);
|
||||
}
|
||||
for (const applicationId of listed) pending.delete(applicationId);
|
||||
return pending;
|
||||
}
|
||||
|
||||
function connectionRank(connection: ToolConnection): number {
|
||||
return connection.status === "draft" ? 0 : 1;
|
||||
}
|
||||
@@ -620,13 +633,16 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
|
||||
const activeConnections = (connectionsQuery.data?.connections ?? []).filter(
|
||||
(connection) =>
|
||||
connection.status !== "archived" &&
|
||||
!connection.firstSignInPending &&
|
||||
connection.connectionPurpose !== "channel",
|
||||
);
|
||||
const pendingOnlyApplicationIds = pendingFirstSignInOnlyApplicationIds(connectionsQuery.data?.connections ?? []);
|
||||
const activeApplications = (
|
||||
applicationsQuery.data?.applications ?? []
|
||||
).filter(
|
||||
(application) =>
|
||||
application.status !== "archived" &&
|
||||
!pendingOnlyApplicationIds.has(application.id) &&
|
||||
application.type !== "chat" &&
|
||||
application.metadata?.purpose !== "channel",
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user