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: "