From bb258a5429aa91a00389ed43af7285a60d7044aa Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:56:16 -0600 Subject: [PATCH] fix(connections): explain failed app sign-ins and guide GitHub app install (#22234) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents can ask a person to connect an app, such as GitHub, through a sign-in window > - When that sign-in fails, the server knows the reason and records it in the activity log > - The sign-in window tells the opener only "failed", so the person sees "Authorization did not complete" for every cause > - People cannot fix the problem themselves, and support cannot help without reading server data > - This pull request sends the safe failure code to the opener and shows plain copy for the common causes > - The benefit is that a person knows what to do next, such as to finish faster or to stay in the same session ## Linked Issues or Issue Description **What happened?** A user tried to connect GitHub from an agent request. The dialog showed "GitHub couldn't connect. Authorization did not complete. Try again when you're ready." The same text shows for every failure cause. **Expected behavior** The dialog should tell the user why sign-in failed and what to do next. **Steps to reproduce** 1. Start an app connection from an agent request. 2. Let the sign-in take longer than the state lifetime, or finish it in a different Paperclip session. 3. See the generic "Authorization did not complete" message. **Paperclip version or commit** `master` at 84a529df4f. **Deployment mode** Paperclip Cloud. The connection-intent sign-in path is the same in self-hosted deployments. ## What Changed - The connection-intent sign-in page now posts a `code` field with a `failed` outcome. Only codes that match `^[a-z][a-z0-9_]{0,63}$` are sent. Connected and declined outcomes send no code. - Both OAuth callback catch blocks pass their failure code to that page. - OAuth state errors now carry codes: `oauth_state_expired`, `oauth_state_missing` and `oauth_session_mismatch`. - The setup flow maps common codes to plain copy. Unknown codes keep the old generic text, and raw codes never show to the user. - The managed-connector callback now records `tool_app.oauth_failed` with the failure code. Before, it answered 200 and recorded nothing. - A callback whose state is already gone now answers an HTML request with a page that posts `oauth_state_missing`. The dialog accepts it only from its own active sign-in window. - GitHub: before sign-in, the setup explains that Paperclip connects through the Paperclip for GitHub app and which account to install it on. - GitHub: when sign-in finds no usable installation, the sign-in window passes the GitHub install and manage links (github.com only) to the dialog. The dialog shows "Install Paperclip on GitHub" and "Manage repositories on GitHub" next to "Try again". ## Verification - `server`: `npx vitest run src/routes/tool-access-connection-intent.test.ts src/__tests__/generic-mcp-connection.test.ts` (126 passed). A new test checks that a safe code is posted, an unsafe code is dropped, and a connected outcome has no code. - `server`: `npx vitest run src/__tests__/tool-access-oauth-protocol.integration.test.ts -t "missing sign-in state"` covers the missing-state page on both callbacks. - `ui`: `npx vitest run src/features/connections/` (130 passed). Tests cover the GitHub install links, which drop non-github.com links, and missing-state messages from an old window. - `ui`: earlier run `npx vitest run src/features/connections/ConnectionSetupFlow.oauth.test.ts` (21 passed). New tests check the copy for expired and cross-session sign-in, and that unknown codes show the generic text. ## Risks - Low risk. The postMessage adds one optional field. Old openers ignore it. - The state errors now include `details.code`. The status codes and messages do not change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 - [ ] 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 --- .../shared/src/app-definitions/github.json | 2 +- ...-access-oauth-protocol.integration.test.ts | 24 ++++++ .../tool-access-connection-intent.test.ts | 57 +++++++++++++ server/src/routes/tool-access.ts | 83 ++++++++++++++++++- .../src/services/tool-access/oauth/state.ts | 10 ++- .../ConnectionSetupFlow.oauth.test.ts | 79 ++++++++++++++++++ .../connections/ConnectionSetupFlow.tsx | 68 ++++++++++++++- 7 files changed, 314 insertions(+), 9 deletions(-) diff --git a/packages/shared/src/app-definitions/github.json b/packages/shared/src/app-definitions/github.json index 1e7b359b584..9eb13cfb65c 100644 --- a/packages/shared/src/app-definitions/github.json +++ b/packages/shared/src/app-definitions/github.json @@ -28,7 +28,7 @@ "defaults": { "serverUrl": "https://api.githubcopilot.com/mcp/" }, - "guidanceMd": "Authorize Paperclip, then choose selected repositories in GitHub. You can edit repository access later from GitHub's installation settings.", + "guidanceMd": "Paperclip connects through the Paperclip for GitHub app. Sign in to GitHub, then install the app on the account or organization that owns your repositories and choose which repositories agents can use. An organization owner may need to approve the install. You can change repository access later in GitHub's installation settings.", "riskTier": "S3", "label": "Connect GitHub", "purpose": "tool", diff --git a/server/src/__tests__/tool-access-oauth-protocol.integration.test.ts b/server/src/__tests__/tool-access-oauth-protocol.integration.test.ts index 484d3dad919..c74279f6ebd 100644 --- a/server/src/__tests__/tool-access-oauth-protocol.integration.test.ts +++ b/server/src/__tests__/tool-access-oauth-protocol.integration.test.ts @@ -42,6 +42,30 @@ describe("tool OAuth over local HTTP", () => { if (keyDir) await rm(keyDir, { recursive: true, force: true }); }); + it.each([ + "/api/tools/oauth/callback", + "/api/tools/oauth/cloud-connector/callback", + ])("explains a missing sign-in state to the waiting dialog at %s", async (path) => { + const app = express(); + app.use((req, _res, next) => { + req.actor = { type: "board", userId: `oauth-user-${randomUUID()}`, source: "local_implicit", isInstanceAdmin: true }; + next(); + }); + app.use("/api", toolAccessRoutes(db, { deploymentMode: "local_trusted", deploymentExposure: "private", paperclipCloudConnector: null })); + app.use(errorHandler); + + const page = await request(app).get(path) + .set("accept", "text/html") + .query({ state: `gone-${randomUUID()}`, claim_id: "claim" }) + .expect(200); + expect(page.headers["content-type"]).toContain("text/html"); + expect(page.text).toContain('"outcome":"failed"'); + expect(page.text).toContain('"code":"oauth_state_missing"'); + expect(page.text).not.toContain('"interactionId"'); + + await request(app).get(path).query({ state: `gone-${randomUUID()}` }).expect(400); + }); + it.each([ { authMethod: "none", grantKind: "organization", scopeMode: "omitted_initial" }, { authMethod: "client_secret_basic", grantKind: "organization", scopeMode: "omitted_refresh" }, diff --git a/server/src/routes/tool-access-connection-intent.test.ts b/server/src/routes/tool-access-connection-intent.test.ts index 6948eaa2114..87cc1ada458 100644 --- a/server/src/routes/tool-access-connection-intent.test.ts +++ b/server/src/routes/tool-access-connection-intent.test.ts @@ -3,6 +3,7 @@ import { cloudConnectorEnrollmentReturnPath, cloudConnectorEnrollmentOutcomeHtml, connectionIntentOAuthOutcomeHtml, + githubInstallationRecovery, } from "./tool-access.js"; describe("Cloud connector enrollment return path", () => { @@ -83,6 +84,62 @@ describe("connection intent OAuth callback document", () => { }, ); + it("tells the opener why a failed sign-in failed, using only safe codes", () => { + const failed = connectionIntentOAuthOutcomeHtml({ + interactionId: "interaction-123", + issueId: null, + outcome: "failed", + code: "oauth_state_expired", + }); + expect(failed).toContain('"code":"oauth_state_expired"'); + + const unsafe = connectionIntentOAuthOutcomeHtml({ + interactionId: "interaction-123", + issueId: null, + outcome: "failed", + code: "", + }); + expect(unsafe).not.toContain('"code"'); + + const connected = connectionIntentOAuthOutcomeHtml({ + interactionId: "interaction-123", + issueId: null, + outcome: "connected", + code: "oauth_state_expired", + }); + expect(connected).not.toContain('"code"'); + }); + + it("sends GitHub install links only for a missing GitHub installation", () => { + const recovery = githubInstallationRecovery("github_installation_required", { + installationUrl: "https://github.com/apps/paperclip-for-github/installations/new", + managementUrl: "https://evil.test/settings", + }); + expect(recovery).toEqual({ + installationUrl: "https://github.com/apps/paperclip-for-github/installations/new", + managementUrl: null, + }); + expect(githubInstallationRecovery("oauth_state_expired", { installationUrl: "https://github.com/x" })).toBeNull(); + + const html = connectionIntentOAuthOutcomeHtml({ + interactionId: "interaction-123", + issueId: null, + outcome: "failed", + code: "github_installation_required", + recovery, + }); + expect(html).toContain('"recovery":{"installationUrl":"https://github.com/apps/paperclip-for-github/installations/new","managementUrl":null}'); + + const other = connectionIntentOAuthOutcomeHtml({ + interactionId: "interaction-123", + issueId: null, + outcome: "failed", + code: "oauth_state_expired", + recovery, + }); + expect(other).not.toContain('"recovery"'); + }); + it("can return a localhost callback outcome to the numeric-loopback opener", () => { const html = connectionIntentOAuthOutcomeHtml({ interactionId: "interaction-123", diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 2ac4ed49052..a52fd32f7bb 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -193,19 +193,48 @@ export function filterVisibleToolConnections | null) { + if (code !== "github_installation_required" || !details) return null; + const installationUrl = githubRecoveryLink(details.installationUrl); + const managementUrl = githubRecoveryLink(details.managementUrl); + return installationUrl || managementUrl ? { installationUrl, managementUrl } : null; +} + export function connectionIntentOAuthOutcomeHtml(input: { - interactionId: string; + interactionId: string | null; issueId: string | null; outcome: "connected" | "declined" | "failed"; openerOrigin?: string | null; + code?: string | null; + recovery?: { installationUrl: string | null; managementUrl: string | null } | null; }) { // The callback window is only a signal. Connection identity and every // authorization URL stay server-side; the opener refreshes the task from the // interaction id instead of trusting provider-window data. const message = JSON.stringify({ type: "paperclip.connection-intent.oauth", - interactionId: input.interactionId, + ...(input.interactionId ? { interactionId: input.interactionId } : {}), outcome: input.outcome, + ...(input.outcome === "failed" && input.code && OAUTH_FAILURE_CODE_PATTERN.test(input.code) + ? { code: input.code } + : {}), + ...(input.outcome === "failed" && input.code === "github_installation_required" && input.recovery + ? { recovery: input.recovery } + : {}), }).replace(/ : null; + await logActivity(db, { + companyId: pendingState.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "tool_app.oauth_failed", + entityType: "tool_connection", + entityId: pendingState.connectionId, + details: { + code: typeof details?.code === "string" + ? details.code + : callbackError instanceof HttpError ? `oauth_callback_http_${callbackError.status}` : "oauth_callback_failed", + status: callbackError instanceof HttpError ? callbackError.status : 500, + message: callbackError instanceof HttpError + ? callbackError.message + : "OAuth callback failed unexpectedly.", + }, + }); if (pendingConnectionIntent && pendingState.interactionId && req.actor.userId) { const outcome = details?.code === "oauth_authorization_denied" ? "declined" : "failed"; await finishConnectionIntentOAuth({ @@ -1389,6 +1446,8 @@ function connectorEnrollmentPrincipal(req: Request): string { issueId: pendingState.issueId, outcome, openerOrigin: pendingState.returnTo, + code: typeof details?.code === "string" ? details.code : null, + recovery: githubInstallationRecovery(typeof details?.code === "string" ? details.code : null, details), }); return; } @@ -1412,6 +1471,15 @@ function connectorEnrollmentPrincipal(req: Request): string { const state = typeof req.query.state === "string" ? req.query.state : ""; const error = typeof req.query.error === "string" ? req.query.error : null; const pendingState = state ? await svc.peekOAuthState(state) : null; + if (!pendingState && req.get("accept")?.includes("text/html") === true) { + res.type("html").send(connectionIntentOAuthOutcomeHtml({ + interactionId: null, + issueId: null, + outcome: "failed", + code: "oauth_state_missing", + })); + return; + } if (!pendingState || !hasCompanyAccess(req, pendingState.companyId)) { throw badRequest("Invalid or expired Vercel Connect state"); } @@ -1511,6 +1579,15 @@ function connectorEnrollmentPrincipal(req: Request): string { // `error` code to its own copy instead of reflecting them (PAP-17108). const iss = typeof req.query.iss === "string" ? req.query.iss : null; const pendingState = state ? await svc.peekOAuthState(state) : null; + if (!pendingState && req.get("accept")?.includes("text/html") === true) { + res.type("html").send(connectionIntentOAuthOutcomeHtml({ + interactionId: null, + issueId: null, + outcome: "failed", + code: "oauth_state_missing", + })); + return; + } if (!pendingState || !hasCompanyAccess(req, pendingState.companyId)) { throw badRequest("Invalid or expired OAuth state"); } @@ -1589,6 +1666,8 @@ function connectorEnrollmentPrincipal(req: Request): string { issueId: pendingState.issueId, outcome, openerOrigin: pendingState.returnTo, + code: callbackFailureCode, + recovery: githubInstallationRecovery(callbackErrorCode, details), }); return; } diff --git a/server/src/services/tool-access/oauth/state.ts b/server/src/services/tool-access/oauth/state.ts index 694c03e35ca..3909829ab74 100644 --- a/server/src/services/tool-access/oauth/state.ts +++ b/server/src/services/tool-access/oauth/state.ts @@ -29,6 +29,7 @@ function assertSameOAuthActor( if (!expected.actorType || !expected.actorId) { throw forbidden( "OAuth sign-in state is not bound to an authenticated board session", + { code: "oauth_session_mismatch" }, ); } if ( @@ -37,11 +38,13 @@ function assertSameOAuthActor( ) { throw forbidden( "OAuth sign-in must be completed by the user who started it", + { code: "oauth_session_mismatch" }, ); } if (expected.sessionId && expected.sessionId !== actual.sessionId) { throw forbidden( "OAuth sign-in must be completed from the same authenticated session", + { code: "oauth_session_mismatch" }, ); } } @@ -75,9 +78,9 @@ async function validateOAuthState( .where(eq(toolOauthStates.state, state)) .limit(1); if (!stateRow) - throw badRequest("OAuth state was not found or has already been used"); + throw badRequest("OAuth state was not found or has already been used", { code: "oauth_state_missing" }); if (stateRow.expiresAt.getTime() <= Date.now()) - throw badRequest("OAuth state has expired"); + throw badRequest("OAuth state has expired", { code: "oauth_state_expired" }); if (stateRow.subjectUserId) { if ( actor?.actorType !== "user" || @@ -85,6 +88,7 @@ async function validateOAuthState( ) { throw forbidden( "OAuth callback user does not match the requested subject", + { code: "oauth_session_mismatch" }, ); } } else { @@ -108,7 +112,7 @@ async function consumeOAuthState( .where(eq(toolOauthStates.state, state)) .returning(); if (!consumed) - throw badRequest("OAuth state was not found or has already been used"); + throw badRequest("OAuth state was not found or has already been used", { code: "oauth_state_missing" }); return consumed; } diff --git a/ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts b/ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts index 8b7da25a7fb..ba2526c13d7 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts +++ b/ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts @@ -6,6 +6,10 @@ import { getConnectableAppDefinition } from "@paperclipai/shared"; import { isConnectionDefinitionUnavailable, isVercelConnectUnavailable, + isMissingOAuthStateMessage, + oauthFailureMessage, + readConnectionIntentGitHubRecovery, + readConnectionIntentOAuthFailureCode, readConnectionIntentOAuthOutcome, retainedResumeMatches, retainedReconnectMatches, @@ -264,3 +268,78 @@ describe("retained reconnect target matching", () => { })).toBe(false); }); }); + +describe("connection intent OAuth failure reasons", () => { + it("explains an expired sign-in instead of a generic failure", () => { + const code = readConnectionIntentOAuthFailureCode({ + type: "paperclip.connection-intent.oauth", + interactionId, + outcome: "failed", + code: "oauth_state_expired", + }); + expect(code).toBe("oauth_state_expired"); + expect(oauthFailureMessage(code)).toMatch(/took too long/); + }); + + it("explains a sign-in finished in another Paperclip session", () => { + expect(oauthFailureMessage("oauth_session_mismatch")).toMatch(/different Paperclip session/); + }); + + it("ignores malformed codes and never shows a raw code", () => { + expect(readConnectionIntentOAuthFailureCode({ code: "