mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 12:50:37 +01:00
## 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/<id>/permissions`. A later `GET
/api/tool-connections/<id>` 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
`/<prefix>/apps/connect?resume=<id>` 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/<connectionId>`. 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
`/<prefix>/apps/<id>/permissions`, not to `/apps/connect?resume=<id>`.
- `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
`/<prefix>/apps/<id>/permissions` (while asserting curated
`google-workspace` apps still hand off to
`/apps/connect?resume=<id>&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 <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Dotta <bippadotta@protonmail.com>
783 lines
37 KiB
TypeScript
783 lines
37 KiB
TypeScript
import { notifyIssueReviewState } from "../../issue-review-state-notifications.js";
|
|
import { vercelConnectHttpError, vercelCredentialFor, vercelConnectResourcesFor } from "../vercel-credentials.js";
|
|
import { credentialScope, managedConnectorProfile } from "./client-settings.js";
|
|
import { assertOAuthClientBindingUnchanged, createOAuthClientRegistration } from "./client-registration.js";
|
|
import type { ActorInfo } from "../types.js";
|
|
import { createOAuthEndpointPolicy } from "./endpoint-policy.js";
|
|
import { createOAuthDiscovery } from "./discovery.js";
|
|
import { asRecord, oauthConfig, normalizeOauthScopes, originOf } from "./metadata.js";
|
|
import { connectionMethodForConnection } from "../connection-methods.js";
|
|
import { GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, googleWorkspaceDraftRequestedScopes, googleWorkspaceSelectedScopes, type GoogleWorkspaceServiceSelection, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared";
|
|
import { paperclipGoogleSignInAvailable } from "../../google-sign-in-availability.js";
|
|
import { and, eq, lt } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { companies, agents, connectionGrants, issueThreadInteractions, toolConnections, toolOauthStates } from "@paperclipai/db";
|
|
import type { ConnectionGrantKind, ToolOAuthStartResult } from "@paperclipai/shared";
|
|
import { getConnectableAppDefinition } from "@paperclipai/shared";
|
|
import { badRequest, conflict, forbidden, notFound, tooManyRequests, unprocessable } from "../../../errors.js";
|
|
import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, paperclipCloudConnectorConsentAllowed, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
|
|
import { deriveVercelConnectSubject, vercelConnectCallbackUrl, VercelConnectClientError, type VercelConnectClient } from "../../vercel-connect.js";
|
|
|
|
import type { ConnectionSetupPolicy } from "../connections/setup-policy.js";
|
|
import { assertSupportedConnection } from "../connections/setup-policy.js";
|
|
|
|
import { actorBinding } from "../actor.js";
|
|
import { assertOAuthRedirectConstraints, randomOauthToken, base64UrlSha256 } from "./authorization-constraints.js";
|
|
import type { createPersonalConnectionIdentity } from "../connections/personal-identity.js";
|
|
import { connectionRemovedOrSignInCancelled } from "../connections/first-sign-in.js";
|
|
|
|
type Dependencies = {
|
|
now: () => Date;
|
|
getConnectionRow(idOrUid: string, companyId?: string): Promise<typeof toolConnections.$inferSelect>;
|
|
setupPolicy: ConnectionSetupPolicy;
|
|
fixedPersonalIdentityForReconnect: ReturnType<typeof createPersonalConnectionIdentity>;
|
|
currentCloudConnector: () => PaperclipCloudConnector | null;
|
|
vercelConnect: VercelConnectClient | null;
|
|
ensureOAuthClient: ReturnType<typeof createOAuthClientRegistration>;
|
|
oauthEndpointsForConnection: ReturnType<typeof createOAuthDiscovery>["oauthEndpointsForConnection"];
|
|
assertOAuthEndpointUrl: ReturnType<typeof createOAuthEndpointPolicy>["assertOAuthEndpointUrl"];
|
|
};
|
|
|
|
function googleSignInCloudOnlyError() {
|
|
return unprocessable(GOOGLE_SIGN_IN_CLOUD_ONLY_MESSAGE, { code: "google_sign_in_cloud_only" });
|
|
}
|
|
|
|
function cloudConnectorStartHttpError(error: unknown, provider: string, providerName: string, at: Date): unknown {
|
|
if (!(error instanceof PaperclipCloudConnectorError)) return error;
|
|
if (provider === "google" && error.brokerReason === "PROVIDER_CLOUD_ONLY") return googleSignInCloudOnlyError();
|
|
if (error.status !== 429 && error.brokerReason !== "RATE_LIMITED") return error;
|
|
const retryAfterSeconds = error.retryAt === undefined
|
|
? undefined
|
|
: Math.max(1, Math.ceil((error.retryAt - at.getTime()) / 1000));
|
|
return tooManyRequests(`${providerName} sign-in is busy right now. Try again in a moment.`, {
|
|
code: "paperclip_cloud_connector_rate_limited",
|
|
...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }),
|
|
});
|
|
}
|
|
|
|
export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies) {
|
|
const { now, getConnectionRow, setupPolicy, fixedPersonalIdentityForReconnect, currentCloudConnector, vercelConnect, ensureOAuthClient, oauthEndpointsForConnection, assertOAuthEndpointUrl } = dependencies;
|
|
const { assertConnectorConnectionSetupEnabled, assertExperimentalConnectorSetupEnabled } = setupPolicy;
|
|
async function startOAuth(
|
|
companyId: string,
|
|
connectionId: string,
|
|
input: {
|
|
redirectUri: string;
|
|
actor: ActorInfo;
|
|
subjectUserId?: string;
|
|
subjectAgentId?: string;
|
|
scopes?: string[];
|
|
workspaceServices?: GoogleWorkspaceServiceSelection;
|
|
returnTo?: string;
|
|
issueId?: string;
|
|
interactionId?: string;
|
|
},
|
|
): Promise<ToolOAuthStartResult> {
|
|
await input.actor.managementContext?.reauthorize();
|
|
let connection = await getConnectionRow(connectionId, companyId);
|
|
assertSupportedConnection(connection);
|
|
await assertConnectorConnectionSetupEnabled(connection);
|
|
await assertExperimentalConnectorSetupEnabled(connection.config.sourceTemplateKey, connection.status !== "draft");
|
|
if (connectionRemovedOrSignInCancelled(connection))
|
|
throw conflict("Archived app connections cannot start sign in");
|
|
const sourceTemplateKey =
|
|
typeof connection.config.sourceTemplateKey === "string"
|
|
? connection.config.sourceTemplateKey
|
|
: null;
|
|
const galleryEntry = sourceTemplateKey
|
|
? getConnectableAppDefinition(sourceTemplateKey)
|
|
: null;
|
|
assertOAuthRedirectConstraints(galleryEntry, input.redirectUri);
|
|
const galleryMethod = galleryEntry
|
|
? connectionMethodForConnection(galleryEntry, connection)
|
|
: null;
|
|
const starterBinding = actorBinding(input.actor);
|
|
const fixedPersonalIdentity = await fixedPersonalIdentityForReconnect(
|
|
connection,
|
|
input.subjectUserId,
|
|
input.actor,
|
|
);
|
|
const authorizationSubjectUserId =
|
|
fixedPersonalIdentity?.subjectUserId ?? input.subjectUserId;
|
|
const authorizationSubjectAgentId = input.subjectAgentId;
|
|
const workspaceDraftBinding = {
|
|
companyId, connectionId: connection.id,
|
|
actorType: starterBinding.actorType, actorId: starterBinding.actorId,
|
|
grantKind: connection.credentialPolicy === "per_user" ? "user" as const
|
|
: connection.credentialPolicy === "per_agent" ? "agent" as const : "organization" as const,
|
|
subjectId: connection.credentialPolicy === "per_user" ? authorizationSubjectUserId ?? null
|
|
: connection.credentialPolicy === "per_agent" ? authorizationSubjectAgentId ?? null : null,
|
|
};
|
|
const requestedScopes = await (async () => {
|
|
if (input.workspaceServices && sourceTemplateKey !== "google-workspace") throw badRequest("Service selection requires Google Workspace");
|
|
if (sourceTemplateKey === "google-workspace") {
|
|
if (input.workspaceServices && input.scopes) throw badRequest("Choose services or scopes, not both");
|
|
const allowed = normalizeOauthScopes(galleryMethod?.defaults?.scopesHint);
|
|
let scopes = input.scopes ?? (input.workspaceServices ? googleWorkspaceSelectedScopes(input.workspaceServices) : undefined);
|
|
if (!scopes && connection.status === "draft") {
|
|
scopes = googleWorkspaceDraftRequestedScopes(connection.config.workspaceSetup, workspaceDraftBinding) ?? undefined;
|
|
}
|
|
if (!scopes && input.actor.managementContext?.actor.type === "agent") return null;
|
|
if (!scopes) {
|
|
// Account-page reconnect has no new service choice. Never replace its
|
|
// subject's saved request with the new-account write defaults.
|
|
const subjectUserId = authorizationSubjectUserId ?? (starterBinding.actorType === "user" ? starterBinding.actorId : null);
|
|
const kind = connection.credentialPolicy === "per_user" ? "user"
|
|
: connection.credentialPolicy === "per_agent" ? "agent" : "organization";
|
|
const [grant] = await db.select().from(connectionGrants).where(and(
|
|
eq(connectionGrants.companyId, companyId),
|
|
eq(connectionGrants.connectionId, connection.id),
|
|
eq(connectionGrants.kind, kind),
|
|
kind === "user" ? eq(connectionGrants.subjectUserId, subjectUserId ?? "")
|
|
: kind === "agent" ? eq(connectionGrants.subjectAgentId, input.subjectAgentId ?? "")
|
|
: eq(connectionGrants.isDefault, true),
|
|
)).limit(1);
|
|
const saved = grant?.providerTenant?.oauth;
|
|
scopes = normalizeOauthScopes(saved?.requestedScopes ?? (connection.status !== "draft" ? saved?.scopes : undefined))
|
|
.filter(scope => allowed.includes(scope));
|
|
if (scopes.length === 0) throw badRequest(connection.status === "draft"
|
|
? "Choose your Google Workspace services before continuing setup"
|
|
: "Choose your Google Workspace services before reconnecting");
|
|
}
|
|
if (!isGoogleWorkspaceScopeGrant(scopes) || scopes.some(scope => !allowed.includes(scope))) throw badRequest("Select at least one supported Google service");
|
|
return scopes;
|
|
}
|
|
if (!galleryMethod) return input.scopes ?? null;
|
|
const allowed = normalizeOauthScopes(galleryMethod.defaults?.scopesHint);
|
|
if (!input.scopes) return allowed;
|
|
const requested = normalizeOauthScopes(input.scopes);
|
|
const widened = requested.filter((scope) => !allowed.includes(scope));
|
|
if (widened.length > 0) {
|
|
throw badRequest(
|
|
`Requested OAuth scopes are not allowed for ${galleryEntry?.name ?? "this app"}`,
|
|
{
|
|
code: "oauth_scope_widening_rejected",
|
|
scopes: widened,
|
|
},
|
|
);
|
|
}
|
|
return requested;
|
|
})();
|
|
if (authorizationSubjectAgentId) {
|
|
const [subjectAgent] = await db
|
|
.select({ id: agents.id })
|
|
.from(agents)
|
|
.where(
|
|
and(
|
|
eq(agents.id, authorizationSubjectAgentId),
|
|
eq(agents.companyId, companyId),
|
|
),
|
|
)
|
|
.limit(1);
|
|
if (!subjectAgent)
|
|
throw badRequest(
|
|
"Dedicated identity requires an agent in this company",
|
|
);
|
|
if (connection.credentialPolicy !== "per_agent") {
|
|
throw badRequest(
|
|
"This connection is not configured for a dedicated agent identity",
|
|
);
|
|
}
|
|
}
|
|
const intentLink = input.interactionId
|
|
? await db
|
|
.select({
|
|
id: issueThreadInteractions.id,
|
|
issueId: issueThreadInteractions.issueId,
|
|
addresseeUserId: issueThreadInteractions.addresseeUserId,
|
|
kind: issueThreadInteractions.kind,
|
|
status: issueThreadInteractions.status,
|
|
})
|
|
.from(issueThreadInteractions)
|
|
.where(
|
|
and(
|
|
eq(issueThreadInteractions.id, input.interactionId),
|
|
eq(issueThreadInteractions.companyId, companyId),
|
|
),
|
|
)
|
|
.limit(1)
|
|
.then((rows) => rows[0] ?? null)
|
|
: null;
|
|
if (
|
|
input.interactionId &&
|
|
(!intentLink ||
|
|
intentLink.kind !== "connection_intent" ||
|
|
intentLink.status !== "pending" ||
|
|
(input.actor.managementContext?.responsibleUserId ?? (starterBinding.actorType === "user" ? starterBinding.actorId : null)) !== intentLink.addresseeUserId)
|
|
) {
|
|
throw forbidden(
|
|
"Only the addressed user can authorize this connection request",
|
|
);
|
|
}
|
|
if (input.actor.managementContext?.actor.type === "agent") {
|
|
// An agent has no browser session. Reuse the saved setup; the addressed
|
|
// human starts provider authorization in their own authenticated session.
|
|
// No provider state or credentials are issued by this handoff.
|
|
if (sourceTemplateKey === "google-workspace" && (input.workspaceServices || input.scopes)) {
|
|
await input.actor.managementContext.reauthorize();
|
|
const userId = input.actor.managementContext.responsibleUserId!;
|
|
await db.transaction(async tx => {
|
|
const [saved] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId))).for("no key update");
|
|
if (!saved) throw notFound("Connection not found");
|
|
const rawOauth = saved.config.oauth;
|
|
const oauth = rawOauth && typeof rawOauth === "object" && !Array.isArray(rawOauth) ? rawOauth as Record<string, unknown> : {};
|
|
const prior = oauth.pendingWorkspaceServiceRequests;
|
|
const pending = prior && typeof prior === "object" && !Array.isArray(prior) ? prior as Record<string, unknown> : {};
|
|
const requested = { ...pending, [userId]: { requestedScopes, requestedAt: now().toISOString() } };
|
|
const config = { ...saved.config, oauth: { ...oauth, pendingWorkspaceServiceRequests: requested } };
|
|
const transportOauth = saved.transportConfig.oauth;
|
|
const transportConfig = { ...saved.transportConfig, oauth: { ...(transportOauth && typeof transportOauth === "object" && !Array.isArray(transportOauth) ? transportOauth : {}), pendingWorkspaceServiceRequests: requested } };
|
|
await tx.update(toolConnections).set({ config, transportConfig, updatedAt: now() }).where(eq(toolConnections.id, saved.id));
|
|
});
|
|
}
|
|
const [company] = await db.select({ prefix: companies.issuePrefix }).from(companies).where(eq(companies.id, companyId));
|
|
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.
|
|
// 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 };
|
|
}
|
|
if (sourceTemplateKey === "google-workspace" && connection.status === "draft") {
|
|
const workspaceSetup = { version: 1, ...workspaceDraftBinding, requestedScopes };
|
|
const updated = await db.transaction(async tx => {
|
|
const [saved] = await tx.select().from(toolConnections).where(and(
|
|
eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId), eq(toolConnections.status, "draft"),
|
|
)).for("no key update");
|
|
if (!saved || (["credentialPolicy", "credentialSource", "authKind", "transport", "createdByUserId"] as const)
|
|
.some(key => saved[key] !== connection[key])
|
|
|| ["sourceTemplateKey", "connectionMethodKey"].some(key => saved.config[key] !== connection.config[key]
|
|
|| saved.transportConfig[key] !== connection.transportConfig[key])) {
|
|
throw conflict("Connection setup changed. Reload before continuing");
|
|
}
|
|
const config: Record<string, unknown> = { ...saved.config, workspaceSetup };
|
|
const transportConfig: Record<string, unknown> = { ...saved.transportConfig, workspaceSetup };
|
|
if (starterBinding.actorType === "user" && starterBinding.actorId) {
|
|
for (const target of [config, transportConfig]) {
|
|
const oauth = asRecord(target.oauth);
|
|
const pending = { ...asRecord(oauth.pendingWorkspaceServiceRequests) };
|
|
if (Object.hasOwn(pending, starterBinding.actorId)) {
|
|
delete pending[starterBinding.actorId];
|
|
target.oauth = { ...oauth, pendingWorkspaceServiceRequests: pending };
|
|
}
|
|
}
|
|
}
|
|
const [row] = await tx.update(toolConnections).set({ config, transportConfig, updatedAt: now() })
|
|
.where(and(eq(toolConnections.id, saved.id), eq(toolConnections.companyId, companyId), eq(toolConnections.status, "draft"))).returning();
|
|
return row;
|
|
});
|
|
if (!updated) throw conflict("Connection setup changed. Reload before continuing");
|
|
connection = updated;
|
|
}
|
|
if (connection.credentialSource === "vercel_connect") {
|
|
if (!vercelConnect)
|
|
throw vercelConnectHttpError(
|
|
new VercelConnectClientError("vercel_connect_unavailable", 503),
|
|
);
|
|
const credential = vercelCredentialFor(connection);
|
|
if (
|
|
connection.authKind !== "oauth" ||
|
|
credential.principalMode !== "user"
|
|
) {
|
|
throw badRequest(
|
|
"This Vercel connector does not use browser authorization",
|
|
);
|
|
}
|
|
const binding = starterBinding;
|
|
if (!binding.actorType || !binding.actorId) {
|
|
throw forbidden(
|
|
"Vercel Connect authorization requires an authenticated actor",
|
|
);
|
|
}
|
|
const grantKind: ConnectionGrantKind = authorizationSubjectUserId
|
|
? "user"
|
|
: "organization";
|
|
const derived = deriveVercelConnectSubject({
|
|
credential,
|
|
connectionId: connection.id,
|
|
companyId,
|
|
grantKind,
|
|
subjectUserId: authorizationSubjectUserId,
|
|
});
|
|
const state = randomOauthToken();
|
|
let authorization;
|
|
try {
|
|
authorization = await vercelConnect.startAuthorization(
|
|
{
|
|
connector: credential.connectorUid,
|
|
subject: derived.subject,
|
|
scopes: credential.scopes,
|
|
resources: vercelConnectResourcesFor(connection),
|
|
},
|
|
vercelConnectCallbackUrl(input.redirectUri, state),
|
|
);
|
|
} catch (error) {
|
|
throw vercelConnectHttpError(error);
|
|
}
|
|
const remoteExpiry = authorization.expiresAt
|
|
? new Date(authorization.expiresAt)
|
|
: null;
|
|
const expiresAt =
|
|
remoteExpiry && Number.isFinite(remoteExpiry.getTime())
|
|
? new Date(
|
|
Math.min(
|
|
remoteExpiry.getTime(),
|
|
now().getTime() + 10 * 60 * 1000,
|
|
),
|
|
)
|
|
: new Date(now().getTime() + 10 * 60 * 1000);
|
|
await db
|
|
.delete(toolOauthStates)
|
|
.where(lt(toolOauthStates.expiresAt, now()));
|
|
await db.insert(toolOauthStates).values({
|
|
state,
|
|
companyId,
|
|
connectionId: connection.id,
|
|
// Vercel owns its verifier. This marker only dispatches the consumed
|
|
// one-time state to the Vercel callback completion path.
|
|
codeVerifier: "vercel-connect",
|
|
createdByActorType: binding.actorType,
|
|
createdByActorId: binding.actorId,
|
|
createdBySessionId: binding.sessionId,
|
|
subjectUserId: authorizationSubjectUserId,
|
|
requestedScopes: [...credential.scopes],
|
|
returnTo: input.returnTo,
|
|
issueId: intentLink?.issueId ?? input.issueId,
|
|
interactionId: intentLink?.id,
|
|
expiresAt,
|
|
});
|
|
return {
|
|
connectionId: connection.id,
|
|
provider: `vercel-connect:${credential.service}`,
|
|
authorizationUrl: authorization.url,
|
|
expiresAt: expiresAt.toISOString(),
|
|
issuer: "https://vercel.com/connect",
|
|
resource: galleryMethod?.defaults?.serverUrl ?? null,
|
|
registrationSource: null,
|
|
};
|
|
}
|
|
if (
|
|
galleryMethod &&
|
|
isPaperclipCloudConnectorStrategy(galleryMethod.oauthStrategy)
|
|
) {
|
|
const connectorProfile = galleryMethod.connectorProfile;
|
|
const managedProfile = managedConnectorProfile(connectorProfile);
|
|
if (!managedProfile)
|
|
throw badRequest("This app has an invalid managed connector profile");
|
|
const providerName = galleryEntry?.name ?? "Google Workspace";
|
|
if (managedProfile.provider === "google" && !paperclipGoogleSignInAvailable()) throw googleSignInCloudOnlyError();
|
|
if (!paperclipCloudConnectorConsentAllowed(managedProfile.id)) {
|
|
throw unprocessable(
|
|
`${providerName} can no longer be connected through Paperclip with these permissions. Connect Google Workspace, or set up ${providerName} with your own Google OAuth app.`,
|
|
{ code: "paperclip_cloud_connector_scope_not_offered" },
|
|
);
|
|
}
|
|
const cloudConnector = currentCloudConnector();
|
|
if (!cloudConnector) {
|
|
throw unprocessable(
|
|
`${providerName} connections through Paperclip are not available on this instance yet`,
|
|
{
|
|
code: "paperclip_cloud_connector_unavailable",
|
|
},
|
|
);
|
|
}
|
|
const binding = starterBinding;
|
|
if (!binding.actorType || !binding.actorId) {
|
|
throw forbidden(
|
|
`${providerName} sign-in requires an authenticated actor`,
|
|
);
|
|
}
|
|
const subjectUserId = authorizationSubjectAgentId
|
|
? null
|
|
: (authorizationSubjectUserId ??
|
|
(binding.actorType === "user" ? binding.actorId : null));
|
|
if (!subjectUserId && !authorizationSubjectAgentId) {
|
|
throw forbidden(
|
|
`Agent-started ${providerName} sign-in requires an authorized identity`,
|
|
);
|
|
}
|
|
if (
|
|
!authorizationSubjectAgentId &&
|
|
binding.actorType === "user" &&
|
|
subjectUserId !== binding.actorId
|
|
) {
|
|
throw forbidden(
|
|
`Board users may only authorize their own ${providerName} identity`,
|
|
);
|
|
}
|
|
await db
|
|
.delete(toolOauthStates)
|
|
.where(lt(toolOauthStates.expiresAt, now()));
|
|
const state = randomOauthToken();
|
|
const returnUri = new URL(input.redirectUri);
|
|
returnUri.pathname = "/api/tools/oauth/cloud-connector/callback";
|
|
returnUri.search = "";
|
|
returnUri.hash = "";
|
|
let session;
|
|
try {
|
|
session = await cloudConnector.startAuthorization({
|
|
subject: authorizationSubjectAgentId
|
|
? `agent:${authorizationSubjectAgentId}`
|
|
: subjectUserId!,
|
|
companyId,
|
|
profile: managedProfile.id,
|
|
...(managedProfile.id === "workspace.all" ? { scopes: requestedScopes! } : {}),
|
|
returnUri: returnUri.toString(),
|
|
returnState: state,
|
|
});
|
|
} catch (error) {
|
|
throw cloudConnectorStartHttpError(error, managedProfile.provider, providerName, now());
|
|
}
|
|
const remoteExpiry = new Date(session.expiresAt);
|
|
const expiresAt = Number.isFinite(remoteExpiry.getTime())
|
|
? new Date(
|
|
Math.min(remoteExpiry.getTime(), now().getTime() + 10 * 60 * 1000),
|
|
)
|
|
: new Date(now().getTime() + 10 * 60 * 1000);
|
|
await db.insert(toolOauthStates).values({
|
|
state,
|
|
companyId,
|
|
connectionId: connection.id,
|
|
// Paperclip Cloud owns PKCE for this flow. The local state row remains the
|
|
// single-use browser correlator and never stores broker token material.
|
|
codeVerifier: "paperclip-cloud-connector",
|
|
createdByActorType: binding.actorType,
|
|
createdByActorId: binding.actorId,
|
|
createdBySessionId: binding.sessionId,
|
|
subjectUserId,
|
|
subjectAgentId: authorizationSubjectAgentId,
|
|
requestedScopes: managedProfile.id === "workspace.all" ? requestedScopes! : [...managedProfile.scopes],
|
|
returnTo: input.returnTo,
|
|
issueId: intentLink?.issueId ?? input.issueId,
|
|
interactionId: intentLink?.id,
|
|
expiresAt,
|
|
});
|
|
return {
|
|
connectionId: connection.id,
|
|
provider: managedProfile.provider,
|
|
authorizationUrl: session.authorizationUrl,
|
|
expiresAt: expiresAt.toISOString(),
|
|
...(session.handoff ? { handoff: session.handoff } : {}),
|
|
issuer:
|
|
managedProfile.provider === "github"
|
|
? "https://github.com"
|
|
: managedProfile.provider === "asana"
|
|
? "https://app.asana.com"
|
|
: "https://accounts.google.com",
|
|
resource: galleryMethod.defaults?.serverUrl ?? null,
|
|
registrationSource: null,
|
|
};
|
|
}
|
|
const endpoints = await oauthEndpointsForConnection(
|
|
connection,
|
|
null,
|
|
input.redirectUri,
|
|
);
|
|
if (endpoints.grantType === "client_credentials") {
|
|
throw unprocessable(
|
|
"This app uses shared machine credentials and does not need browser sign in",
|
|
);
|
|
}
|
|
const resolvedClient = await ensureOAuthClient({
|
|
connection,
|
|
endpoints,
|
|
redirectUri: input.redirectUri,
|
|
galleryEntry,
|
|
actor: input.actor,
|
|
});
|
|
connection = resolvedClient.connection;
|
|
const client = resolvedClient.client;
|
|
if (galleryMethod?.oauthClientSecretRequired && !client.clientSecret) {
|
|
throw unprocessable("This app requires an OAuth client secret. Add it in the app setup before signing in.");
|
|
}
|
|
if (!client.clientId)
|
|
throw unprocessable(
|
|
`OAuth client id is not configured for ${endpoints.provider}`,
|
|
);
|
|
|
|
const authorizationScopes = normalizeOauthScopes(
|
|
galleryMethod ? (requestedScopes ?? []) : (input.scopes ?? endpoints.scopes),
|
|
);
|
|
if (
|
|
!galleryMethod &&
|
|
endpoints.offlineAccessSupported &&
|
|
(!endpoints.grantTypesSupported?.length ||
|
|
endpoints.grantTypesSupported.includes("refresh_token")) &&
|
|
!authorizationScopes.includes("offline_access")
|
|
) authorizationScopes.push("offline_access");
|
|
|
|
await db
|
|
.delete(toolOauthStates)
|
|
.where(lt(toolOauthStates.expiresAt, new Date()));
|
|
|
|
const state = randomOauthToken();
|
|
const codeVerifier = randomOauthToken(48);
|
|
const expiresAt = new Date(Date.now() + 10 * 60 * 1000);
|
|
const binding = starterBinding;
|
|
if (!binding.actorType || !binding.actorId) {
|
|
throw forbidden("OAuth sign-in requires an authenticated board session");
|
|
}
|
|
await db.insert(toolOauthStates).values({
|
|
state,
|
|
companyId,
|
|
connectionId: connection.id,
|
|
codeVerifier,
|
|
createdByActorType: binding.actorType,
|
|
createdByActorId: binding.actorId,
|
|
createdBySessionId: binding.sessionId,
|
|
subjectUserId: authorizationSubjectUserId,
|
|
requestedScopes: authorizationScopes,
|
|
returnTo: input.returnTo,
|
|
issueId: intentLink?.issueId ?? input.issueId,
|
|
interactionId: intentLink?.id,
|
|
expiresAt,
|
|
});
|
|
|
|
// Last gate before this URL becomes a top-level browser navigation. Every
|
|
// producer above already validates, so reaching a rejection here means a new
|
|
// path was added without one — fail closed rather than hand the board an
|
|
// unvetted target.
|
|
const authorizationUrl = new URL(
|
|
assertOAuthEndpointUrl("authorization", endpoints.authorizationUrl, {
|
|
// Paperclip's own callback origin: a first-party authorization endpoint is
|
|
// served however this deployment is served, plaintext LAN host included.
|
|
firstPartyOrigin: originOf(input.redirectUri),
|
|
}),
|
|
);
|
|
authorizationUrl.searchParams.set("response_type", "code");
|
|
authorizationUrl.searchParams.set("client_id", client.clientId);
|
|
authorizationUrl.searchParams.set("redirect_uri", input.redirectUri);
|
|
authorizationUrl.searchParams.set("state", state);
|
|
authorizationUrl.searchParams.set(
|
|
"code_challenge",
|
|
base64UrlSha256(codeVerifier),
|
|
);
|
|
authorizationUrl.searchParams.set("code_challenge_method", "S256");
|
|
// RFC 8707: name the MCP server the resulting token is for, so an
|
|
// authorization server that serves several resources can audience-restrict it.
|
|
if (endpoints.resource)
|
|
authorizationUrl.searchParams.set("resource", endpoints.resource);
|
|
// Curated definitions are an allowlist, not a suggestion. Never copy every
|
|
// scope advertised by discovery into a provider consent screen: a curated
|
|
// method either sends its reviewed hint or omits scope entirely. Generic
|
|
// MCP URLs retain discovery-first behavior because Paperclip has no manifest
|
|
// against which it could safely judge the caller's requested scope.
|
|
if (authorizationScopes.length > 0)
|
|
authorizationUrl.searchParams.set("scope", authorizationScopes.join(" "));
|
|
if (galleryMethod && connection.config.sourceTemplateKey === "google-workspace")
|
|
authorizationUrl.searchParams.set("enable_granular_consent", "true");
|
|
const reviewedAuthorizationParams =
|
|
galleryMethod?.defaults?.oauthAuthorizationParams;
|
|
if (reviewedAuthorizationParams?.access_type)
|
|
authorizationUrl.searchParams.set(
|
|
"access_type",
|
|
reviewedAuthorizationParams.access_type,
|
|
);
|
|
if (reviewedAuthorizationParams?.prompt)
|
|
authorizationUrl.searchParams.set(
|
|
"prompt",
|
|
reviewedAuthorizationParams.prompt,
|
|
);
|
|
else if (!galleryMethod && authorizationScopes.includes("offline_access"))
|
|
// OIDC offline access requires consent unless the provider has another
|
|
// established basis for granting it. A generic server has no reviewed override.
|
|
authorizationUrl.searchParams.set("prompt", "consent");
|
|
|
|
if (
|
|
authorizationSubjectUserId &&
|
|
input.issueId &&
|
|
binding.actorType === "agent"
|
|
) {
|
|
const idempotencyKey = `connection-authorization:${connection.id}:${authorizationSubjectUserId}`;
|
|
// Provider label for the card's copy. The gallery definition's name when we
|
|
// have one, else the connection's own name — never a secret name or ref.
|
|
const sourceTemplateKey =
|
|
typeof connection.config.sourceTemplateKey === "string"
|
|
? connection.config.sourceTemplateKey
|
|
: null;
|
|
const providerName =
|
|
(sourceTemplateKey
|
|
? getConnectableAppDefinition(sourceTemplateKey)?.name
|
|
: null) ?? connection.name;
|
|
const [requestingAgent] = binding.actorId
|
|
? await db
|
|
.select({ name: agents.name })
|
|
.from(agents)
|
|
.where(
|
|
and(
|
|
eq(agents.id, binding.actorId),
|
|
eq(agents.companyId, companyId),
|
|
),
|
|
)
|
|
.limit(1)
|
|
: [undefined];
|
|
const payload = {
|
|
version: 1 as const,
|
|
prompt: `Connect your ${providerName} to continue`,
|
|
acceptLabel: `Connect ${providerName}`,
|
|
rejectLabel: "Not now",
|
|
detailsMarkdown:
|
|
"Authorization is required before this agent can act on your behalf.",
|
|
// Presentation metadata so the card can compose its own copy instead of
|
|
// parsing the title string (PAP-17835 seam #6). The interaction kind and
|
|
// the server-addressed audience are unchanged.
|
|
connectionAuthorization: {
|
|
version: 1 as const,
|
|
providerName,
|
|
connectionName:
|
|
connection.name === providerName ? null : connection.name,
|
|
requestingAgentName: requestingAgent?.name ?? null,
|
|
},
|
|
target: {
|
|
type: "custom" as const,
|
|
key: `connection:${connection.uid}:user:${authorizationSubjectUserId}`,
|
|
revisionId: state,
|
|
label: `Connect ${providerName}`,
|
|
href: authorizationUrl.toString(),
|
|
},
|
|
};
|
|
const issueId = input.issueId;
|
|
await db.transaction(async tx => {
|
|
await notifyIssueReviewState(tx, { companyId, issueId });
|
|
const [existingInteraction] = await tx
|
|
.select()
|
|
.from(issueThreadInteractions)
|
|
.where(
|
|
and(
|
|
eq(issueThreadInteractions.companyId, companyId),
|
|
eq(issueThreadInteractions.issueId, issueId),
|
|
eq(issueThreadInteractions.idempotencyKey, idempotencyKey),
|
|
),
|
|
)
|
|
.limit(1);
|
|
const [interaction] = existingInteraction
|
|
? await tx
|
|
.update(issueThreadInteractions)
|
|
.set({
|
|
status: "pending",
|
|
requestedResolverPolicy: "human_only",
|
|
effectiveResolverPolicy: "human_only",
|
|
resolverPolicyProvenance: "explicit",
|
|
effectiveResolverPolicySource: "requested",
|
|
addresseeUserId: authorizationSubjectUserId,
|
|
payload,
|
|
result: null,
|
|
resolvedAt: null,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(issueThreadInteractions.id, existingInteraction.id))
|
|
.returning()
|
|
: await tx
|
|
.insert(issueThreadInteractions)
|
|
.values({
|
|
companyId,
|
|
issueId: issueId,
|
|
kind: "request_confirmation",
|
|
status: "pending",
|
|
continuationPolicy: "none",
|
|
requestedResolverPolicy: "human_only",
|
|
effectiveResolverPolicy: "human_only",
|
|
resolverPolicyProvenance: "explicit",
|
|
effectiveResolverPolicySource: "requested",
|
|
addresseeUserId: authorizationSubjectUserId,
|
|
idempotencyKey,
|
|
sourceRunId:
|
|
binding.actorType === "agent"
|
|
? (input.actor.sessionId ?? null)
|
|
: null,
|
|
title: `Connect your ${providerName} to continue`,
|
|
summary: `${requestingAgent?.name ?? "An agent"} needs your ${providerName} identity for work running as you.`,
|
|
createdByAgentId:
|
|
binding.actorType === "agent" ? binding.actorId : null,
|
|
payload,
|
|
})
|
|
.returning();
|
|
if (interaction) {
|
|
await tx
|
|
.update(toolOauthStates)
|
|
.set({ interactionId: interaction.id })
|
|
.where(eq(toolOauthStates.state, state));
|
|
}
|
|
});
|
|
}
|
|
|
|
await db.transaction(async tx => {
|
|
const [saved] = await tx.select().from(toolConnections).where(and(
|
|
eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId),
|
|
)).for("no key update");
|
|
if (!saved) throw notFound("Tool connection not found");
|
|
assertOAuthClientBindingUnchanged(connection, saved, endpoints, input.redirectUri);
|
|
const oauth = {
|
|
provider: endpoints.provider,
|
|
authorizationUrl: endpoints.authorizationUrl,
|
|
tokenUrl: endpoints.tokenUrl,
|
|
registrationUrl: endpoints.registrationUrl ?? null,
|
|
metadataUrl: endpoints.metadataUrl ?? null,
|
|
// Curated apps persist only the reviewed scopes attached to this OAuth
|
|
// state. Discovery metadata can advertise a provider's entire scope
|
|
// universe and must never silently become Paperclip's requested set.
|
|
scopes: authorizationScopes,
|
|
offlineAccessSupported: endpoints.offlineAccessSupported,
|
|
grantTypesSupported: endpoints.grantTypesSupported ?? [],
|
|
codeChallengeMethodsSupported:
|
|
endpoints.codeChallengeMethodsSupported ?? [],
|
|
tokenEndpointAuthMethodsSupported:
|
|
endpoints.tokenEndpointAuthMethodsSupported ?? [],
|
|
grantType: "authorization_code",
|
|
clientIdEnv: client.clientIdEnv,
|
|
clientSecretEnv: client.clientSecret ? client.clientSecretEnv : null,
|
|
credentialScope: credentialScope(connection, input.actor),
|
|
// Persist the issuer and resource this authorization run is bound to.
|
|
// `iss` on the callback is validated against `expectedIssuer`, and
|
|
// refresh/reconnect/revoke reuse the same pair rather than re-deriving it.
|
|
issuer: endpoints.issuer ?? oauthConfig(saved).issuer ?? null,
|
|
expectedIssuer: endpoints.issuer ?? null,
|
|
// RFC 9207: when the server promises `iss`, a callback without it is refused.
|
|
expectIssParameter: Boolean(endpoints.issuer) && endpoints.issParameterSupported === true,
|
|
resource:
|
|
endpoints.resource ?? oauthConfig(saved).resource ?? null,
|
|
clientIdMetadataDocumentSupported:
|
|
endpoints.clientIdMetadataDocumentSupported === true,
|
|
issParameterSupported: endpoints.issParameterSupported === true,
|
|
};
|
|
const nextConfig = { ...saved.config, oauth: { ...oauthConfig(saved), ...oauth } };
|
|
const nextTransportConfig = { ...saved.transportConfig, oauth: { ...asRecord(saved.transportConfig.oauth), ...oauth } };
|
|
await tx
|
|
.update(toolConnections)
|
|
.set({
|
|
// A generic URL connection starts life as `authKind: none`. Once it has
|
|
// completed OAuth discovery and client resolution it is an OAuth
|
|
// connection, and refresh, reconnect, revoke and diagnostics must all
|
|
// treat it as one.
|
|
authKind: "oauth",
|
|
config: nextConfig,
|
|
transportConfig: nextTransportConfig,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId)));
|
|
});
|
|
|
|
return {
|
|
connectionId: connection.id,
|
|
provider: endpoints.provider,
|
|
authorizationUrl: authorizationUrl.toString(),
|
|
expiresAt: expiresAt.toISOString(),
|
|
issuer: endpoints.issuer ?? null,
|
|
resource: endpoints.resource ?? null,
|
|
registrationSource: resolvedClient.source,
|
|
};
|
|
}
|
|
return startOAuth;
|
|
}
|