From d99721398db23360e8f06e74a3d8a304162d02e2 Mon Sep 17 00:00:00 2001 From: marshall Date: Wed, 25 Nov 2026 13:31:22 -0800 Subject: [PATCH] fix(tool-access): keep a personal OAuth URL draft that needs its user's sign-in (#20167) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents and people can connect a custom remote MCP server ("Connect your own MCP server") through `POST /api/companies/{companyId}/tools/apps/connect` > - A draft that declares OAuth for one user (`authMode: "oauth"`, `grantKind: "user"`) has no user grant until the OAuth callback > - Its first health check stops at `user_authorization_required` before any request reaches the server > - The connect flow handles only `oauth_challenge` as "needs sign-in", so it deletes the draft and returns a 422 with a `setupUrl` to the deleted row > - The person who opens that link finds a connection that does not exist > - This pull request keeps the draft and starts sign-in, and it removes links to a deleted draft from the error > - The benefit is that an agent can start a per-user OAuth connection for its user, and the link it gets back opens a draft the user can sign in to ## Linked Issues or Issue Description **What happened?** An agent called `POST /api/companies/{companyId}/tools/apps/connect` for a per-user OAuth remote MCP server. The call returned 422 `user_authorization_required`. The body held a `draft` connection id and a `setupUrl` / `reconnectUrl` of `/apps//permissions`. A later `GET /api/tool-connections/` returned 404, and the connection was not in the company's connection list. The connect flow had deleted the draft after it built the error. Also: for a custom server draft with no `sourceTemplateKey`, the agent sign-in hand-off from `start-authorization` is `//apps/connect?resume=` with no `source`. The connect route sends a link without `source` to the Apps list, so the user does not see the sign-in. **Expected behavior** The draft stays, sign-in starts, and the returned link opens a page where the user can click **Connect as me**. If setup deletes its draft, the error carries no link to that draft and says what to do next. **Steps to reproduce** 1. As an agent with a responsible user, call `POST /api/companies/{companyId}/tools/apps/connect` for a custom remote MCP URL with `authMode: "oauth"` and `grantKind: "user"`. 2. See the 422 `user_authorization_required` with a `setupUrl`. 3. Call `GET /api/tool-connections/`. It returns 404. **Paperclip version or commit** Rebased onto `master` at `2d06567795`. ## What Changed - `server/src/services/tool-access.ts`: on a fresh personal OAuth draft, treat `user_authorization_required` from the first health check like `oauth_challenge`. Keep the draft and start sign-in. - `server/src/services/tool-access.ts`: when setup deletes its draft, remove `setupUrl` / `reconnectUrl` for that draft from the 422. Add `connectionRemoved: true` and a `nextStep` message. - `server/src/services/tool-access/oauth/authorization-start.ts`: for a draft with no app source, send the agent's hand-off to `//apps//permissions`, not to `/apps/connect?resume=`. - `server/src/__tests__/generic-mcp-connection.test.ts`: 3 regression tests covering draft preservation, stripped dead links on removed drafts, and agent custom-server hand-off URLs. - `server/src/__tests__/connection-management-delegated-policy.integration.test.ts`: update the custom-server hand-off assertion to expect `//apps//permissions` (while asserting curated `google-workspace` apps still hand off to `/apps/connect?resume=&source=google-workspace`), and add a full-stack HTTP E2E integration test verifying an agent-started personal OAuth draft stays alive (`200` on GET, `firstSignInPending: true`, `canConnectAsCurrentUser: true`) until the addressed user signs in through `start-authorization` and `/api/tools/oauth/callback`. ## Verification - Red-before-fix on `master` (`2d06567795`): all 3 new regression tests in `generic-mcp-connection.test.ts` fail (`422 user_authorization_required` instead of `201`, missing `connectionRemoved: true` with dead `setupUrl`/`reconnectUrl` still present). - Green-after-fix locally: - `pnpm --filter @paperclipai/server typecheck`: passed (0 errors) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/generic-mcp-connection.test.ts src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts`: 121/121 passed - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/connection-management-delegated-policy.integration.test.ts src/__tests__/tool-access-oauth-protocol.integration.test.ts`: 41/41 passed (including full-stack HTTP agent-to-human E2E sign-in test) - `pnpm verify --base 2d06567795 --explain` selects 1947/2301 Vitest files because `server/src/services/tool-access.ts` is broadly imported; focused suites and typecheck passed locally and required CI supplies broad sharded coverage. ## Risks - Low risk. The new path applies only to a draft created in the same connect call, with `authMode: "oauth"` and `grantKind: "user"`. Other health-check errors still delete the draft as before. - The 422 body for a deleted draft no longer has `setupUrl` / `reconnectUrl`. A client that read those fields got a link to a deleted row, so no working flow depends on them. - Compatible with #22714 (`firstSignInPending`): an awaiting personal draft is marked `firstSignInPending: true` in the Apps list while remaining reachable via `GET /api/tool-connections/:id` and `start-authorization` until the user signs in, after which `firstSignInPending` clears and the connection becomes `active`. - Not in scope: after a user signs in on a personal draft with no installs, the defaults give access to all agents. That is a sharing-default design question, not part of this fix. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use and code execution (original PR commit). - Rebase, delegated-policy test alignment, full-stack E2E integration test, and local verification: Antigravity agent with shell, edit, and test tools. ## 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 (no docs change needed) - [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 --------- Co-authored-by: Paperclip Co-authored-by: Claude Opus 5.5 Co-authored-by: Dotta --- ...ement-delegated-policy.integration.test.ts | 149 +++++++++++++++++- .../__tests__/generic-mcp-connection.test.ts | 94 +++++++++++ server/src/services/tool-access.ts | 42 ++++- .../tool-access/oauth/authorization-start.ts | 15 +- 4 files changed, 292 insertions(+), 8 deletions(-) diff --git a/server/src/__tests__/connection-management-delegated-policy.integration.test.ts b/server/src/__tests__/connection-management-delegated-policy.integration.test.ts index f7995f5da05..c3af5f1825c 100644 --- a/server/src/__tests__/connection-management-delegated-policy.integration.test.ts +++ b/server/src/__tests__/connection-management-delegated-policy.integration.test.ts @@ -216,13 +216,157 @@ describe("connection management delegated policy and profile access", () => { expiresAt: null, requiredUserAction: { userId: f.userId, resource: { id: created.body.id } }, } }); // The agent links this in chat, so it is a relative app route, never the server's own origin. + // A custom remote MCP server has no app source, so the hand-off goes to the + // draft's own permissions page where the user can click "Connect as me". expect(started.body.authorizationUrl).toMatch(/^\/[^/]/); expect(started.body.requiredUserAction.setupPath).toBe(started.body.authorizationUrl); - expect(new URL(started.body.authorizationUrl, "https://paperclip.example").searchParams.get("resume")).toBe(created.body.id); + expect(new URL(started.body.authorizationUrl, "https://paperclip.example").pathname) + .toMatch(new RegExp(`^/[^/]+/apps/${created.body.id}/permissions$`)); expect(await f.request("POST", path, { asCurrentUser: true })).toMatchObject({ status: 200, body: { authorizationUrl: started.body.authorizationUrl } }); expect(await server.db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, created.body.id))).toHaveLength(0); }); + it("keeps an agent-started personal OAuth URL draft alive until the addressed user signs in", async () => { + const f = await fixture(); + const mcpOrigin = "https://8.8.8.8"; + const mcpUrl = `${mcpOrigin}/mcp`; + const issuer = `${mcpOrigin}/tenant/acme`; + let accessToken: string | null = null; + provider = async (url, init) => { + const method = (init?.method ?? "GET").toUpperCase(); + if (url === `${mcpOrigin}/.well-known/oauth-protected-resource/mcp`) { + return Response.json({ resource: mcpUrl, authorization_servers: [issuer] }); + } + if (url === `${mcpOrigin}/.well-known/oauth-authorization-server/tenant/acme`) { + return Response.json({ + issuer, + authorization_endpoint: `${issuer}/authorize`, + token_endpoint: `${issuer}/token`, + registration_endpoint: `${issuer}/register`, + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + scopes_supported: ["mcp:read"], + }); + } + if (url === `${issuer}/register` && method === "POST") { + const requested = JSON.parse(String(init?.body ?? "{}")) as Record; + return Response.json({ + client_id: "fixture-dcr-client", + redirect_uris: requested.redirect_uris, + grant_types: requested.grant_types, + response_types: requested.response_types, + token_endpoint_auth_method: requested.token_endpoint_auth_method, + application_type: requested.application_type, + }); + } + if (url === `${issuer}/token` && method === "POST") { + accessToken = `fixture-access-${randomUUID()}`; + return Response.json({ + access_token: accessToken, + refresh_token: "fixture-refresh", + expires_in: 3600, + token_type: "Bearer", + scope: "mcp:read", + }); + } + if (url === mcpUrl && method === "POST") { + const headers = new Headers(init?.headers); + if (headers.get("authorization") !== `Bearer ${accessToken}`) { + return new Response("", { + status: 401, + headers: { "www-authenticate": `Bearer resource_metadata="${mcpOrigin}/.well-known/oauth-protected-resource/mcp"` }, + }); + } + return Response.json({ + jsonrpc: "2.0", + id: "paperclip-catalog-refresh", + result: { tools: [{ name: "list_items", description: "List items", annotations: { readOnlyHint: true } }] }, + }); + } + return Response.json({ error: "not_found" }, { status: 404 }); + }; + try { + const connected = await f.request("POST", `/companies/${f.companyId}/tools/apps/connect`, { + link: mcpUrl, + name: "Agent personal OAuth E2E", + authMode: "oauth", + grantKind: "user", + }); + expect(connected, JSON.stringify(connected)).toMatchObject({ status: 201 }); + const connectionId = connected.body.connectionId as string; + expect(connected.body.auth).toMatchObject({ kind: "oauth", issuer }); + const permissionsPathPattern = new RegExp(`^/[^/]+/apps/${connectionId}/permissions$`); + expect(connected.body.auth.startUrl).toMatch(permissionsPathPattern); + expect(connected.body.requiredUserAction?.setupPath).toBe(connected.body.auth.startUrl); + expect(await server.db.select().from(toolOauthStates).where(eq(toolOauthStates.connectionId, connectionId))).toHaveLength(0); + + // The addressed human opens the handed-off link: the draft is alive (not a 404 dead link) + // and exposes "Connect as me" capability while awaiting first sign-in. + const cookie = await server.humanSession(f.userId); + const getConnectionRes = await fetch(`${server.apiUrl}/api/tool-connections/${connectionId}`, { headers: { cookie } }); + expect(getConnectionRes.status).toBe(200); + expect(await getConnectionRes.json()).toMatchObject({ + id: connectionId, + status: "draft", + credentialPolicy: "per_user", + createdByUserId: f.userId, + }); + + const listBeforeRes = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/tools/connections`, { headers: { cookie } }); + expect(listBeforeRes.status).toBe(200); + const listBefore = await listBeforeRes.json() as { connections: Array<{ id: string; status: string; firstSignInPending?: boolean }> }; + expect(listBefore.connections.find(c => c.id === connectionId)).toMatchObject({ status: "draft", firstSignInPending: true }); + + const grantsBeforeRes = await fetch(`${server.apiUrl}/api/tool-connections/${connectionId}/grants`, { headers: { cookie } }); + expect(grantsBeforeRes.status).toBe(200); + expect(await grantsBeforeRes.json()).toMatchObject({ + grants: [], + currentUserId: f.userId, + capabilities: { canConnectAsCurrentUser: true }, + }); + + // The human clicks "Connect as me" on the draft's permissions page and finishes OAuth. + const startAuthRes = await fetch( + `${server.apiUrl}/api/companies/${f.companyId}/tools/connections/${connectionId}/start-authorization`, + { + method: "POST", + headers: { cookie, "Content-Type": "application/json", origin: server.apiUrl }, + body: JSON.stringify({ subjectUserId: f.userId, returnTo: `/apps/${connectionId}/permissions` }), + }, + ); + const startAuthBody = await startAuthRes.json(); + expect(startAuthRes.status, JSON.stringify(startAuthBody)).toBe(200); + const providerAuthUrl = new URL(startAuthBody.url); + expect(providerAuthUrl.origin + providerAuthUrl.pathname).toBe(`${issuer}/authorize`); + const state = providerAuthUrl.searchParams.get("state")!; + expect(state).toBeTruthy(); + + const callbackRes = await fetch( + `${server.apiUrl}/api/tools/oauth/callback?${new URLSearchParams({ state, code: "fixture-auth-code", iss: issuer })}`, + { headers: { cookie, Accept: "text/html" }, redirect: "manual" }, + ); + expect(callbackRes.status).toBe(303); + expect(callbackRes.headers.get("location")).toMatch(new RegExp(`^/[^/]+/apps/${connectionId}/permissions\\?success=1$`)); + + const getAfterRes = await fetch(`${server.apiUrl}/api/tool-connections/${connectionId}`, { headers: { cookie } }); + expect(getAfterRes.status).toBe(200); + expect(await getAfterRes.json()).toMatchObject({ id: connectionId, status: "active", enabled: true }); + + const listAfterRes = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/tools/connections`, { headers: { cookie } }); + expect(listAfterRes.status).toBe(200); + const listAfter = await listAfterRes.json() as { connections: Array<{ id: string; status: string; firstSignInPending?: boolean }> }; + expect(listAfter.connections.find(c => c.id === connectionId)?.firstSignInPending).toBeUndefined(); + + await expect( + server.db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connectionId)), + ).resolves.toEqual([ + expect.objectContaining({ kind: "user", subjectUserId: f.userId, status: "active" }), + ]); + } finally { + provider = null; + } + }); + it("delegates and revokes an owned credential with actual agent attribution", async () => { const f = await fixture(); const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { @@ -257,6 +401,9 @@ describe("connection management delegated policy and profile access", () => { expect(created, JSON.stringify(created)).toMatchObject({ status: 201 }); const handoff = await f.request("POST", `/tools/oauth/${created.body.id}/start`, { asCurrentUser: true }); expect(handoff, JSON.stringify(handoff)).toMatchObject({ status: 200, body: { expiresAt: null, requiredUserAction: { userId: f.userId } } }); + const handoffUrl = new URL(handoff.body.authorizationUrl, "https://paperclip.example"); + expect(handoffUrl.searchParams.get("resume")).toBe(created.body.id); + expect(handoffUrl.searchParams.get("source")).toBe("google-workspace"); const [unselected] = await server.db.select().from(toolConnections).where(eq(toolConnections.id, created.body.id)); expect(unselected.config.workspaceSetup).toBeUndefined(); const services = { gmail: "read" as const }; diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.ts index ae85753be94..c819e2699a8 100644 --- a/server/src/__tests__/generic-mcp-connection.test.ts +++ b/server/src/__tests__/generic-mcp-connection.test.ts @@ -1777,6 +1777,100 @@ describeEmbeddedPostgres("generic remote MCP connections", () => { ]); }); + it("keeps a personal OAuth URL draft that needs its user's sign-in instead of deleting it", async () => { + const fixture = installMcpOAuthFixture({ auth: "oauth" }); + const company = await createCompany(db); + const app = createRouteApp(db); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL); + + // Declaring OAuth up front means the draft has no user grant yet, so its + // first probe answers "needs the current user's authorization". + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ + link: MCP_URL, + name: "Fixture personal declared OAuth", + authMode: "oauth", + grantKind: "user", + }); + expect(response.status, JSON.stringify(response.body)).toBe(201); + const connected = response.body; + expect(connected.auth).toMatchObject({ kind: "oauth", issuer: ISSUER, startUrl: expect.any(String) }); + + const [draft] = await db.select().from(toolConnections) + .where(eq(toolConnections.id, connected.connectionId)); + expect(draft).toMatchObject({ status: "draft", credentialPolicy: "per_user", createdByUserId: "board-user" }); + await request(app).get(`/api/tool-connections/${connected.connectionId}`).expect(200); + + const authorizationUrl = new URL(connected.auth.startUrl); + const code = fixture.issueAuthorizationCode(connected.auth.startUrl); + await request(app) + .get("/api/tools/oauth/callback") + .set("Accept", "text/html") + .query({ state: authorizationUrl.searchParams.get("state")!, code, iss: ISSUER }) + .expect(303); + await expect( + db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId)), + ).resolves.toEqual([expect.objectContaining({ kind: "user", subjectUserId: "board-user", status: "active" })]); + }); + + it("does not return a sign-in link to a personal draft that setup removed", async () => { + // No OAuth metadata anywhere, so sign-in cannot start and setup is undone. + vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response( + JSON.stringify({ error: "not_found" }), + { status: 404, headers: { "content-type": "application/json" } }, + )); + const company = await createCompany(db); + const app = createRouteApp(db); + + const response = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ link: MCP_URL, name: "Fixture personal OAuth without metadata", authMode: "oauth", grantKind: "user" }); + expect(response.status, JSON.stringify(response.body)).toBe(422); + expect(response.body.details).toMatchObject({ code: "user_authorization_required", connectionRemoved: true }); + expect(response.body.details).not.toHaveProperty("setupUrl"); + expect(response.body.details).not.toHaveProperty("reconnectUrl"); + await expect( + db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id)), + ).resolves.toHaveLength(0); + }); + + it("hands an agent's custom-server sign-in to the draft's own page", async () => { + installMcpOAuthFixture({ auth: "oauth" }); + const company = await createCompany(db); + const service = toolAccessService(db); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Setup helper", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning(); + const agentActor = { + actorType: "agent" as const, + actorId: agent!.id, + managementContext: { + actor: { type: "agent", agentId: agent!.id, companyId: company.id, source: "agent_key" }, + responsibleUserId: "board-user", + reauthorize: async () => undefined, + }, + } as unknown as Parameters[2]["actor"]; + + const connected = await service.connectGalleryApp(company.id, { + link: MCP_URL, + name: "Fixture agent-started personal OAuth", + authMode: "oauth", + grantKind: "user", + }, agentActor); + expect(connected.auth).toMatchObject({ kind: "oauth" }); + + const handoff = await service.startOAuth(company.id, connected.connectionId, { + redirectUri: REDIRECT_URI, + actor: agentActor, + subjectUserId: "board-user", + }); + // The connect wizard turns a link with no app source back to the Apps + // list; the connection page lets the user sign in as themselves. + expect(handoff.authorizationUrl).toBe(`/${company.issuePrefix}/apps/${connected.connectionId}/permissions`); + const [draft] = await db.select().from(toolConnections) + .where(eq(toolConnections.id, connected.connectionId)); + expect(draft).toMatchObject({ status: "draft", createdByUserId: "board-user" }); + }); + it("creates a separate fresh personal URL connection and keeps explicit reconnect owner-bound", async () => { const fixture = installMcpOAuthFixture({ auth: "oauth" }); const company = await createCompany(db); diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index 00125148b87..c3a66600839 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -2993,13 +2993,25 @@ export function toolAccessService( allowUnauthenticatedProbe: unauthenticatedPersonalProbe, }); } catch (error) { + const healthFailureCode = + error instanceof HttpError ? asRecord(error.details).code : null; + // A new personal OAuth draft has no user grant until the callback, so + // its probe stops at "needs the current user's authorization" before + // any request reaches the server. That is the same sign-in-required + // state as a 401 challenge, not a failed setup: keep the draft and + // start sign-in instead of deleting it and returning its dead link. + const personalOAuthDraftNeedsSignIn = + healthFailureCode === "user_authorization_required" && + genericAuthKind === "oauth" && + Boolean(personalIdentityUserId) && + !retainedPersonalIdentity?.grant; if ( (!galleryEntry || remoteMcpConnector) && input.authMode !== "none" && input.authMode !== "bearer" && input.authMode !== "custom_headers" && error instanceof HttpError && - asRecord(error.details).code === "oauth_challenge" + (healthFailureCode === "oauth_challenge" || personalOAuthDraftNeedsSignIn) ) { const [oauthConnection] = await db .select() @@ -3125,6 +3137,7 @@ export function toolAccessService( } catch (error) { if (personalPublicSetupEstablished) throw error; let identityRollbackError: unknown = null; + let removedConnectionId: string | null = null; let preserveConcurrentRevival = false; if (connectionRow && revivedConnectionPrevious) { const attemptedConnection = connectionRow; @@ -3256,10 +3269,11 @@ export function toolAccessService( } } else if (connectionRow) { const failedConnectionId = connectionRow.id; - await writeToolConnectionHealthChange(db, { companyId, id: failedConnectionId }, tx => tx + const removed = await writeToolConnectionHealthChange(db, { companyId, id: failedConnectionId }, tx => tx .delete(toolConnections) .where(eq(toolConnections.id, failedConnectionId))) - .catch(() => undefined); + .then(() => true, () => false); + if (removed) removedConnectionId = failedConnectionId; } if ( !preserveConcurrentRevival && @@ -3303,10 +3317,30 @@ export function toolAccessService( }, ); } - throw error; + throw withoutRemovedConnectionLinks(error, removedConnectionId); } } + // A setup failure deletes its new draft, so a credential error raised while + // probing it must not hand the caller a link to that draft: the link would + // open a connection that no longer exists. Edit the error in place so its + // remote-failure classification, keyed by identity, still applies. + function withoutRemovedConnectionLinks(error: unknown, removedConnectionId: string | null): unknown { + if (!removedConnectionId || !(error instanceof HttpError)) return error; + const details = asRecord(error.details); + const removedPath = `/apps/${removedConnectionId}/permissions`; + if (details.setupUrl !== removedPath && details.reconnectUrl !== removedPath) return error; + const rest = { ...details }; + delete rest.setupUrl; + delete rest.reconnectUrl; + error.details = { + ...rest, + connectionRemoved: true, + nextStep: "This setup was not saved. Start the connection again; do not send a link to this setup.", + }; + return error; + } + async function assertCatalogEntriesForConnection( companyId: string, connectionId: string, diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index 065eadae0c8..3faef1f6e1c 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -234,9 +234,18 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies if (!company) throw notFound("Company not found"); // A relative app route: the agent links it in chat, where it opens on // whichever host the person uses, never the server's own listen address. - const destination = `/${encodeURIComponent(company.prefix)}/apps/${connection.credentialSource === "vercel_connect" ? "vercel-connect" : "connect"}?${new URLSearchParams({ - [connection.status === "draft" ? "resume" : "reconnect"]: connection.id, - ...(sourceTemplateKey ? { source: sourceTemplateKey } : {}), ...(intentLink ? { intent: intentLink.id } : {}) })}`; + // The connect wizard only opens for a known app source. A custom server + // has none, so send its user to the connection's own page, where they + // sign in as themselves. + const customServer = !sourceTemplateKey && connection.credentialSource !== "vercel_connect"; + const query = new URLSearchParams(customServer + ? { ...(intentLink ? { intent: intentLink.id } : {}) } + : { [connection.status === "draft" ? "resume" : "reconnect"]: connection.id, + ...(sourceTemplateKey ? { source: sourceTemplateKey } : {}), ...(intentLink ? { intent: intentLink.id } : {}) }).toString(); + const destination = (customServer + ? `/${encodeURIComponent(company.prefix)}/apps/${encodeURIComponent(connection.id)}/permissions` + : `/${encodeURIComponent(company.prefix)}/apps/${connection.credentialSource === "vercel_connect" ? "vercel-connect" : "connect"}`) + + (query ? `?${query}` : ""); return { connectionId: connection.id, provider: sourceTemplateKey ?? "oauth", authorizationUrl: destination, expiresAt: null }; }