mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 16:29:42 +01:00
fix(connections): explain failed app sign-ins and guide GitHub app install (#22234)
## 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
06750cb18e
commit
bb258a5429
7 files changed
+314
-9
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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: "</script><b>",
|
||||
});
|
||||
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",
|
||||
|
||||
@@ -193,19 +193,48 @@ export function filterVisibleToolConnections<T extends {
|
||||
|| Boolean(actor.userId && connection.createdByUserId === actor.userId));
|
||||
}
|
||||
|
||||
const OAUTH_FAILURE_CODE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
||||
|
||||
function githubRecoveryLink(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "https:" && url.hostname.toLowerCase() === "github.com" && !url.username && !url.password
|
||||
? url.toString()
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function githubInstallationRecovery(code: string | null | undefined, details: Record<string, unknown> | 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(/</g, "\\u003c");
|
||||
const issuePath = input.issueId
|
||||
? `/issues/${encodeURIComponent(input.issueId)}`
|
||||
@@ -336,6 +365,8 @@ export function toolAccessRoutes(
|
||||
issueId: string | null;
|
||||
outcome: "connected" | "declined" | "failed";
|
||||
openerOrigin?: string | null;
|
||||
code?: string | null;
|
||||
recovery?: { installationUrl: string | null; managementUrl: string | null } | null;
|
||||
},
|
||||
) {
|
||||
res.type("html").send(connectionIntentOAuthOutcomeHtml(input));
|
||||
@@ -1298,6 +1329,15 @@ function connectorEnrollmentPrincipal(req: Request): string {
|
||||
const claimId = typeof req.query.claim_id === "string" ? req.query.claim_id : null;
|
||||
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 OAuth state");
|
||||
}
|
||||
@@ -1375,6 +1415,23 @@ function connectorEnrollmentPrincipal(req: Request): string {
|
||||
const details = callbackError instanceof HttpError && callbackError.details && typeof callbackError.details === "object"
|
||||
? callbackError.details as Record<string, unknown>
|
||||
: 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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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: "<script>" })).toBeNull();
|
||||
expect(readConnectionIntentOAuthFailureCode(null)).toBeNull();
|
||||
const fallback = oauthFailureMessage("oauth_callback_http_500");
|
||||
expect(fallback).toBe("Authorization did not complete. Try again when you’re ready.");
|
||||
expect(fallback).not.toContain("oauth_");
|
||||
});
|
||||
});
|
||||
|
||||
describe("missing sign-in state messages", () => {
|
||||
const missing = { type: "paperclip.connection-intent.oauth", outcome: "failed", code: "oauth_state_missing" };
|
||||
const activePopup = {} as Window;
|
||||
const oldPopup = {} as Window;
|
||||
const from = (data: unknown, source: Window | null, eventOrigin = origin) => ({ origin: eventOrigin, data, source });
|
||||
|
||||
it("accepts a missing-state failure from this setup's active sign-in window", () => {
|
||||
expect(isMissingOAuthStateMessage(from(missing, activePopup), origin, activePopup)).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores a missing-state failure from an old sign-in window", () => {
|
||||
expect(isMissingOAuthStateMessage(from(missing, oldPopup), origin, activePopup)).toBe(false);
|
||||
expect(isMissingOAuthStateMessage(from(missing, oldPopup), origin, null)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects other origins, other codes, and messages bound to an interaction", () => {
|
||||
expect(isMissingOAuthStateMessage(from(missing, activePopup, "https://evil.test"), origin, activePopup)).toBe(false);
|
||||
expect(isMissingOAuthStateMessage(from({ ...missing, code: "oauth_state_expired" }, activePopup), origin, activePopup)).toBe(false);
|
||||
expect(isMissingOAuthStateMessage(from({ ...missing, interactionId }, activePopup), origin, activePopup)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GitHub installation recovery from the sign-in window", () => {
|
||||
it("offers the install and manage links GitHub returned", () => {
|
||||
expect(readConnectionIntentGitHubRecovery({
|
||||
outcome: "failed",
|
||||
code: "github_installation_required",
|
||||
recovery: {
|
||||
installationUrl: "https://github.com/apps/paperclip-for-github/installations/new",
|
||||
managementUrl: "https://github.com/settings/installations",
|
||||
},
|
||||
})).toEqual({
|
||||
installationUrl: "https://github.com/apps/paperclip-for-github/installations/new",
|
||||
managementUrl: "https://github.com/settings/installations",
|
||||
});
|
||||
expect(oauthFailureMessage("github_installation_required")).toMatch(/Paperclip for GitHub app isn’t installed/);
|
||||
});
|
||||
|
||||
it("drops links that are not on github.com or belong to another failure", () => {
|
||||
expect(readConnectionIntentGitHubRecovery({
|
||||
code: "github_installation_required",
|
||||
recovery: { installationUrl: "https://evil.test/install", managementUrl: "javascript:alert(1)" },
|
||||
})).toBeNull();
|
||||
expect(readConnectionIntentGitHubRecovery({
|
||||
code: "oauth_state_expired",
|
||||
recovery: { installationUrl: "https://github.com/apps/paperclip-for-github/installations/new" },
|
||||
})).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -466,7 +466,7 @@ function recommendedManagedConnectorMethod(
|
||||
// One-method sign-in skips the access step. These providers' warnings (Railway
|
||||
// project scope, Circleback sharing outside the workspace) must still be read
|
||||
// before authorizing, so the sign-in screen repeats them.
|
||||
const SIGN_IN_GUIDANCE_SLUGS = new Set(["railway", "circleback"]);
|
||||
const SIGN_IN_GUIDANCE_SLUGS = new Set(["railway", "circleback", "github"]);
|
||||
|
||||
function canUseAutomaticOAuthFastPath(entry: AppDefinition | null | undefined): boolean {
|
||||
if (!entry) return false;
|
||||
@@ -554,6 +554,59 @@ export function readConnectionIntentOAuthOutcome(
|
||||
: null;
|
||||
}
|
||||
|
||||
export function readConnectionIntentGitHubRecovery(data: unknown): { installationUrl: string | null; managementUrl: string | null } | null {
|
||||
if (!data || typeof data !== "object") return null;
|
||||
const message = data as { code?: unknown; recovery?: unknown };
|
||||
if (message.code !== "github_installation_required" || !message.recovery || typeof message.recovery !== "object") return null;
|
||||
const recovery = message.recovery as { installationUrl?: unknown; managementUrl?: unknown };
|
||||
const installationUrl = githubRecoveryUrl(typeof recovery.installationUrl === "string" ? recovery.installationUrl : null);
|
||||
const managementUrl = githubRecoveryUrl(typeof recovery.managementUrl === "string" ? recovery.managementUrl : null);
|
||||
return installationUrl || managementUrl ? { installationUrl, managementUrl } : null;
|
||||
}
|
||||
|
||||
export function isMissingOAuthStateMessage(
|
||||
event: Pick<MessageEvent, "origin" | "data" | "source">,
|
||||
expectedOrigin: string,
|
||||
activePopup: Window | null,
|
||||
): boolean {
|
||||
if (!activePopup || event.source !== activePopup) return false;
|
||||
if (event.origin !== expectedOrigin || !event.data || typeof event.data !== "object") return false;
|
||||
const message = event.data as { type?: unknown; interactionId?: unknown; outcome?: unknown; code?: unknown };
|
||||
return message.type === "paperclip.connection-intent.oauth"
|
||||
&& message.interactionId === undefined
|
||||
&& message.outcome === "failed"
|
||||
&& message.code === "oauth_state_missing";
|
||||
}
|
||||
|
||||
export function readConnectionIntentOAuthFailureCode(data: unknown): string | null {
|
||||
if (!data || typeof data !== "object") return null;
|
||||
const code = (data as { code?: unknown }).code;
|
||||
return typeof code === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : null;
|
||||
}
|
||||
|
||||
export function oauthFailureMessage(code: string | null): string {
|
||||
switch (code) {
|
||||
case "oauth_state_expired":
|
||||
case "oauth_state_missing":
|
||||
return "The sign-in took too long or was already used. Try again and finish signing in within a few minutes.";
|
||||
case "oauth_session_mismatch":
|
||||
return "Sign-in finished in a different Paperclip session. Stay signed in to Paperclip in this browser and try again.";
|
||||
case "oauth_redirect_origin_unsupported":
|
||||
return "Sign-in returned to a different Paperclip address than the one you started from. Open Paperclip at its usual address and try again.";
|
||||
case "oauth_token_exchange_failed":
|
||||
case "oauth_token_endpoint_rejected":
|
||||
case "oauth_access_token_missing":
|
||||
return "The provider accepted your sign-in but didn’t give Paperclip access. Try again; if it keeps happening, check that your account or organization allows this app.";
|
||||
case "oauth_insufficient_scope":
|
||||
case "oauth_scope_grant_invalid":
|
||||
return "The provider didn’t grant the access Paperclip asked for. Try again and approve every requested permission.";
|
||||
case "github_installation_required":
|
||||
return "You signed in, but the Paperclip for GitHub app isn’t installed on any account you can use. Install it and choose at least one repository, then try again. An organization owner may need to approve the install.";
|
||||
default:
|
||||
return "Authorization did not complete. Try again when you’re ready.";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ConnectionSetupFlowProps {
|
||||
/** Optional settings composed into the standard credential form above its footer. */
|
||||
additionalSettings?: ReactNode;
|
||||
@@ -796,6 +849,7 @@ function StandardConnectionSetupFlow({
|
||||
if (!resumingAfterOAuthFailure) return null;
|
||||
return oauthCallbackErrorMessage(oauthCallbackOutcome, oauthCallbackCode);
|
||||
});
|
||||
const [intentGitHubRecovery, setIntentGitHubRecovery] = useState<{ installationUrl: string | null; managementUrl: string | null } | null>(null);
|
||||
/** Host of the page the operator is about to be sent to, shown while redirecting. */
|
||||
const [authorizationHost, setAuthorizationHost] = useState<string | null>(null);
|
||||
const directOAuthAccessConfirmedRef = useRef(false);
|
||||
@@ -869,6 +923,7 @@ function StandardConnectionSetupFlow({
|
||||
// proxy from window.open without opening a usable authorization tab.
|
||||
oauthPopupRef.current = null;
|
||||
setOAuthError(null);
|
||||
setIntentGitHubRecovery(null);
|
||||
setOAuthPhase("redirecting");
|
||||
onPhaseChange?.("authorizing");
|
||||
}, [onPhaseChange]);
|
||||
@@ -888,6 +943,7 @@ function StandardConnectionSetupFlow({
|
||||
const prepareAndOpenOAuth = useCallback(async (
|
||||
start: Pick<ToolOAuthStartResult, "authorizationUrl" | "handoff">,
|
||||
) => {
|
||||
setIntentGitHubRecovery(null);
|
||||
oauthHandoffAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
oauthHandoffAbortRef.current = controller;
|
||||
@@ -925,6 +981,11 @@ function StandardConnectionSetupFlow({
|
||||
let disposed = false;
|
||||
const receiveOAuthOutcome = async (event: MessageEvent) => {
|
||||
const outcome = readConnectionIntentOAuthOutcome(event, window.location.origin, connectionIntentId);
|
||||
if (!outcome && isMissingOAuthStateMessage(event, window.location.origin, oauthPopupRef.current)) {
|
||||
setOAuthPhase("error");
|
||||
setOAuthError(oauthFailureMessage("oauth_state_missing"));
|
||||
return;
|
||||
}
|
||||
if (outcome === "connected") {
|
||||
setOAuthPhase("entry");
|
||||
setAuthorizationFallbackUrl(null);
|
||||
@@ -952,7 +1013,8 @@ function StandardConnectionSetupFlow({
|
||||
}
|
||||
if (outcome !== "failed") return;
|
||||
setOAuthPhase("error");
|
||||
setOAuthError("Authorization did not complete. Try again when you’re ready.");
|
||||
setIntentGitHubRecovery(readConnectionIntentGitHubRecovery(event.data));
|
||||
setOAuthError(oauthFailureMessage(readConnectionIntentOAuthFailureCode(event.data)));
|
||||
};
|
||||
window.addEventListener("message", receiveOAuthOutcome);
|
||||
return () => { disposed = true; window.removeEventListener("message", receiveOAuthOutcome); };
|
||||
@@ -2359,7 +2421,7 @@ function StandardConnectionSetupFlow({
|
||||
recoveryActions={oauthCallbackCode === "github_installation_required" ? {
|
||||
installationUrl: githubInstallationUrl,
|
||||
managementUrl: githubManagementUrl,
|
||||
} : undefined}
|
||||
} : intentGitHubRecovery ?? undefined}
|
||||
authorizationHost={authorizationHost}
|
||||
authorizationUrl={authorizationFallbackUrl}
|
||||
guidance={entry && SIGN_IN_GUIDANCE_SLUGS.has(entry.slug) && accessStepMethod ? (
|
||||
|
||||
Reference in new issue
Block a user