mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use apps through connections. Most app connections use an OAuth sign-in. > - Paperclip saves a draft connection before it opens the provider sign-in page. > - When the user cancels or abandons that sign-in, the draft stays. The Apps list counts it as a connection that "needs attention". > - The user did not ask for that connection, and the user must not clean it up by hand. > - This pull request hides drafts that never finished their first sign-in and removes the draft when the user clicks Cancel. > - The benefit is that a cancelled sign-in leaves no visible connection, and a retry makes exactly one connection. ## Linked Issues or Issue Description Refs #22634 **What happened?** A workspace has one working "Google Workspace for the organization" connection. The user clicks "Add account", chooses services, and clicks Continue. The page shows "Opening Google Workspace…". The user clicks Cancel before finishing at Google. The Apps page then shows "2 connections · 1 needs attention". **What did you expect to happen?** A cancelled sign-in leaves no visible connection. The same applies when the user closes the page, reloads it, closes the Google tab, or refuses consent at Google. A retry after a cancel makes exactly one connection. A cancelled reconnect of a working connection does not change that connection. **Steps to reproduce** 1. Connect one Google Workspace account. 2. Open Apps, then Google Workspace, then "Add account". 3. Click "Continue to sign in", choose services, and click Continue. 4. On the "Opening Google Workspace" page, click Cancel. 5. Look at the Google Workspace card on the Apps page. ## What Changed - Root cause: `connectApp` saves an OAuth draft (`status: "draft"`) before sign-in (`server/src/services/tool-access.ts`, the connection insert in the connect path). Cancel only navigated away. The Apps list counted every draft as "needs attention" (`ui/src/pages/apps/Browse.tsx`, `connectionState` and the attention count). - New module `server/src/services/tool-access/connections/first-sign-in.ts`. It decides if an OAuth draft never held a credential. It checks for OAuth tokens on the connection and its grants, legacy inline tokens (the removal module's list), a provider consent time, an external credential, and the markers a real connection keeps when it needs a new sign-in. If any check is not clear, the connection counts as real. - The connection list endpoint sets `firstSignInPending: true` on those drafts. The shared `ToolConnection` type has the new field. - New route `POST /tool-connections/:connectionId/sign-in/cancel`. It checks company access and configure permission. It removes the draft with the normal removal teardown (grants, OAuth states, bindings) only if the draft never held a credential. For any other connection it changes nothing and returns `abandoned: false`. A removal writes the activity entry `tool_connection.sign_in_cancelled`. The route is in the OpenAPI registry. - The Apps list does not show connections with `firstSignInPending`, and it does not show an app whose only connections are such drafts. The check is one pass with `Set` lookups. - Cancel works in one transaction: it deletes the pending sign-in states, locks the connection, checks it again, and parks it as `disabled` with the marker `oauth_sign_in_cancelled`. If the connection must stay, the transaction rolls back. Then the normal removal archives the parked draft. Setup never reuses a parked draft, so a retry during the removal gets its own row. - One predicate, `connectionRemovedOrSignInCancelled`, guards authorization start, access finish and machine sign-in. The direct, Cloud and Vercel Connect callbacks and the access finish step lock the connection before they write a grant or activate it, and return 409 `oauth_sign_in_cancelled` for a parked draft. - `docs/api/tool-connections.md` documents the cancel route and the list flag. - The setup page calls the cancel route when the user clicks Cancel on the sign-in screen. It does this only for a draft that this page made. It does not do this for a resume, a reconnect, or a task-linked setup. - Design for abandoned drafts (tab closed, reload, consent refused): they are not listed, and the next attempt reuses them through the existing draft reuse in setup. No background cleanup job is added. ## Verification - `server/src/__tests__/tool-access-cancelled-first-sign-in.integration.test.ts` runs the real routes against embedded Postgres and a local OAuth provider. It covers: a draft is marked and hidden; a provider token exchange held open across Cancel ends in 409; Cancel and a retry at the same time leave exactly one active connection; a parked draft is hidden and refuses a new sign-in start; a legacy draft with an inline token is not cancelled; Cancel removes it, deletes its OAuth state, logs activity, and a late callback fails; a retry after Cancel gives exactly one live connection (organization and personal); Cancel does not change an active connection or a connection that needs a new sign-in; a draft refused at the provider stays hidden and Cancel removes it; another company cannot cancel the draft. - `ui/src/pages/apps/Browse.test.tsx`: a pending draft is not listed and does not add "needs attention". - `ui/src/pages/apps/AppsConnect.test.tsx`: Google Workspace setup, Continue, then Cancel calls the cancel route for the new draft. - Red/green: the new Browse and setup tests fail without the UI change. The server test fails on master because the route and flag do not exist. - Local runs: the new server file, `openapi-routes.test.ts`, `tool-access-oauth-protocol.integration.test.ts`, `Browse.test.tsx`, `AppsConnect.test.tsx`, `activity-format.test.ts`, and `src/features/connections` pass. Server typecheck passes. `pnpm verify` exits 2 because of the pinned inputs file, so CI supplies broad coverage. - Not done: a real browser test against Google. ## Risks - Low risk. The cancel route fails toward no change: it removes nothing that shows any sign of a credential. - Cancel and a late provider callback agree under the connection row lock. If the callback commits first, Cancel changes nothing. If Cancel commits first, the callback returns 409 and saves nothing. This covers the direct, Cloud and Vercel Connect callbacks and the access finish step. - If the removal after Cancel fails, the draft stays parked and hidden, and a second Cancel finishes it. - A connection that was removed before and is now added again keeps its old consent record. If that new sign-in is cancelled, it stays as a visible draft, as it does today. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code with tool use (shell, file edits, test runs). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
509 lines
21 KiB
TypeScript
509 lines
21 KiB
TypeScript
import { notifyGitHubCredentialChange } from "../../github-connection-notifications.js";
|
|
import type { createGitHubGrantContinuity } from "../github-grant-continuity.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { notifyIssueReviewState } from "../../issue-review-state-notifications.js";
|
|
import { notifyToolConnectionHealth } from "../../tool-connection-health-notifications.js";
|
|
import { managedConnectorProfile } from "./client-settings.js";
|
|
import type { ActorInfo } from "../types.js";
|
|
import { oauthConfig, normalizeOauthScopes } from "./metadata.js";
|
|
import { connectionMethodForConnection } from "../connection-methods.js";
|
|
import { loadGitHubGrantMetadata } from "../github-access-discovery.js";
|
|
import { googleWorkspaceEffectiveScopes, googleWorkspaceSubmittedScopesIn, isGoogleWorkspaceScopeGrant } from "@paperclipai/shared";
|
|
import { emitConnectionUpdated } from "../../connector-telemetry.js";
|
|
import { and, eq, gte, ne } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { connectionGrants, companyMemberships, principalPermissionGrants, issueThreadInteractions, toolApplications, toolConnections, toolOauthStates } from "@paperclipai/db";
|
|
import type { ConnectionGrantKind, ConnectToolAppResult } from "@paperclipai/shared";
|
|
import { getConnectableAppDefinition, recommendedDefaultsForApp } from "@paperclipai/shared";
|
|
import { badRequest, forbidden, HttpError, unprocessable } from "../../../errors.js";
|
|
import { lockConnectionForSignIn } from "../connections/first-sign-in.js";
|
|
import { secretService } from "../../secrets.js";
|
|
import { isPaperclipCloudConnectorStrategy, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js";
|
|
|
|
import type { OAuthStateStore } from "./state.js";
|
|
import type { OAuthCredentialStore } from "./credential-store.js";
|
|
import type { OAuthCatalogCompletion } from "./catalog-completion.js";
|
|
import type { RefreshConnectionCatalog } from "../catalog/contracts.js";
|
|
|
|
import { toApplication } from "../applications/projection.js";
|
|
import { groupedActions } from "../catalog/action-summary.js";
|
|
|
|
type Dependencies = {
|
|
now: () => Date;
|
|
getConnectionRow(idOrUid: string, companyId?: string): Promise<typeof toolConnections.$inferSelect>;
|
|
state: OAuthStateStore;
|
|
refreshCatalog: RefreshConnectionCatalog;
|
|
finishOAuthCatalogWithRecommendedDefaults: OAuthCatalogCompletion;
|
|
store: Pick<OAuthCredentialStore, "createOrRotateOAuthSecret" | "syncCredentialBindings">;
|
|
currentCloudConnector: () => PaperclipCloudConnector | null;
|
|
syncGitHubGrantBindings: ReturnType<typeof createGitHubGrantContinuity>["syncGitHubGrantBindings"];
|
|
};
|
|
|
|
export function createCloudOAuthCallback(db: Db, dependencies: Dependencies) {
|
|
const { now, getConnectionRow, state, store, refreshCatalog, finishOAuthCatalogWithRecommendedDefaults, currentCloudConnector } = dependencies;
|
|
const { consumeOAuthState, validateOAuthState, rejectPendingOAuthInteraction } = state;
|
|
const { createOrRotateOAuthSecret, syncCredentialBindings } = store;
|
|
async function completePaperclipCloudConnectorCallback(input: {
|
|
state: string;
|
|
claimId?: string | null;
|
|
error?: string | null;
|
|
actor?: ActorInfo;
|
|
}): Promise<ConnectToolAppResult> {
|
|
// Keep the local state live until the sealed claim is in the durable vault.
|
|
// The broker binds repeat claim requests to this stable state value, so a
|
|
// transient broker, database, or secret-store failure can retry safely.
|
|
const stateRow = await validateOAuthState(input.state, input.actor);
|
|
let connection = await getConnectionRow(
|
|
stateRow.connectionId,
|
|
stateRow.companyId,
|
|
);
|
|
const preCloudCallbackLifecycle = {
|
|
status: connection.status,
|
|
enabled: connection.enabled,
|
|
};
|
|
// The connection lifecycle, not the incidental presence of its app profile,
|
|
// distinguishes setup from reauthorization. New connections and connections
|
|
// revived after removal are drafts until this callback completes. A profile
|
|
// may legitimately survive removal because an MCP gateway retains it, or be
|
|
// intentionally archived on an otherwise active connection; neither case
|
|
// should invert whether recommended defaults are rebuilt.
|
|
const shouldFinalizeManagedDefaults = connection.status === "draft";
|
|
const sourceTemplateKey =
|
|
typeof connection.config.sourceTemplateKey === "string"
|
|
? connection.config.sourceTemplateKey
|
|
: null;
|
|
const galleryEntry = sourceTemplateKey
|
|
? getConnectableAppDefinition(sourceTemplateKey)
|
|
: null;
|
|
const method = galleryEntry
|
|
? connectionMethodForConnection(galleryEntry, connection)
|
|
: null;
|
|
const providerName = galleryEntry?.name ?? "Google Workspace";
|
|
if (input.error) {
|
|
const consumedState = await consumeOAuthState(input.state, input.actor);
|
|
await rejectPendingOAuthInteraction(consumedState, input.actor);
|
|
throw new HttpError(
|
|
400,
|
|
`${providerName} authorization did not complete. Start a new ${providerName} connection to try again.`,
|
|
{
|
|
code:
|
|
input.error === "access_denied"
|
|
? "oauth_authorization_denied"
|
|
: "paperclip_cloud_connector_failed",
|
|
},
|
|
);
|
|
}
|
|
if (!input.claimId)
|
|
throw badRequest(
|
|
`${providerName} callback is missing a claim identifier`,
|
|
);
|
|
const cloudConnector = currentCloudConnector();
|
|
if (!cloudConnector) {
|
|
throw unprocessable(
|
|
`${providerName} connections through Paperclip are not available on this instance yet`,
|
|
{
|
|
code: "paperclip_cloud_connector_unavailable",
|
|
},
|
|
);
|
|
}
|
|
const subjectUserId = stateRow.subjectUserId;
|
|
const subjectAgentId = stateRow.subjectAgentId;
|
|
if (
|
|
!method ||
|
|
!isPaperclipCloudConnectorStrategy(method.oauthStrategy) ||
|
|
(!subjectUserId && !subjectAgentId)
|
|
) {
|
|
throw badRequest(
|
|
"OAuth state does not belong to a managed connector flow",
|
|
);
|
|
}
|
|
const connectorProfile = method.connectorProfile;
|
|
const profile = managedConnectorProfile(connectorProfile);
|
|
if (!profile) throw badRequest("Managed connector profile is invalid");
|
|
const connectorSubject = subjectAgentId
|
|
? `agent:${subjectAgentId}`
|
|
: subjectUserId!;
|
|
const credentials = await cloudConnector.claim({
|
|
subject: connectorSubject,
|
|
companyId: stateRow.companyId,
|
|
profile: profile.id,
|
|
claimId: input.claimId,
|
|
redemptionId: input.state,
|
|
...(profile.id === "workspace.all" && stateRow.requestedScopes ? { scopes: stateRow.requestedScopes } : {}),
|
|
});
|
|
if (profile.id === "workspace.all") {
|
|
const requested = googleWorkspaceSubmittedScopesIn(normalizeOauthScopes(stateRow.requestedScopes));
|
|
credentials.scopes = googleWorkspaceEffectiveScopes(requested, googleWorkspaceSubmittedScopesIn(credentials.scopes));
|
|
if (!isGoogleWorkspaceScopeGrant(credentials.scopes)) throw unprocessable("Google did not grant any selected service permissions", { code: "oauth_scope_grant_invalid" });
|
|
}
|
|
const refreshToken = credentials.refreshToken;
|
|
if ((profile.provider === "google" || profile.provider === "asana") && !refreshToken) {
|
|
throw unprocessable(
|
|
`${providerName} did not return offline access. Reconnect and grant the requested permissions.`,
|
|
{
|
|
code: "oauth_refresh_missing",
|
|
},
|
|
);
|
|
}
|
|
const githubMetadata =
|
|
profile.provider === "github"
|
|
? await loadGitHubGrantMetadata(
|
|
credentials.accessToken,
|
|
fetch,
|
|
credentials.appSlug,
|
|
)
|
|
: null;
|
|
const authorizingUserId =
|
|
subjectUserId ??
|
|
(stateRow.createdByActorType === "user"
|
|
? stateRow.createdByActorId
|
|
: null);
|
|
if (!authorizingUserId)
|
|
throw forbidden(
|
|
`A signed-in connection manager must authorize ${providerName}`,
|
|
);
|
|
|
|
await db.transaction(async (tx) => {
|
|
// Keep connector credential persistence serialized with membership
|
|
// suspension, downgrade, and removal. A successful claim is only durable
|
|
// while the initiating user still holds connection-management authority.
|
|
const [membership] = await tx
|
|
.select({
|
|
id: companyMemberships.id,
|
|
membershipRole: companyMemberships.membershipRole,
|
|
})
|
|
.from(companyMemberships)
|
|
.where(
|
|
and(
|
|
eq(companyMemberships.companyId, connection.companyId),
|
|
eq(companyMemberships.principalType, "user"),
|
|
eq(companyMemberships.principalId, authorizingUserId),
|
|
eq(companyMemberships.status, "active"),
|
|
ne(companyMemberships.membershipRole, "viewer"),
|
|
),
|
|
)
|
|
.limit(1)
|
|
.for("update");
|
|
if (!membership) {
|
|
throw forbidden(
|
|
`Your company membership no longer permits connection changes. Restore non-viewer access before you connect ${providerName} again.`,
|
|
);
|
|
}
|
|
if (subjectAgentId) {
|
|
const roleCanManage =
|
|
membership.membershipRole === "owner" ||
|
|
membership.membershipRole === "admin";
|
|
const [explicitManagerGrant] = roleCanManage
|
|
? []
|
|
: await tx
|
|
.select({
|
|
id: principalPermissionGrants.id,
|
|
})
|
|
.from(principalPermissionGrants)
|
|
.where(
|
|
and(
|
|
eq(principalPermissionGrants.companyId, connection.companyId),
|
|
eq(principalPermissionGrants.principalType, "user"),
|
|
eq(principalPermissionGrants.principalId, authorizingUserId),
|
|
eq(
|
|
principalPermissionGrants.permissionKey,
|
|
"tools:manage_connections",
|
|
),
|
|
),
|
|
)
|
|
.limit(1)
|
|
.for("update");
|
|
if (!roleCanManage && !explicitManagerGrant) {
|
|
throw forbidden(
|
|
"Only a connection manager can authorize a dedicated agent identity.",
|
|
);
|
|
}
|
|
}
|
|
const [consumedState] = await tx
|
|
.delete(toolOauthStates)
|
|
.where(
|
|
and(
|
|
eq(toolOauthStates.state, input.state),
|
|
gte(toolOauthStates.expiresAt, new Date()),
|
|
),
|
|
)
|
|
.returning({ state: toolOauthStates.state });
|
|
if (!consumedState)
|
|
throw badRequest(
|
|
"OAuth state was not found, expired, or has already been used",
|
|
);
|
|
const txSecrets = secretService(tx);
|
|
const txSecretContext = { dbClient: tx, secretClient: txSecrets };
|
|
const personalCredential = connection.credentialPolicy === "per_user";
|
|
const agentCredential = connection.credentialPolicy === "per_agent";
|
|
const grantKind: ConnectionGrantKind = agentCredential
|
|
? "agent"
|
|
: personalCredential
|
|
? "user"
|
|
: "organization";
|
|
const [existingCredentialGrant] = await tx
|
|
.select()
|
|
.from(connectionGrants)
|
|
.where(
|
|
and(
|
|
eq(connectionGrants.companyId, connection.companyId),
|
|
eq(connectionGrants.connectionId, connection.id),
|
|
eq(connectionGrants.kind, grantKind),
|
|
agentCredential
|
|
? eq(connectionGrants.subjectAgentId, subjectAgentId!)
|
|
: personalCredential
|
|
? eq(connectionGrants.subjectUserId, subjectUserId!)
|
|
: eq(connectionGrants.isDefault, true),
|
|
),
|
|
)
|
|
.limit(1)
|
|
.for("update");
|
|
await tx.select({ id: toolApplications.id }).from(toolApplications)
|
|
.where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, connection.companyId)))
|
|
.for("update");
|
|
await lockConnectionForSignIn(tx, connection);
|
|
const existingRefs =
|
|
existingCredentialGrant?.credentialSecretRefs ??
|
|
(personalCredential || agentCredential
|
|
? []
|
|
: connection.credentialSecretRefs);
|
|
const accessRef = await createOrRotateOAuthSecret(
|
|
{
|
|
companyId: connection.companyId,
|
|
connection,
|
|
configPath: "oauth.access_token",
|
|
label: `${providerName} access token`,
|
|
value: credentials.accessToken,
|
|
actor: input.actor,
|
|
existingRefs,
|
|
ownerUserId: personalCredential ? subjectUserId! : undefined,
|
|
},
|
|
txSecretContext,
|
|
);
|
|
const refreshRef = refreshToken
|
|
? await createOrRotateOAuthSecret(
|
|
{
|
|
companyId: connection.companyId,
|
|
connection,
|
|
configPath: "oauth.refresh_token",
|
|
label: `${providerName} refresh token`,
|
|
value: refreshToken,
|
|
actor: input.actor,
|
|
existingRefs,
|
|
ownerUserId: personalCredential ? subjectUserId! : undefined,
|
|
},
|
|
txSecretContext,
|
|
)
|
|
: null;
|
|
const credentialSecretRefs = [
|
|
...existingRefs.filter(
|
|
(ref) =>
|
|
ref.configPath !== "oauth.access_token" &&
|
|
ref.configPath !== "oauth.refresh_token",
|
|
),
|
|
accessRef,
|
|
...(refreshRef ? [refreshRef] : []),
|
|
];
|
|
await notifyGitHubCredentialChange(tx, connection);
|
|
await notifyToolConnectionHealth(tx, connection);
|
|
const grantValues = {
|
|
providerTenant: {
|
|
name: githubMetadata?.login ?? providerName,
|
|
externalId: credentials.subject,
|
|
oauth: {
|
|
strategy: "paperclip_cloud_connector",
|
|
accessTokenExpiresAt: credentials.accessTokenExpiresAt,
|
|
scopes: credentials.scopes,
|
|
requestedScopes: stateRow.requestedScopes ?? undefined,
|
|
consentedAt: now().toISOString(),
|
|
tokenType: credentials.tokenType,
|
|
...(credentials.refreshTokenExpiresAt
|
|
? { refreshTokenExpiresAt: credentials.refreshTokenExpiresAt }
|
|
: {}),
|
|
...(credentials.accessTokenExpiresAt
|
|
? { refreshedAt: now().toISOString() }
|
|
: {}),
|
|
},
|
|
...(githubMetadata ? { github: { ...githubMetadata, bindingSync: {
|
|
id: randomUUID(), removeInstallationIds: [...new Set([
|
|
...(existingCredentialGrant?.providerTenant?.github?.bindingSync?.removeInstallationIds ?? []),
|
|
...(existingCredentialGrant?.providerTenant?.github?.installationIds ?? []),
|
|
])].filter(id => !githubMetadata.installationIds.includes(id)),
|
|
} } } : {}),
|
|
},
|
|
credentialSecretRefs,
|
|
status: "active" as const,
|
|
revokedAt: null,
|
|
revokedByAgentId: null,
|
|
revokedByUserId: null,
|
|
updatedAt: now(),
|
|
};
|
|
if (existingCredentialGrant) {
|
|
await tx
|
|
.update(connectionGrants)
|
|
.set(grantValues)
|
|
.where(eq(connectionGrants.id, existingCredentialGrant.id));
|
|
} else {
|
|
await tx.insert(connectionGrants).values({
|
|
companyId: connection.companyId,
|
|
connectionId: connection.id,
|
|
kind: grantKind,
|
|
subjectUserId: personalCredential ? subjectUserId : null,
|
|
subjectAgentId: agentCredential ? subjectAgentId : null,
|
|
...grantValues,
|
|
isDefault: grantKind === "organization",
|
|
createdByUserId: authorizingUserId,
|
|
});
|
|
}
|
|
const nextConfig = {
|
|
...connection.config,
|
|
oauth: {
|
|
...oauthConfig(connection),
|
|
strategy: "paperclip_cloud_connector",
|
|
provider: galleryEntry?.slug,
|
|
connectorProfile,
|
|
connectorSubjectUserId: subjectUserId,
|
|
connectorSubjectAgentId: subjectAgentId,
|
|
resource: method.defaults?.serverUrl,
|
|
scopes: [...profile.scopes],
|
|
},
|
|
};
|
|
[connection] = await tx
|
|
.update(toolConnections)
|
|
.set({
|
|
status: shouldFinalizeManagedDefaults ? "draft" : "active",
|
|
enabled: shouldFinalizeManagedDefaults ? false : true,
|
|
authKind: "oauth",
|
|
config: nextConfig,
|
|
transportConfig: nextConfig,
|
|
credentialRefs:
|
|
personalCredential || agentCredential
|
|
? connection.credentialRefs.filter(
|
|
(ref) => ref.name !== "oauth.access_token",
|
|
)
|
|
: [
|
|
...connection.credentialRefs.filter(
|
|
(ref) => ref.name !== "oauth.access_token",
|
|
),
|
|
{
|
|
name: "oauth.access_token",
|
|
secretId: accessRef.secretId,
|
|
version: "latest" as const,
|
|
placement: "header" as const,
|
|
key: "Authorization",
|
|
prefix: "Bearer ",
|
|
},
|
|
],
|
|
credentialSecretRefs:
|
|
personalCredential || agentCredential
|
|
? connection.credentialSecretRefs.filter(
|
|
(ref) =>
|
|
ref.configPath !== "oauth.access_token" &&
|
|
ref.configPath !== "oauth.refresh_token",
|
|
)
|
|
: credentialSecretRefs,
|
|
updatedAt: now(),
|
|
})
|
|
.where(eq(toolConnections.id, connection.id))
|
|
.returning();
|
|
await tx
|
|
.update(toolApplications)
|
|
.set({
|
|
status: shouldFinalizeManagedDefaults ? "draft" : "active",
|
|
updatedAt: now(),
|
|
})
|
|
.where(eq(toolApplications.id, connection.applicationId));
|
|
await syncCredentialBindings(
|
|
connection,
|
|
personalCredential || agentCredential ? credentialSecretRefs : [],
|
|
tx,
|
|
);
|
|
const linkedInteraction = stateRow.interactionId
|
|
? await tx
|
|
.select({ kind: issueThreadInteractions.kind, issueId: issueThreadInteractions.issueId })
|
|
.from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, stateRow.interactionId))
|
|
.limit(1)
|
|
.then((rows) => rows[0] ?? null)
|
|
: null;
|
|
if (
|
|
stateRow.interactionId &&
|
|
linkedInteraction?.kind === "request_confirmation"
|
|
) {
|
|
await notifyIssueReviewState(tx, { companyId: connection.companyId, issueId: linkedInteraction.issueId });
|
|
await tx
|
|
.update(issueThreadInteractions)
|
|
.set({
|
|
status: "accepted",
|
|
result: { version: 1, outcome: "accepted" },
|
|
resolvedByUserId: authorizingUserId,
|
|
resolvedAt: now(),
|
|
updatedAt: now(),
|
|
})
|
|
.where(eq(issueThreadInteractions.id, stateRow.interactionId));
|
|
}
|
|
});
|
|
// The transaction above committed the connection's lifecycle write; a
|
|
// Paperclip Cloud connector callback is the managed variant of an OAuth
|
|
// callback completion.
|
|
emitConnectionUpdated(connection, preCloudCallbackLifecycle, "oauth_callback");
|
|
// Binding registration is saved above before Cloud I/O. The continuity
|
|
// worker drains it after activation, including after a callback/server crash.
|
|
const refresh = await refreshCatalog(connection.id, input.actor, {
|
|
enableAllByDefault: false,
|
|
quarantineManagedOAuthDraft: shouldFinalizeManagedDefaults,
|
|
skipDefaultProfileSync: true,
|
|
credentialHeaders: { Authorization: `Bearer ${credentials.accessToken}` },
|
|
});
|
|
const recommended = recommendedDefaultsForApp(galleryEntry!, method.key);
|
|
const suggestedDefaults = subjectAgentId
|
|
? { ...recommended, access: { agentIds: [subjectAgentId] } as const }
|
|
: recommended;
|
|
const finished = shouldFinalizeManagedDefaults
|
|
? await finishOAuthCatalogWithRecommendedDefaults({
|
|
interactionId: stateRow.interactionId,
|
|
connection,
|
|
catalog: refresh.catalog,
|
|
suggestedDefaults,
|
|
activateQuarantined: true,
|
|
actor: input.actor,
|
|
})
|
|
: null;
|
|
if (githubMetadata) {
|
|
const [grant] = await db.select().from(connectionGrants).where(and(
|
|
eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id),
|
|
subjectAgentId ? and(eq(connectionGrants.kind, "agent"), eq(connectionGrants.subjectAgentId, subjectAgentId))
|
|
: and(eq(connectionGrants.kind, "user"), eq(connectionGrants.subjectUserId, subjectUserId!)),
|
|
)).limit(1);
|
|
if (!grant) throw new Error("GitHub grant was not persisted");
|
|
await dependencies.syncGitHubGrantBindings(await getConnectionRow(connection.id, connection.companyId), grant, input.actor, credentials.accessToken);
|
|
}
|
|
const activatedCatalogEntryIds = new Set(
|
|
shouldFinalizeManagedDefaults
|
|
? refresh.catalog
|
|
.filter((entry) => entry.status === "quarantined")
|
|
.map((entry) => entry.id)
|
|
: [],
|
|
);
|
|
const catalog = refresh.catalog.map((entry) =>
|
|
activatedCatalogEntryIds.has(entry.id)
|
|
? { ...entry, status: "active" as const }
|
|
: entry,
|
|
);
|
|
const [application] = await db
|
|
.select()
|
|
.from(toolApplications)
|
|
.where(eq(toolApplications.id, connection.applicationId));
|
|
return {
|
|
connectionId: connection.id,
|
|
application: toApplication(application),
|
|
connection: finished?.connection ?? refresh.connection,
|
|
catalog,
|
|
actions: groupedActions(catalog),
|
|
suggestedDefaults,
|
|
auth: null,
|
|
};
|
|
}
|
|
return completePaperclipCloudConnectorCallback;
|
|
}
|