diff --git a/docs/api/tool-connections.md b/docs/api/tool-connections.md index 70d327cf558..aac0c7e3a35 100644 --- a/docs/api/tool-connections.md +++ b/docs/api/tool-connections.md @@ -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 ``` diff --git a/packages/shared/src/types/tool-access.ts b/packages/shared/src/types/tool-access.ts index f8224dd6845..6c12f314791 100644 --- a/packages/shared/src/types/tool-access.ts +++ b/packages/shared/src/types/tool-access.ts @@ -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; diff --git a/server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts b/server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts new file mode 100644 index 00000000000..9444d4d3c66 --- /dev/null +++ b/server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts @@ -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>; + let db: ReturnType; + let keyDir: string; + let provider: Server; + let origin: string; + let holdToken: Promise | 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((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((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((resolve) => { release = resolve; }); + const requested = new Promise((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), 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), 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"); + }); +}); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index dbcfb955189..fb19671e80c 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -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", diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 6179917689d..8fd6fddca88 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -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, { diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index 4a3ab8874bb..ebd7cf72b7a 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -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, diff --git a/server/src/services/tool-access/connections/first-sign-in.ts b/server/src/services/tool-access/connections/first-sign-in.ts new file mode 100644 index 00000000000..33b0dcfa072 --- /dev/null +++ b/server/src/services/tool-access/connections/first-sign-in.ts @@ -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; + +const OAUTH_TOKEN_PATHS = new Set(["oauth.access_token", "oauth.refresh_token"]); +const SIGN_IN_CANCELLED = "oauth_sign_in_cancelled"; + +function signInCancelled(connection: Pick): boolean { + return connection.status === "disabled" && connection.lastError === SIGN_IN_CANCELLED; +} + +export function connectionRemovedOrSignInCancelled(connection: Pick): 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, +) { + 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; +}; + +async function grantEvidence(db: ToolAccessMutationDb, companyId: string, connectionIds: string[]): Promise { + 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(); + 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 }; +} diff --git a/server/src/services/tool-access/connections/removal.ts b/server/src/services/tool-access/connections/removal.ts index 3dd762ef663..f950801c4de 100644 --- a/server/src/services/tool-access/connections/removal.ts +++ b/server/src/services/tool-access/connections/removal.ts @@ -45,7 +45,7 @@ function asRecord(value: unknown): Record { 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", diff --git a/server/src/services/tool-access/oauth/access-finalization.ts b/server/src/services/tool-access/oauth/access-finalization.ts index 73cde903c8c..d150ff557e3 100644 --- a/server/src/services/tool-access/oauth/access-finalization.ts +++ b/server/src/services/tool-access/oauth/access-finalization.ts @@ -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; @@ -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) diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index c71cc3f100e..065eadae0c8 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -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" diff --git a/server/src/services/tool-access/oauth/client-credentials-service.ts b/server/src/services/tool-access/oauth/client-credentials-service.ts index 880fd550c93..49f7187feaf 100644 --- a/server/src/services/tool-access/oauth/client-credentials-service.ts +++ b/server/src/services/tool-access/oauth/client-credentials-service.ts @@ -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 = {}; diff --git a/server/src/services/tool-access/oauth/cloud-callback.ts b/server/src/services/tool-access/oauth/cloud-callback.ts index bfe6d1fc345..f58e5ec6d59 100644 --- a/server/src/services/tool-access/oauth/cloud-callback.ts +++ b/server/src/services/tool-access/oauth/cloud-callback.ts @@ -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 diff --git a/server/src/services/tool-access/oauth/direct-callback.ts b/server/src/services/tool-access/oauth/direct-callback.ts index 728a4d10087..2623f448049 100644 --- a/server/src/services/tool-access/oauth/direct-callback.ts +++ b/server/src/services/tool-access/oauth/direct-callback.ts @@ -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 }; diff --git a/server/src/services/tool-access/oauth/vercel-callback.ts b/server/src/services/tool-access/oauth/vercel-callback.ts index 543470a1a1d..65e2b406768 100644 --- a/server/src/services/tool-access/oauth/vercel-callback.ts +++ b/server/src/services/tool-access/oauth/vercel-callback.ts @@ -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, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 5a1ad2a90ea..9ed0c718053 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -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", diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.ts index 51b6bfa9897..39fe209533f 100644 --- a/ui/src/api/tools.ts +++ b/ui/src/api/tools.ts @@ -450,6 +450,8 @@ export const toolsApi = { api.delete( `/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(`/tool-connections/${connectionId}/stored-content`), deleteStoredContent: (connectionId: string) => diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx index fe402e9901c..110edcf9dee 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.tsx @@ -891,6 +891,31 @@ function StandardConnectionSetupFlow({ oauthPopupRef.current = null; return true; }, []); + const firstSignInDraftRef = useRef(null); + const trackFirstSignInDraft = useCallback((connection: Pick | 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 => { + 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({
{phase === "error" || phase === "entry" ? ( - )} {authorizationUrl ? : null} - +
diff --git a/ui/src/lib/activity-format.ts b/ui/src/lib/activity-format.ts index b2fd062c16d..19e9441bd47 100644 --- a/ui/src/lib/activity-format.ts +++ b/ui/src/lib/activity-format.ts @@ -136,6 +136,7 @@ const ACTIVITY_ROW_VERBS: Record = { "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", diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index 9ced25c9813..5935ef1a39f 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -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] }); diff --git a/ui/src/pages/apps/Browse.test.tsx b/ui/src/pages/apps/Browse.test.tsx index c7eb3dad542..f2049ec90ad 100644 --- a/ui/src/pages/apps/Browse.test.tsx +++ b/ui/src/pages/apps/Browse.test.tsx @@ -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('[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([ diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsx index 4ee152e2bb7..4d3fcabc7a3 100644 --- a/ui/src/pages/apps/Browse.tsx +++ b/ui/src/pages/apps/Browse.tsx @@ -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[], +): Set { + const pending = new Set(); + const listed = new Set(); + 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", );