fix(connections): use Slack MCP user OAuth flow and surface OAuth errors in setup UI (#22976)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Apps and Connections let operators connect external providers
through remote MCP servers and OAuth.
> - Slack's curated `mcp-oauth` method pins Slack's bot install
endpoints (`oauth/v2/authorize` and `oauth.v2.access`) while sending
user-only scopes (`search:read.public`, `search:read.private`, etc.) in
`scope`, so Slack rejects sign-in with `"Invalid permissions
requested"`.
> - In addition, when OAuth fails or returns an error for a
customer-owned OAuth app like Slack, `ConnectionSetupFlow`'s `KeyStep`
drops `oauthError` completely, hiding the failure banner, and
`OAuthClientFields` hides the method's `guidanceMd` prerequisites.
> - This pull request switches Slack's `mcp-oauth` method to Slack's
documented MCP user OAuth endpoints (`oauth/v2_user/authorize` and
`oauth.v2.user.access`), propagates allowlisted RFC OAuth
`providerError` codes without reflecting untrusted provider prose,
displays OAuth errors and popup fallback links on `KeyStep`, and renders
setup prerequisites (`guidanceMd`) beside customer OAuth fields.
> - The benefit is that customer-owned Slack MCP sign-in succeeds
(including when resuming pre-fix drafts) and any OAuth error or Slack
MCP prerequisite is clearly shown to the user.

## Linked Issues or Issue Description

Fixes: #13935
Refs #17258
Refs #14037

Builds on #17258 (`fix/slack-mcp-user-oauth-flow`) and adds the missing
customer-OAuth error surface and setup guidance in
`ConnectionSetupFlow`.

## What Changed

- Updated `packages/shared/src/app-definitions/slack.json` and
`scripts/ingest-app-definitions.mjs` so Slack's `mcp-oauth` method uses
`https://slack.com/oauth/v2_user/authorize` and
`https://slack.com/api/oauth.v2.user.access`, and added Slack MCP
prerequisites (`User Token Scopes`, callback URL, and `Model Context
Protocol`) to `guidanceMd`.
- Updated `server/src/routes/tool-access.ts` to propagate allowlisted
RFC `providerError` codes (`normalizeOAuthProviderError`, excluding
`unrecognized`) via `provider_error` on OAuth recovery redirects and
connection-intent postMessages, while continuing to never read or
reflect untrusted `error_description` or `error_uri`.
- Updated `ui/src/features/connections/ConnectionSetupFlow.tsx` and
`ui/src/lib/oauthWindowOutcome.ts` so:
- `KeyStep` renders `oauthError` (not only `connectMutation.error`) and
the `"Open sign-in in a new tab"` fallback link when popups are blocked.
- `oauthCallbackErrorMessage` and `oauthFailureMessage` map allowlisted
`providerError` values (such as `invalid_scope`, `invalid_redirect_uri`,
`invalid_client`) and Paperclip failure codes (including
`slack_mcp_access_disabled`) to actionable Paperclip-authored copy.
- Opener popup polling reads same-origin failure `code` and
`provider_error` details from the returned callback URL.
- `OAuthClientFields` renders `method.guidanceMd` for required
customer-owned OAuth apps whose client secret is optional.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for the
changed `@paperclipai/shared` sources.
- Updated Slack OAuth test fixtures in
`server/src/__tests__/tool-access-service.test.ts` and
`server/src/services/tool-access/oauth/client-settings.test.ts`, and
added regressions in `packages/shared/src/app-definitions.test.ts`,
`server/src/__tests__/tool-access-service.test.ts`,
`ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts`, and
`ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx`.

## Verification

- Shared, UI, and OAuth client-settings unit + DOM tests (95/95 passed):
- `pnpm exec vitest run packages/shared/src/app-definitions.test.ts
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx
ui/src/features/connections/ConnectionSetupFlow.architecture.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts`
- Embedded-Postgres server OAuth start + legacy-draft upgrade + callback
error redirect + redaction tests:
- `pnpm exec vitest run server/src/__tests__/tool-access-service.test.ts
-t "uses Slack user OAuth endpoints even for legacy drafts|starts OAuth
from|refreshes|personal|slack"` (33 passed)
- `pnpm exec vitest run
server/src/__tests__/generic-mcp-connection.test.ts -t "returns browser
denials|denied and cancelled callbacks|redacts"` (9 passed)
- Typechecks & guardrails:
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` (all passed)
- `node scripts/check-test-budget.mjs --files
packages/shared/src/app-definitions.test.ts
server/src/__tests__/tool-access-service.test.ts
server/src/services/tool-access/oauth/client-settings.test.ts
ui/src/features/connections/ConnectionSetupFlow.oauth.test.ts
ui/src/features/connections/ConnectionSetupFlow.slack-oauth.test.tsx`
(PASS)
- `pnpm verify --base 2d06567795
--explain` (exit 2 due to `scripts/ingest-app-definitions.mjs` being a
global CI input; `tests/runner-e2e/source-sdk-public-inputs.json`
verified in sync; sharded PR CI supplies broad repo coverage).

## Risks

- Low risk. The endpoint change applies only to Slack's `mcp-oauth` tool
method; Slack chat-channel setup and Slack search OAuth retain their
existing bot/user flows.
- Resuming a pre-fix Slack MCP draft automatically re-resolves the
updated `v2_user` endpoints from the catalog definition during
`startOAuth` and overwrites the stored bot URLs.
- Only allowlisted RFC OAuth error codes (`normalizeOAuthProviderError`)
are forwarded in `provider_error`; untrusted provider
`error_description` and `error_uri` values are never read or echoed.

## Model Used

- Claude Opus 4.6 by Anthropic (in Antigravity with tool use, shell
execution, and file editing). Used for root-cause analysis, test-driven
implementation, and local verification.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-11-25 15:33:26 -06:00
1 parent f9ee58c214
commit 38e3a71669
12 files changed
+699 -106

No files matched your search

@@ -1673,3 +1673,13 @@ it("limits explicit DCR registration preference to remote MCP OAuth methods with
nonMcp.methods[0]!.transport = "rest_api";
expect(appDefinitionSchema.safeParse(nonMcp).success).toBe(false);
});
it("uses Slack MCP user OAuth endpoints and includes user-scope and MCP prerequisites", () => {
const slack = getConnectableAppDefinition("slack")!;
const mcpOAuth = slack.methods.find((method) => method.key === "mcp-oauth")!;
expect(mcpOAuth.defaults?.authorizationEndpoint).toBe("https://slack.com/oauth/v2_user/authorize");
expect(mcpOAuth.defaults?.tokenEndpoint).toBe("https://slack.com/api/oauth.v2.user.access");
expect(mcpOAuth.defaults?.scopesHint).toContain("search:read.public");
expect(mcpOAuth.guidanceMd).toContain("User Token Scopes");
expect(mcpOAuth.guidanceMd).toContain("Model Context Protocol");
});
@@ -28,8 +28,8 @@
},
"defaults": {
"serverUrl": "https://mcp.slack.com/mcp",
"authorizationEndpoint": "https://slack.com/oauth/v2/authorize",
"tokenEndpoint": "https://slack.com/api/oauth.v2.access",
"authorizationEndpoint": "https://slack.com/oauth/v2_user/authorize",
"tokenEndpoint": "https://slack.com/api/oauth.v2.user.access",
"scopesHint": [
"canvases:read",
"canvases:write",
@@ -63,7 +63,7 @@
"users:read.email"
]
},
"guidanceMd": "Connect a Slack workspace and limit access to the channels agents need.",
"guidanceMd": "In your Slack app settings, add Paperclip's callback URL under OAuth & Permissions, add the requested scopes under User Token Scopes (not Bot Token Scopes), and enable Model Context Protocol under Features → Agents & AI Apps.",
"riskTier": "S3",
"label": "Use this connection as an agent tool",
"purpose": "tool",
+35 -4
View File
@@ -356,12 +356,43 @@ const apps = [
"oauth",
{
serverUrl: "https://mcp.slack.com/mcp",
authorizationEndpoint: "https://slack.com/oauth/v2/authorize",
tokenEndpoint: "https://slack.com/api/oauth.v2.access",
scopesHint: ["channels:read", "chat:write", "search:read"],
authorizationEndpoint: "https://slack.com/oauth/v2_user/authorize",
tokenEndpoint: "https://slack.com/api/oauth.v2.user.access",
scopesHint: [
"canvases:read",
"canvases:write",
"channels:history",
"channels:read",
"channels:write",
"chat:write",
"emoji:read",
"files:read",
"files:write",
"groups:history",
"groups:read",
"groups:write",
"im:history",
"im:read",
"im:write",
"lists:read",
"lists:write",
"mpim:history",
"mpim:read",
"mpim:write",
"reactions:read",
"reactions:write",
"search:read.files",
"search:read.im",
"search:read.mpim",
"search:read.private",
"search:read.public",
"search:read.users",
"users:read",
"users:read.email",
],
},
"S3",
"Connect a Slack workspace and limit access to the channels agents need.",
"In your Slack app settings, add Paperclip's callback URL under OAuth & Permissions, add the requested scopes under User Token Scopes (not Bot Token Scopes), and enable Model Context Protocol under Features → Agents & AI Apps.",
{
label: "Use this connection as an agent tool",
purpose: "tool",
+131 -23
View File
@@ -10592,7 +10592,7 @@ describeEmbeddedPostgres("tool access service", () => {
let gatewayAuthorization: string | null = null;
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
return {
ok: true,
status: 200,
@@ -10743,7 +10743,7 @@ describeEmbeddedPostgres("tool access service", () => {
);
vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
return {
ok: true,
status: 200,
@@ -10896,7 +10896,7 @@ describeEmbeddedPostgres("tool access service", () => {
).searchParams.get("state")!;
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
const userAuthorization =
body.get("code") === "user-authorization-code";
@@ -11221,7 +11221,7 @@ describeEmbeddedPostgres("tool access service", () => {
);
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const code = (init?.body as URLSearchParams).get("code");
expect(["personal-code", "personal-reconnect-code"]).toContain(code);
const reconnecting = code === "personal-reconnect-code";
@@ -11565,7 +11565,7 @@ describeEmbeddedPostgres("tool access service", () => {
if (mode === "managed") definition.ownershipAvailability = { ...availability, platform_shared: true };
let discoverNewTool = false;
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
if (String(url) === "https://slack.com/api/oauth.v2.access") return mcpHttpResponse(oauthToken("fixture-access-token", "fixture-refresh-token"));
if (String(url) === "https://slack.com/api/oauth.v2.user.access") return mcpHttpResponse(oauthToken("fixture-access-token", "fixture-refresh-token"));
const body = JSON.parse(String(init?.body));
if (body.method === "notifications/initialized") return new Response(null, { status: 202 });
return mcpHttpResponse({ jsonrpc: "2.0", id: body.id, result: body.method === "initialize" ? { protocolVersion: "2025-06-18" }
@@ -11649,7 +11649,7 @@ describeEmbeddedPostgres("tool access service", () => {
const redirectUri = "https://paperclip.example/api/tools/oauth/callback";
vi.spyOn(globalThis, "fetch").mockImplementation(async url => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") return mcpHttpResponse(oauthToken("fixture-access-token", "fixture-refresh-token"));
if (href === "https://slack.com/api/oauth.v2.user.access") return mcpHttpResponse(oauthToken("fixture-access-token", "fixture-refresh-token"));
if (href === "https://mcp.slack.com/mcp") return mcpHttpResponse(catalogResponse([{ name: "search_messages", annotations: { readOnlyHint: true } }]));
throw new Error(`unexpected fetch ${href}`);
});
@@ -11715,7 +11715,7 @@ describeEmbeddedPostgres("tool access service", () => {
let discoverNewTool = false;
vi.spyOn(globalThis, "fetch").mockImplementation(async url => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") return mcpHttpResponse(oauthToken("fixture-access-token", "fixture-refresh-token"));
if (href === "https://slack.com/api/oauth.v2.user.access") return mcpHttpResponse(oauthToken("fixture-access-token", "fixture-refresh-token"));
if (href === "https://mcp.slack.com/mcp") return mcpHttpResponse(catalogResponse([{ name: "search_messages", annotations: { readOnlyHint: true } }, ...(discoverNewTool ? [{ name: "new_search", annotations: { readOnlyHint: true } }] : [])]));
throw new Error(`unexpected fetch ${href}`);
});
@@ -11792,7 +11792,7 @@ describeEmbeddedPostgres("tool access service", () => {
);
vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
return mcpHttpResponse(oauthToken("share-access-token", "share-refresh-token"));
}
if (href === "https://mcp.slack.com/mcp") {
@@ -11931,7 +11931,7 @@ describeEmbeddedPostgres("tool access service", () => {
.spyOn(globalThis, "fetch")
.mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
if (body.get("grant_type") === "refresh_token") {
expect(body.get("refresh_token")).toBe("personal-refresh-token");
@@ -12052,7 +12052,7 @@ describeEmbeddedPostgres("tool access service", () => {
);
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
if (body.get("grant_type") === "refresh_token") {
return mcpHttpResponse({
@@ -12263,7 +12263,7 @@ describeEmbeddedPostgres("tool access service", () => {
let tokenScope: string | null = null;
vi.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
return mcpHttpResponse({
ok: true,
access_token: `access-${randomUUID()}`,
@@ -12398,7 +12398,7 @@ describeEmbeddedPostgres("tool access service", () => {
let refreshScope: string | null = null;
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
return body.get("grant_type") === "refresh_token"
? slackToken(refreshScope)
@@ -13051,7 +13051,7 @@ describeEmbeddedPostgres("tool access service", () => {
});
const startUrl = new URL(connectRes.body.auth.startUrl);
expect(`${startUrl.origin}${startUrl.pathname}`).toBe(
"https://slack.com/oauth/v2/authorize",
"https://slack.com/oauth/v2_user/authorize",
);
expect(startUrl.searchParams.get("client_id")).toBe("slack-client-id");
expect(startUrl.searchParams.get("code_challenge_method")).toBe("S256");
@@ -13078,7 +13078,7 @@ describeEmbeddedPostgres("tool access service", () => {
.spyOn(globalThis, "fetch")
.mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
expect(body.get("grant_type")).toBe("authorization_code");
expect(body.get("code")).toBe("oauth-code");
@@ -13190,6 +13190,114 @@ describeEmbeddedPostgres("tool access service", () => {
},
);
it("uses Slack user OAuth endpoints even for legacy drafts and propagates allowlisted provider_error without reflecting error_description", async () => {
const origin = "https://paperclip.example";
vi.stubEnv("PAPERCLIP_PUBLIC_URL", origin);
const company = await createCompany(db);
await grantBoardUser(db, company.id, "board-user", [
"tools:manage_connections",
]);
const app = createRouteApp(db);
const connectRes = await request(app)
.post(`/api/companies/${company.id}/tools/apps/connect`)
.set("Host", "paperclip.example")
.set("Origin", origin)
.send({
galleryKey: "slack",
name: "Slack user OAuth",
oauthClient: {
clientId: "slack-customer-id",
clientSecret: "slack-customer-secret",
},
})
.expect(201);
const initialStartUrl = new URL(connectRes.body.auth.startUrl);
expect(`${initialStartUrl.origin}${initialStartUrl.pathname}`).toBe(
"https://slack.com/oauth/v2_user/authorize",
);
expect(initialStartUrl.searchParams.get("scope")?.split(" ")).toContain(
"search:read.public",
);
const [existingDraft] = await db
.select()
.from(toolConnections)
.where(eq(toolConnections.id, connectRes.body.connectionId));
const legacyOAuth = {
...((existingDraft!.config.oauth as Record<string, unknown>) ?? {}),
authorizationUrl: "https://slack.com/oauth/v2/authorize",
tokenUrl: "https://slack.com/api/oauth.v2.access",
};
await db
.update(toolConnections)
.set({
config: { ...existingDraft!.config, oauth: legacyOAuth },
transportConfig: { ...existingDraft!.transportConfig, oauth: legacyOAuth },
})
.where(eq(toolConnections.id, connectRes.body.connectionId));
const retryStartRes = await request(app)
.post(`/api/tools/oauth/${connectRes.body.connectionId}/start`)
.set("Host", "paperclip.example")
.set("Origin", origin)
.send({})
.expect(200);
const retryUrl = new URL(retryStartRes.body.authorizationUrl);
expect(`${retryUrl.origin}${retryUrl.pathname}`).toBe(
"https://slack.com/oauth/v2_user/authorize",
);
const retryState = retryUrl.searchParams.get("state")!;
const failedCallbackRes = await request(app)
.get("/api/tools/oauth/callback")
.set("Host", "paperclip.example")
.set("Accept", "text/html")
.query({
state: retryState,
error: "invalid_scope",
error_description: "Invalid permissions requested (untrusted-canary)",
});
expect(failedCallbackRes.status).toBe(303);
const recoveryLocation = new URL(failedCallbackRes.headers.location, origin);
expect(recoveryLocation.pathname).toBe(`/${company.issuePrefix}/apps/connect`);
expect(recoveryLocation.searchParams.get("source")).toBe("slack");
expect(recoveryLocation.searchParams.get("resume")).toBe(connectRes.body.connectionId);
expect(recoveryLocation.searchParams.get("oauth")).toBe("denied");
expect(recoveryLocation.searchParams.get("code")).toBe("oauth_authorization_denied");
expect(recoveryLocation.searchParams.get("provider_error")).toBe("invalid_scope");
expect(failedCallbackRes.headers.location).not.toContain("untrusted-canary");
expect(failedCallbackRes.headers.location).not.toContain("error_description");
const unlistedStartRes = await request(app)
.post(`/api/tools/oauth/${connectRes.body.connectionId}/start`)
.set("Host", "paperclip.example")
.set("Origin", origin)
.send({})
.expect(200);
const unlistedState = new URL(unlistedStartRes.body.authorizationUrl).searchParams.get("state")!;
const unlistedCallbackRes = await request(app)
.get("/api/tools/oauth/callback")
.set("Host", "paperclip.example")
.set("Accept", "text/html")
.query({
state: unlistedState,
error: "evil_unlisted_code",
error_description: "unlisted-canary",
});
expect(unlistedCallbackRes.status).toBe(303);
const unlistedRecoveryLocation = new URL(unlistedCallbackRes.headers.location, origin);
expect(unlistedRecoveryLocation.searchParams.get("oauth")).toBe("denied");
expect(unlistedRecoveryLocation.searchParams.get("code")).toBe("oauth_authorization_denied");
expect(unlistedRecoveryLocation.searchParams.get("provider_error")).toBeNull();
expect(unlistedCallbackRes.headers.location).not.toContain("evil_unlisted_code");
expect(unlistedCallbackRes.headers.location).not.toContain("unlisted-canary");
});
it("normalizes a direct numeric loopback origin for OAuth when no public URL is configured", async () => {
vi.stubEnv("PAPERCLIP_PUBLIC_URL", "");
vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "slack-client-id");
@@ -13581,7 +13689,7 @@ describeEmbeddedPostgres("tool access service", () => {
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
expect(body.get("grant_type")).toBe("authorization_code");
expect(body.get("code")).toBe("oauth-code");
@@ -14988,7 +15096,7 @@ describeEmbeddedPostgres("tool access service", () => {
let refreshCallCount = 0;
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
if (body.get("grant_type") === "authorization_code") {
return {
@@ -15112,7 +15220,7 @@ describeEmbeddedPostgres("tool access service", () => {
.spyOn(globalThis, "fetch")
.mockImplementation(async (url) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
return mcpHttpResponse(oauthToken("expired-access-token", "single-use-refresh-token"));
}
if (href === "https://mcp.slack.com/mcp") {
@@ -15140,7 +15248,7 @@ describeEmbeddedPostgres("tool access service", () => {
let refreshCallCount = 0;
fetchMock.mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
expect(body.get("grant_type")).toBe("refresh_token");
expect(body.get("refresh_token")).toBe("single-use-refresh-token");
@@ -15222,7 +15330,7 @@ describeEmbeddedPostgres("tool access service", () => {
.spyOn(globalThis, "fetch")
.mockImplementation(async (url) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
return mcpHttpResponse(oauthToken("expired-access-token", "submitted-refresh-token"));
}
if (href === "https://mcp.slack.com/mcp") {
@@ -15253,7 +15361,7 @@ describeEmbeddedPostgres("tool access service", () => {
fetchMock.mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = init?.body as URLSearchParams;
expect(body.get("refresh_token")).toBe("submitted-refresh-token");
await secretService(db).rotate(refreshRef.secretId, {
@@ -15366,7 +15474,7 @@ describeEmbeddedPostgres("tool access service", () => {
const tokenRequests: Array<{ url: string; clientId: string | null; clientSecret: string | null }> = [];
vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
const body = new URLSearchParams(String(init?.body ?? ""));
tokenRequests.push({ url: href, clientId: body.get("client_id"), clientSecret: body.get("client_secret") });
return { ok: true, status: 200, json: async () => ({ access_token: "deployment-access", refresh_token: "deployment-refresh", expires_in: 3600 }) } as Response;
@@ -15385,7 +15493,7 @@ describeEmbeddedPostgres("tool access service", () => {
redirectUri: "https://paperclip.example/api/tools/oauth/callback",
actor: { actorType: "user", actorId: userId },
});
expect(tokenRequests).toEqual([{ url: "https://slack.com/api/oauth.v2.access", clientId: "slack-deployment-id", clientSecret: "slack-deployment-secret" }]);
expect(tokenRequests).toEqual([{ url: "https://slack.com/api/oauth.v2.user.access", clientId: "slack-deployment-id", clientSecret: "slack-deployment-secret" }]);
});
it("never sends a deployment OAuth client to a machine-to-machine token endpoint of a custom server", async () => {
@@ -15450,7 +15558,7 @@ describeEmbeddedPostgres("tool access service", () => {
.spyOn(globalThis, "fetch")
.mockImplementation(async (url) => {
const href = String(url);
if (href === "https://slack.com/api/oauth.v2.access") {
if (href === "https://slack.com/api/oauth.v2.user.access") {
return {
ok: true,
json: async () => ({
+19
View File
@@ -1,4 +1,5 @@
import { isCrossSiteOAuthCallbackNavigation, oauthCallbackInterstitialHtml } from "../lib/oauth-browser-return.js";
import { normalizeOAuthProviderError } from "../services/tool-access/oauth/provider-errors.js";
import { aiConnectionRouterPluginKey, isSamePaperclipInstance, paperclipPeerFromMcpUrl } from "@paperclipai/shared";
import { aiConnectionRouterService } from "../services/ai-connection-router.js";
import { loadPluginAppCatalog } from "../services/plugin-app-catalog.js";
@@ -218,17 +219,24 @@ export function githubInstallationRecovery(code: string | null | undefined, deta
return installationUrl || managementUrl ? { installationUrl, managementUrl } : null;
}
function safeOAuthProviderErrorCode(value: unknown): string | null {
const normalized = normalizeOAuthProviderError(value);
return normalized && normalized !== "unrecognized" ? normalized : null;
}
export function connectionIntentOAuthOutcomeHtml(input: {
interactionId: string | null;
issueId: string | null;
outcome: "connected" | "declined" | "failed";
openerOrigin?: string | null;
code?: string | null;
providerError?: 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 safeProviderError = input.outcome === "connected" ? null : safeOAuthProviderErrorCode(input.providerError);
const message = JSON.stringify({
type: "paperclip.connection-intent.oauth",
...(input.interactionId ? { interactionId: input.interactionId } : {}),
@@ -236,6 +244,7 @@ export function connectionIntentOAuthOutcomeHtml(input: {
...(input.outcome === "failed" && input.code && OAUTH_FAILURE_CODE_PATTERN.test(input.code)
? { code: input.code }
: {}),
...(safeProviderError ? { providerError: safeProviderError } : {}),
...(input.outcome === "failed" && input.code === "github_installation_required" && input.recovery
? { recovery: input.recovery }
: {}),
@@ -370,6 +379,7 @@ export function toolAccessRoutes(
outcome: "connected" | "declined" | "failed";
openerOrigin?: string | null;
code?: string | null;
providerError?: string | null;
recovery?: { installationUrl: string | null; managementUrl: string | null } | null;
},
) {
@@ -561,10 +571,13 @@ function connectorEnrollmentPrincipal(req: Request): string {
outcome: "failed" | "denied",
code?: string | null,
providerRecovery?: { installationUrl?: unknown; managementUrl?: unknown },
providerError?: string | null,
) {
const detailPermissionsPath = await oauthAppPath(connection.companyId, connection.id);
const params = new URLSearchParams({ oauth: outcome });
if (code) params.set("code", code);
const safeProviderError = safeOAuthProviderErrorCode(providerError);
if (safeProviderError) params.set("provider_error", safeProviderError);
const addGitHubRecoveryUrls = (target: URLSearchParams) => {
if (code !== "github_installation_required") return;
for (const [key, value] of [
@@ -598,6 +611,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
oauth: outcome,
});
if (code) setupParams.set("code", code);
if (safeProviderError) setupParams.set("provider_error", safeProviderError);
addGitHubRecoveryUrls(setupParams);
const setupRoute = connection.credentialSource === "vercel_connect"
? "/apps/vercel-connect"
@@ -1658,6 +1672,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
? callbackError.details as Record<string, unknown>
: null;
const callbackErrorCode = typeof details?.code === "string" ? details.code : null;
const callbackProviderError = safeOAuthProviderErrorCode(details?.providerError);
const callbackFailureCode = callbackErrorCode
?? (callbackError instanceof HttpError ? `oauth_callback_http_${callbackError.status}` : "oauth_callback_failed");
await logActivity(db, {
@@ -1669,6 +1684,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
entityId: pendingState.connectionId,
details: {
code: callbackFailureCode,
...(callbackProviderError ? { providerError: callbackProviderError } : {}),
status: callbackError instanceof HttpError ? callbackError.status : 500,
// HttpError messages are Paperclip-authored. Provider-authored
// error_description/error_uri values are never read above and cannot
@@ -1693,6 +1709,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
outcome,
openerOrigin: pendingState.returnTo,
code: callbackFailureCode,
providerError: callbackProviderError,
recovery: githubInstallationRecovery(callbackErrorCode, details),
});
return;
@@ -1701,6 +1718,8 @@ function connectorEnrollmentPrincipal(req: Request): string {
pendingConnection,
callbackErrorCode === "oauth_authorization_denied" ? "denied" : "failed",
callbackFailureCode,
undefined,
callbackProviderError,
));
return;
}
@@ -30,7 +30,7 @@ describe("instance OAuth clients", () => {
vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id");
vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_SECRET", "instance-slack-secret");
expect(configuredOAuthClientForConnection(slack(), "slack", "https://slack.com/api/oauth.v2.access")).toMatchObject({
expect(configuredOAuthClientForConnection(slack(), "slack", "https://slack.com/api/oauth.v2.user.access")).toMatchObject({
clientId: "instance-slack-id",
clientSecret: "instance-slack-secret",
});
@@ -38,9 +38,9 @@ describe("instance OAuth clients", () => {
it.each([
["a different host", "https://attacker.example/token"],
["a lookalike path on the vendor host", "https://slack.com/api/oauth.v2.access/../../collect"],
["plain http on the vendor host", "http://slack.com/api/oauth.v2.access"],
["a vendor subdomain", "https://evil.slack.com/api/oauth.v2.access"],
["a lookalike path on the vendor host", "https://slack.com/api/oauth.v2.user.access/../../collect"],
["plain http on the vendor host", "http://slack.com/api/oauth.v2.user.access"],
["a vendor subdomain", "https://evil.slack.com/api/oauth.v2.user.access"],
["no token endpoint", null],
])("never returns the instance secret for %s", (_label, tokenUrl) => {
vi.stubEnv("PAPERCLIP_TOOL_OAUTH_SLACK_CLIENT_ID", "instance-slack-id");
@@ -94,7 +94,7 @@ describe("instance OAuth clients", () => {
expect(client.clientId).toBeNull();
expect(client.clientSecret).toBeNull();
}
expect(configuredOAuthClientForConnection(marked, "slack", "https://slack.com/api/oauth.v2.access").clientId).toBeNull();
expect(configuredOAuthClientForConnection(marked, "slack", "https://slack.com/api/oauth.v2.user.access").clientId).toBeNull();
});
it("never uses one app's instance client for a connection that claims another provider", () => {
@@ -78,7 +78,7 @@
"packages/shared/src/app-definitions-url.test.ts": "56792d6745a5bc7eafc36e7403f4c9bbd671ae99",
"packages/shared/src/app-definitions.generated.ts": "b162e9621fab029951d77a6b4605ab7893904a3a",
"packages/shared/src/app-definitions.ingestion-report.json": "a7b60c7c16a484a411989315e9f08d48258fa647",
"packages/shared/src/app-definitions.test.ts": "ff3bdaec0840b1aff109ce0928aa3eacb4d27032",
"packages/shared/src/app-definitions.test.ts": "269e1c82f377bab004c00765ba51543922315172",
"packages/shared/src/app-definitions.ts": "f8c9c3aa66ea3bbe38c3a2eff7abca9a25911c83",
"packages/shared/src/app-definitions/1password.json": "c11a4777de2c78805b2d391da5eb075a9511e0f8",
"packages/shared/src/app-definitions/agentmail.json": "edd0799b1980d0f5f43b89c8f7a1173dc623f7fa",
@@ -171,7 +171,7 @@
"packages/shared/src/app-definitions/sentry.json": "0afeca8c0e76be5d8324fa6d18fb970a38bb2b88",
"packages/shared/src/app-definitions/shopify.json": "f6bff7db55083d96060d8bd46a08aa38b33c3080",
"packages/shared/src/app-definitions/similarweb.json": "37a912287b7ad323cf783eb32d01b943a93e83fd",
"packages/shared/src/app-definitions/slack.json": "733de01cdeec0dc66d732639925c9bb9fb7dc53d",
"packages/shared/src/app-definitions/slack.json": "0a3e028d0c729f1448be06eaff3a7b51f08b194d",
"packages/shared/src/app-definitions/speko.json": "6f25f776269b435e8cbde3c3249d35d3063156ce",
"packages/shared/src/app-definitions/stripe.json": "708fb6d3498dbb57902dd5ebc45c8fded5d6b578",
"packages/shared/src/app-definitions/supabase.json": "9a92a2f30af01e1c9f4cebdf7d4ba0101353c1c6",
@@ -3,13 +3,16 @@
import { describe, expect, it } from "vitest";
import type { ToolApplication, ToolConnection } from "@paperclipai/shared";
import { getConnectableAppDefinition } from "@paperclipai/shared";
import { readOAuthWindowFailureDetails, readOAuthWindowOutcome } from "@/lib/oauthWindowOutcome";
import {
isConnectionDefinitionUnavailable,
isVercelConnectUnavailable,
isMissingOAuthStateMessage,
oauthCallbackErrorMessage,
oauthFailureMessage,
readConnectionIntentGitHubRecovery,
readConnectionIntentOAuthFailureCode,
readConnectionIntentOAuthProviderError,
readConnectionIntentOAuthOutcome,
retainedResumeMatches,
retainedReconnectMatches,
@@ -350,10 +353,61 @@ describe("connection intent OAuth failure reasons", () => {
it("ignores malformed codes and never shows a raw code", () => {
expect(readConnectionIntentOAuthFailureCode({ code: "<script>" })).toBeNull();
expect(readConnectionIntentOAuthFailureCode(null)).toBeNull();
expect(readConnectionIntentOAuthProviderError({ providerError: "<script>" })).toBeNull();
expect(readConnectionIntentOAuthProviderError({ providerError: "invalid_scope" })).toBe("invalid_scope");
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_");
});
it("maps allowlisted callback providerError and Slack MCP error codes to actionable Paperclip copy", () => {
expect(oauthCallbackErrorMessage("denied", "oauth_authorization_denied", "invalid_scope"))
.toMatch(/rejected the requested permissions/i);
expect(oauthCallbackErrorMessage("denied", "oauth_authorization_denied", "invalid_redirect_uri"))
.toMatch(/rejected Paperclip’s callback URL/i);
expect(oauthCallbackErrorMessage("failed", "slack_mcp_access_disabled"))
.toMatch(/Slack MCP access is disabled/i);
expect(oauthCallbackErrorMessage("failed", "oauth_token_exchange_failed"))
.toMatch(/didn’t give Paperclip access/i);
expect(oauthCallbackErrorMessage("denied", "oauth_authorization_denied", "access_denied"))
.toBe("Authorization was cancelled or declined. Your saved connection was not changed.");
expect(oauthCallbackErrorMessage("failed", "unknown_raw_code", "attacker_raw_text"))
.toBe("Authorization did not complete. Your saved connection is still here, so you can try again.");
for (const inheritedKey of ["__proto__", "constructor", "toString", "valueOf"]) {
expect(readConnectionIntentOAuthProviderError({ providerError: inheritedKey })).toBeNull();
expect(oauthFailureMessage(null, inheritedKey)).toBe("Authorization did not complete. Try again when you’re ready.");
expect(oauthCallbackErrorMessage("denied", "oauth_authorization_denied", inheritedKey))
.toBe("Authorization was cancelled or declined. Your saved connection was not changed.");
}
});
it("reads same-origin OAuth window failure details only for the matching connection", () => {
const sameOriginPopup = (href: string, closed = false) =>
({ closed, location: { href } }) as unknown as Window;
const failedPopup = sameOriginPopup(
`${window.location.origin}/ACM/apps/connect?source=slack&resume=conn-1&oauth=denied&code=oauth_authorization_denied&provider_error=invalid_scope`,
);
expect(readOAuthWindowOutcome(failedPopup, "conn-1")).toBe("denied");
expect(readOAuthWindowFailureDetails(failedPopup, "conn-1")).toEqual({
code: "oauth_authorization_denied",
providerError: "invalid_scope",
});
expect(readOAuthWindowFailureDetails(failedPopup, "conn-other")).toBeNull();
expect(
readOAuthWindowFailureDetails(
sameOriginPopup("https://evil.example/ACM/apps/connect?resume=conn-1&oauth=failed&code=oauth_state_expired"),
"conn-1",
),
).toBeNull();
expect(
readOAuthWindowFailureDetails(
sameOriginPopup(`${window.location.origin}/ACM/apps/conn-1/permissions?success=1`),
"conn-1",
),
).toBeNull();
});
});
describe("missing sign-in state messages", () => {
@@ -0,0 +1,249 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { getConnectableAppDefinition, type ToolApplication, type ToolConnection } from "@paperclipai/shared";
import { ConnectionSetupFlow } from "./ConnectionSetupFlow";
const fixture = vi.hoisted(() => ({
companyId: "company-1",
search: "",
params: {} as Record<string, string | undefined>,
navigate: vi.fn(),
breadcrumbs: vi.fn(),
pushToast: vi.fn(),
listGallery: vi.fn(),
listApplications: vi.fn(),
listConnections: vi.fn(),
connectApp: vi.fn(),
startOAuth: vi.fn(),
putConnectionInstalls: vi.fn(),
listAgents: vi.fn(),
}));
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({
selectedCompanyId: fixture.companyId,
selectedCompany: { id: fixture.companyId, name: "Acme", issuePrefix: "ACM" },
}),
}));
vi.mock("@/context/BreadcrumbContext", () => ({
useBreadcrumbs: () => ({ setBreadcrumbs: fixture.breadcrumbs }),
}));
vi.mock("@/context/ToastContext", () => ({
useToast: () => ({ pushToast: fixture.pushToast }),
}));
vi.mock("@/hooks/useCloudInstance", () => ({
useCloudInstance: () => false,
}));
vi.mock("@/hooks/useChatConnectorsEnabled", () => ({
useChatConnectorsEnabled: () => ({ enabled: false, githubEnabled: false }),
chatProviderVisible: () => true,
}));
vi.mock("@/hooks/useMemoryConnectorsEnabled", () => ({
useMemoryConnectorsEnabled: () => ({ loaded: true, enabled: false }),
}));
vi.mock("@/hooks/useConnectorAvailability", () => ({
useConnectorAvailability: () => ({ loaded: true, failed: false, enabled: () => true }),
}));
vi.mock("@/lib/router", () => ({
Link: ({ to, children, ...props }: { to: string; children: React.ReactNode }) => <a href={to} {...props}>{children}</a>,
useNavigate: () => fixture.navigate,
useParams: () => fixture.params,
useSearchParams: () => [new URLSearchParams(fixture.search), vi.fn()],
}));
vi.mock("@/api/tools", () => ({
toolsApi: {
listGallery: (...args: unknown[]) => fixture.listGallery(...args),
listApplications: (...args: unknown[]) => fixture.listApplications(...args),
listConnections: (...args: unknown[]) => fixture.listConnections(...args),
connectApp: (...args: unknown[]) => fixture.connectApp(...args),
startOAuth: (...args: unknown[]) => fixture.startOAuth(...args),
putConnectionInstalls: (...args: unknown[]) => fixture.putConnectionInstalls(...args),
getConnection: vi.fn(),
getCloudConnectorEnrollment: vi.fn(),
startCloudConnectorEnrollment: vi.fn(),
},
}));
vi.mock("@/api/agents", () => ({
agentsApi: {
list: (...args: unknown[]) => fixture.listAgents(...args),
},
}));
vi.mock("@/api/connection-intents", () => ({
connectionIntentsApi: {
setPhase: vi.fn(),
setupOptions: vi.fn(),
},
}));
vi.mock("@/pages/apps/AppLogo", () => ({
AppLogo: () => null,
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
let container: HTMLDivElement;
let root: Root;
let queryClient: QueryClient;
const SLACK = getConnectableAppDefinition("slack")!;
const SLACK_APP = {
id: "app-slack-1",
companyId: "company-1",
applicationKey: "app-gallery:slack",
name: "Slack",
status: "draft",
metadata: { sourceTemplateKey: "slack" },
} as unknown as ToolApplication;
const SLACK_DRAFT = {
id: "conn-slack-1",
companyId: "company-1",
applicationId: "app-slack-1",
name: "Slack",
status: "draft",
enabled: false,
authKind: "oauth",
transport: "mcp_remote",
credentialPolicy: "organization",
credentialSource: "paperclip_vault",
hasSavedOAuthClientSecret: true,
config: {
sourceTemplateKey: "slack",
connectionMethodKey: "mcp-oauth",
oauth: {
clientId: "slack-client-123",
clientRegistrationSource: "manual",
},
},
transportConfig: {
sourceTemplateKey: "slack",
connectionMethodKey: "mcp-oauth",
},
} as unknown as ToolConnection;
async function settle() {
for (let i = 0; i < 8; i += 1) {
await new Promise((resolve) => window.setTimeout(resolve, 0));
}
}
function renderFlow() {
flushSync(() => {
root.render(
<QueryClientProvider client={queryClient}>
<ConnectionSetupFlow host="page" />
</QueryClientProvider>,
);
});
}
beforeEach(() => {
vi.clearAllMocks();
fixture.companyId = "company-1";
fixture.search = "";
fixture.params = {};
fixture.listGallery.mockResolvedValue({
apps: [SLACK],
oauthCallbackUrl: "https://paperclip.example/api/tools/oauth/callback",
capabilities: { canCreateOrganizationGrant: true, canSetCompanyInstall: true },
});
fixture.listApplications.mockResolvedValue({ applications: [SLACK_APP] });
fixture.listConnections.mockResolvedValue({ connections: [SLACK_DRAFT] });
fixture.listAgents.mockResolvedValue([]);
fixture.putConnectionInstalls.mockResolvedValue({});
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => {
flushSync(() => root.unmount());
queryClient.clear();
container.remove();
vi.restoreAllMocks();
});
describe("ConnectionSetupFlow — Slack customer OAuth error surface and guidance", () => {
it("surfaces OAuth callback permission rejection text in an alert banner on KeyStep", async () => {
fixture.search = "source=slack&resume=conn-slack-1&oauth=denied&code=oauth_authorization_denied&provider_error=invalid_scope";
renderFlow();
await settle();
const alert = container.querySelector('[role="alert"]');
expect(alert, "expected OAuth failure banner to be visible on KeyStep").not.toBeNull();
expect(alert?.textContent).toMatch(/rejected the requested permissions/i);
});
it("surfaces Slack MCP disabled callback errors in an alert banner on KeyStep", async () => {
fixture.search = "source=slack&resume=conn-slack-1&oauth=failed&code=slack_mcp_access_disabled";
renderFlow();
await settle();
const alert = container.querySelector('[role="alert"]');
expect(alert, "expected Slack MCP disabled error banner to be visible").not.toBeNull();
expect(alert?.textContent).toMatch(/Slack MCP access is disabled/i);
});
it("shows Slack MCP setup prerequisites alongside the customer OAuth client fields", async () => {
fixture.search = "source=slack";
renderFlow();
await settle();
expect(container.textContent).toContain("User Token Scopes");
expect(container.textContent).toContain("Model Context Protocol");
});
it("shows the OAuth error and fallback sign-in link when the popup is blocked on a customer OAuth app", async () => {
fixture.search = "source=slack&resume=conn-slack-1";
vi.spyOn(window, "open").mockReturnValue(null);
fixture.connectApp.mockResolvedValue({
connectionId: SLACK_DRAFT.id,
application: SLACK_APP,
connection: SLACK_DRAFT,
catalog: [],
actions: { readOnly: [], canMakeChanges: [] },
suggestedDefaults: { access: "all_agents", askFirstRiskLevels: [] },
auth: {
kind: "oauth",
startUrl: "https://slack.com/oauth/v2_user/authorize?client_id=slack-client-123&state=s1",
},
});
renderFlow();
await settle();
const submitButton = [...container.querySelectorAll("button")].find((button) =>
button.textContent?.includes("Continue to sign in"),
);
expect(submitButton).toBeDefined();
flushSync(() => submitButton!.click());
await settle();
const alert = container.querySelector('[role="alert"]');
expect(alert, "expected popup-blocked OAuth error banner on KeyStep").not.toBeNull();
expect(alert?.textContent).toMatch(/couldn’t open the sign-in window/i);
const fallbackLink = container.querySelector('a[href="https://slack.com/oauth/v2_user/authorize?client_id=slack-client-123&state=s1"]');
expect(fallbackLink?.textContent).toContain("Open sign-in in a new tab");
});
it("ignores inherited object property keys in provider_error without crashing the setup screen", async () => {
for (const inheritedKey of ["__proto__", "constructor", "toString"]) {
fixture.search = `source=slack&resume=conn-slack-1&oauth=denied&code=oauth_authorization_denied&provider_error=${inheritedKey}`;
renderFlow();
await settle();
const alert = container.querySelector('[role="alert"]');
expect(alert).not.toBeNull();
expect(alert?.textContent).toBe("Authorization was cancelled or declined. Your saved connection was not changed.");
}
});
});
@@ -1,6 +1,19 @@
import { connectionIntentsApi } from "@/api/connection-intents";
import { useAwsRoleSetupStep } from "./useAwsRoleSetupStep";
import { readOAuthWindowOutcome } from "@/lib/oauthWindowOutcome";
import { readOAuthWindowFailureDetails, readOAuthWindowOutcome } from "@/lib/oauthWindowOutcome";
import {
allowlistedOAuthProviderError,
oauthCallbackErrorMessage,
oauthFailureMessage,
readConnectionIntentOAuthFailureCode,
readConnectionIntentOAuthProviderError,
} from "./oauthFailureMessages";
export {
oauthCallbackErrorMessage,
oauthFailureMessage,
readConnectionIntentOAuthFailureCode,
readConnectionIntentOAuthProviderError,
} from "./oauthFailureMessages";
import { bindAccount } from "@/lib/account-scope";
import { StepHeader } from "./ConnectionSetupHeader";
import { GoogleWorkspaceServicesDialog } from "./GoogleWorkspaceServices";
@@ -191,16 +204,6 @@ function githubRecoveryUrl(value: string | null): string | null {
}
}
function oauthCallbackErrorMessage(outcome: string | null, code: string | null): string {
if (outcome === "denied") {
return "Authorization was cancelled or declined. Your saved connection was not changed.";
}
if (code === "github_installation_required") {
return "GitHub access is required. Install Paperclip and grant at least one repository, then try again.";
}
return "Authorization did not complete. Your saved connection is still here, so you can try again.";
}
const ROUTE_STAGE_BY_STEP: Partial<Record<Step, string>> = {
key: "setup",
success: "complete",
@@ -568,35 +571,6 @@ export function isMissingOAuthStateMessage(
&& 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;
@@ -738,6 +712,7 @@ function StandardConnectionSetupFlow({
const resumeConnectionId = searchParams.get("resume")?.trim() || null;
const oauthCallbackOutcome = searchParams.get("oauth");
const oauthCallbackCode = searchParams.get("code");
const oauthCallbackProviderError = allowlistedOAuthProviderError(searchParams.get("provider_error"));
const githubInstallationUrl = githubRecoveryUrl(searchParams.get("installation_url"));
const githubManagementUrl = githubRecoveryUrl(searchParams.get("management_url"));
const reconnectConnectionId = configuredConnection?.id ?? (searchParams.get("reconnect")?.trim() || null);
@@ -837,7 +812,7 @@ function StandardConnectionSetupFlow({
);
const [oauthError, setOAuthError] = useState<string | null>(() => {
if (!resumingAfterOAuthFailure) return null;
return oauthCallbackErrorMessage(oauthCallbackOutcome, oauthCallbackCode);
return oauthCallbackErrorMessage(oauthCallbackOutcome, oauthCallbackCode, oauthCallbackProviderError);
});
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. */
@@ -1045,15 +1020,25 @@ function StandardConnectionSetupFlow({
return;
}
if (outcome === "declined") {
setAuthorizationFallbackUrl(null);
setOAuthPhase("error");
setOAuthError("Authorization was cancelled. You can try again.");
const providerError = readConnectionIntentOAuthProviderError(event.data);
setOAuthError(
providerError && providerError !== "access_denied"
? oauthFailureMessage(readConnectionIntentOAuthFailureCode(event.data), providerError)
: "Authorization was cancelled. You can try again.",
);
onPhaseChange?.("needs_retry");
return;
}
if (outcome !== "failed") return;
setAuthorizationFallbackUrl(null);
setOAuthPhase("error");
setIntentGitHubRecovery(readConnectionIntentGitHubRecovery(event.data));
setOAuthError(oauthFailureMessage(readConnectionIntentOAuthFailureCode(event.data)));
setOAuthError(oauthFailureMessage(
readConnectionIntentOAuthFailureCode(event.data),
readConnectionIntentOAuthProviderError(event.data),
));
};
window.addEventListener("message", receiveOAuthOutcome);
return () => { disposed = true; window.removeEventListener("message", receiveOAuthOutcome); };
@@ -1073,6 +1058,7 @@ function StandardConnectionSetupFlow({
if (!popup) return;
if (popup.closed) {
setDialogOAuthConnectionId(null);
setAuthorizationFallbackUrl(null);
setOAuthPhase("error");
setOAuthError("The sign-in window closed. Try again to finish connecting.");
return;
@@ -1080,9 +1066,15 @@ function StandardConnectionSetupFlow({
const outcome = readOAuthWindowOutcome(popup, dialogOAuthConnectionId);
if (outcome === "waiting") return;
if (outcome !== "connected") {
const failure = readOAuthWindowFailureDetails(popup, dialogOAuthConnectionId);
setDialogOAuthConnectionId(null);
setAuthorizationFallbackUrl(null);
setOAuthPhase("error");
setOAuthError("Authorization did not complete. Finish setup in the sign-in window or try again.");
setOAuthError(
outcome === "denied" || outcome === "failed"
? oauthCallbackErrorMessage(outcome, failure?.code ?? null, failure?.providerError ?? null)
: "Authorization did not complete. Finish setup in the sign-in window or try again.",
);
return;
}
checking = true;
@@ -2049,7 +2041,7 @@ function StandardConnectionSetupFlow({
// intentionally blank.
if (oauthCallbackOutcome === "failed" || oauthCallbackOutcome === "denied") {
setOAuthPhase("error");
setOAuthError(oauthCallbackErrorMessage(oauthCallbackOutcome, oauthCallbackCode));
setOAuthError(oauthCallbackErrorMessage(oauthCallbackOutcome, oauthCallbackCode, oauthCallbackProviderError));
} else {
setOAuthPhase("entry");
setOAuthError(null);
@@ -2057,7 +2049,7 @@ function StandardConnectionSetupFlow({
setStep("key");
hydratedResumeConnectionIdRef.current = savedConnection.id;
setHydratedResumeConnectionId(savedConnection.id);
}, [credentialSource, entry, oauthCallbackCode, oauthCallbackOutcome, resumeConnection, reconnectConnection]);
}, [credentialSource, entry, oauthCallbackCode, oauthCallbackOutcome, oauthCallbackProviderError, resumeConnection, reconnectConnection]);
/**
* Commit the connection: action defaults, agent reach, and installs.
@@ -2879,7 +2871,9 @@ function StandardConnectionSetupFlow({
settingsValid={additionalSettingsValid && instructionsValid && !dedicatedAgentMissing}
entry={entry}
selfHostedGoogleApp={!cloudInstance && Boolean(getConnectableAppDefinition(entry.slug)?.methods.some(isCloudOnlyConnectionMethod))}
error={connectMutation.error ? describeError(connectMutation.error).body : null}
error={connectMutation.error ? describeError(connectMutation.error).body : oauthError}
authorizationUrl={oauthPhase === "error" ? authorizationFallbackUrl : null}
onOpenAuthorization={openAuthorizationTab}
values={credentials}
onChange={setCredentials}
oauthClientId={curatedOAuthClientId}
@@ -2899,6 +2893,8 @@ function StandardConnectionSetupFlow({
methodKey={connectionMethodKey}
onMethodChange={(nextMethod) => {
setConnectionMethodKey(nextMethod?.key ?? "");
setOAuthError(null);
setAuthorizationFallbackUrl(null);
// Capability/auth changes must not broaden the audience selected
// on Access (including choices restored after Cloud enrollment).
if (
@@ -2964,9 +2960,10 @@ function StandardConnectionSetupFlow({
startOAuth(resumableOAuthConnection);
return;
}
setOAuthError(null);
setAuthorizationFallbackUrl(null);
if (selectedMethod && connectionMethodSupportsAutomaticOAuth(selectedMethod)) {
directOAuthAccessConfirmedRef.current = true;
setOAuthError(null);
setOAuthPhase("starting");
}
connectApp();
@@ -3554,6 +3551,8 @@ function KeyStep({
entry,
selfHostedGoogleApp = false,
error,
authorizationUrl,
onOpenAuthorization,
values,
onChange,
oauthClientId,
@@ -3584,6 +3583,8 @@ function KeyStep({
entry: AppDefinition;
selfHostedGoogleApp?: boolean;
error?: string | null;
authorizationUrl?: string | null;
onOpenAuthorization?: () => void;
values: Record<string, string>;
onChange: (next: Record<string, string>) => void;
oauthClientId: string;
@@ -3965,7 +3966,20 @@ function KeyStep({
</div>
) : null}
{error ? <div role="alert"><InlineBanner tone="danger">{error}</InlineBanner></div> : null}
{error ? (
<div role="alert" className="space-y-2">
<InlineBanner tone="danger">{error}</InlineBanner>
{authorizationUrl ? (
<div>
<Button type="button" variant="outline" size="sm" asChild>
<a href={authorizationUrl} target="_blank" rel="noopener noreferrer" onClick={onOpenAuthorization}>
Open sign-in in a new tab
</a>
</Button>
</div>
) : null}
</div>
) : null}
{method?.settingsSchema && onPluginSettingsChange ? (
<JsonSchemaForm
@@ -4114,6 +4128,9 @@ function OAuthClientFields({
? `${entry.name} does not let Paperclip register itself automatically, so this connector needs an OAuth app you create. Add the callback URL below in ${entry.name}, then paste the client details back here.`
: `Register Paperclip's callback URI in ${entry.name}, then enter the customer-owned client details.`}
</p>
{required && !method.oauthClientSecretRequired && method.guidanceMd ? (
<p className="mt-2 text-xs text-muted-foreground">{method.guidanceMd}</p>
) : null}
{method.consoleLinks?.register ? (
<a
href={method.consoleLinks.register}
@@ -0,0 +1,88 @@
const DEFAULT_OAUTH_FAILURE_MESSAGE = "Authorization did not complete. Try again when you’re ready.";
const OAUTH_PROVIDER_ERROR_COPY = new Map<string, string>([
["invalid_scope", "The provider rejected the requested permissions. Check your OAuth app’s configured scopes and try again."],
["invalid_redirect_uri", "The provider rejected Paperclip’s callback URL. Check that the callback URL in your OAuth app matches Paperclip and try again."],
["invalid_client", "The provider rejected this OAuth app’s client credentials. Check your client ID and secret and try again."],
["unauthorized_client", "The provider refused to authorize this OAuth app. Check your OAuth app configuration and try again."],
["invalid_grant", "The provider rejected the authorization code. Try signing in again."],
["invalid_request", "The provider rejected the sign-in request. Check your OAuth app settings and try again."],
["invalid_client_metadata", "The provider rejected Paperclip’s client registration details. Try again or use your own OAuth app."],
["invalid_software_statement", "The provider rejected Paperclip’s client registration details. Try again or use your own OAuth app."],
["unapproved_software_statement", "The provider rejected Paperclip’s client registration details. Try again or use your own OAuth app."],
["unsupported_grant_type", "The provider does not support the OAuth grant Paperclip uses."],
["unsupported_response_type", "The provider does not support the OAuth sign-in flow Paperclip uses."],
["server_error", "The provider reported an internal error. Try again shortly."],
["temporarily_unavailable", "The provider is temporarily unavailable. Try again shortly."],
["account_selection_required", "The provider requires you to select an account. Try connecting again."],
["consent_required", "The provider requires consent to be granted. Try connecting again."],
["interaction_required", "The provider requires interactive sign-in. Try connecting again."],
["login_required", "The provider requires you to sign in first. Try connecting again."],
]);
export function allowlistedOAuthProviderError(value: unknown): string | null {
if (typeof value !== "string") return null;
if (value === "access_denied" || OAUTH_PROVIDER_ERROR_COPY.has(value)) return value;
return null;
}
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 readConnectionIntentOAuthProviderError(data: unknown): string | null {
if (!data || typeof data !== "object") return null;
return allowlistedOAuthProviderError((data as { providerError?: unknown }).providerError);
}
export function oauthFailureMessage(code: string | null, providerError?: string | null): string {
const safeProviderError = allowlistedOAuthProviderError(providerError);
if (safeProviderError && safeProviderError !== "access_denied") {
const providerCopy = OAUTH_PROVIDER_ERROR_COPY.get(safeProviderError);
if (providerCopy) return providerCopy;
}
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 "slack_mcp_access_disabled":
return "Slack MCP access is disabled for this app. Ask the Slack app owner to enable Model Context Protocol under Features → Agents & AI Apps, then try again.";
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 DEFAULT_OAUTH_FAILURE_MESSAGE;
}
}
export function oauthCallbackErrorMessage(
outcome: string | null,
code: string | null,
providerError?: string | null,
): string {
const safeProviderError = allowlistedOAuthProviderError(providerError);
if (code === "github_installation_required") {
return "GitHub access is required. Install Paperclip and grant at least one repository, then try again.";
}
const specific = oauthFailureMessage(
code && code !== "oauth_authorization_denied" ? code : null,
safeProviderError,
);
if (specific !== DEFAULT_OAUTH_FAILURE_MESSAGE) return specific;
if (outcome === "denied" || safeProviderError === "access_denied") {
return "Authorization was cancelled or declined. Your saved connection was not changed.";
}
return "Authorization did not complete. Your saved connection is still here, so you can try again.";
}
+37 -20
View File
@@ -1,26 +1,43 @@
/** A callback is only a signal to re-read the connection from the server. */
function readSameOriginOAuthCallback(
popup: Window | null,
connectionId: string,
): { url: URL; outcome: "connected" | "denied" | "failed" | "waiting" } | null {
if (!popup || popup.closed) return null;
try {
const url = new URL(popup.location.href);
if (url.origin !== window.location.origin) return null;
if (!url.pathname.split("/").includes(connectionId)
&& url.searchParams.get("resume") !== connectionId
&& url.searchParams.get("reconnect") !== connectionId) return null;
const outcome = url.searchParams.get("oauth");
if (outcome === "denied" || outcome === "failed") {
return { url, outcome };
}
const connected = url.searchParams.get("success") === "1"
|| url.pathname.endsWith(`/apps/${connectionId}/permissions`);
return { url, outcome: connected ? "connected" : "waiting" };
} catch {
return null;
}
}
export function readOAuthWindowOutcome(
popup: Window | null,
connectionId: string,
): "waiting" | "closed" | "connected" | "denied" | "failed" {
if (!popup) return "waiting"; // A native fallback link has no window handle.
if (!popup) return "waiting";
if (popup.closed) return "closed";
try {
const url = new URL(popup.location.href);
if (url.origin !== window.location.origin) return "waiting";
if (!url.pathname.split("/").includes(connectionId)
&& url.searchParams.get("resume") !== connectionId
&& url.searchParams.get("reconnect") !== connectionId) return "waiting";
const outcome = url.searchParams.get("oauth");
if (outcome === "denied" || outcome === "failed") return outcome;
// AppDetail consumes success=1 on mount. The exact permissions route is
// also the durable callback destination after that query flag is removed.
// Callers must still verify the saved connection before reporting success.
return url.searchParams.get("success") === "1"
|| url.pathname.endsWith(`/apps/${connectionId}/permissions`)
? "connected" : "waiting";
} catch {
// Reading location is forbidden while the window is at the provider.
return "waiting";
}
return readSameOriginOAuthCallback(popup, connectionId)?.outcome ?? "waiting";
}
export function readOAuthWindowFailureDetails(
popup: Window | null,
connectionId: string,
): { code: string | null; providerError: string | null } | null {
const callback = readSameOriginOAuthCallback(popup, connectionId);
if (!callback || (callback.outcome !== "denied" && callback.outcome !== "failed")) return null;
return {
code: callback.url.searchParams.get("code"),
providerError: callback.url.searchParams.get("provider_error"),
};
}