Skip to content

The open-source app everyone uses to manage agents at work

refactor(tools): isolate connection token broker (#17157)

Dottaa42f2132446d
diff --git a/doc/plans/2026-10-21-tool-access-boundaries.md b/doc/plans/2026-10-21-tool-access-boundaries.md
index a1d6b2cae9..6362f9453b 100644
--- a/doc/plans/2026-10-21-tool-access-boundaries.md
+++ b/doc/plans/2026-10-21-tool-access-boundaries.md
@@ -155,3 +155,23 @@ match normalized syntax across the move. The baseline and post-move runs pass
cases. Server typechecking and the module-boundary gate pass. Existing tests
exercise both full catalog DTOs and lightweight assignments; no new behavior or
fixture-only test was added.
+
+### Connection token broker extraction
+
+The broker owns run admission, explicit mint grants, rate limits, selected grant
+checks, issuance and audit. Configuration parsing, endpoint policy, exchange,
+and issuance storage are separate modules. The service receives the existing
+secret service, policy service, audit function, clock and two connection/grant
+operations. The issuance transaction still acquires the responsible membership
+lock before resolving the parent credential and performing the exchange. It
+stores only the token hash. Private-host policy still reads live environment
+values on each request. No resource, cache or timer is created by the factories.
+
+The entry point is 16,100 lines / 644,119 bytes. The six broker modules total
+1,721 lines; the largest is 755. All 294 pre-existing function/method bodies
+match normalized syntax. Two new public-route tests passed before production
+changes and after extraction. They use real HTTP and disposable PostgreSQL for
+Pages and RFC 8693 exchanges, plus a failing upstream request, and assert that
+issuance/audit rows contain no token material. The complete public service and
+HTTP rebinding run passes 495 cases. Server typechecking and module boundaries
+pass. These fixtures do not claim live third-party qualification.
diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts
index 715e6ed2b1..be3e12337a 100644
--- a/server/src/__tests__/tool-access-service.test.ts
+++ b/server/src/__tests__/tool-access-service.test.ts
@@ -1,5 +1,6 @@
import * as fs from "node:fs/promises";
import { createHash, generateKeyPairSync, randomUUID } from "node:crypto";
+import { createServer } from "node:http";
import express from "express";
import request from "supertest";
import {
@@ -978,6 +979,70 @@ describeEmbeddedPostgres("tool access service", () => {
return false;
}
+ it.each(["pages", "rfc8693"] as const)("mints %s tokens over real HTTP and records upstream failures without token material", async (protocol) => {
+ vi.stubEnv("PAPERCLIP_TOKEN_BROKER_ALLOWED_HOSTS", "127.0.0.1");
+ const received: Array<{ authorization: string | undefined; body: string }> = [];
+ let failExchange = false;
+ const server = createServer(async (incoming, response) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of incoming) chunks.push(Buffer.from(chunk));
+ received.push({ authorization: incoming.headers.authorization, body: Buffer.concat(chunks).toString() });
+ response.writeHead(failExchange ? 503 : 200, { "content-type": "application/json" });
+ response.end(JSON.stringify(failExchange
+ ? { error: "temporarily_unavailable" }
+ : { access_token: "real-http-child-token", expires_in: 600, scope: "pages:publish:ns/dotta" }));
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const company = await createCompany(db);
+ const agent = await createAgent(db, company.id);
+ const { run } = await createIssueAndRun(db, company.id, agent.id);
+ const port = (server.address() as { port: number }).port;
+ const { connection } = await createBrokerConnection(db, company.id, {
+ tokenUrl: `http://127.0.0.1:${port}/exchange`, protocol,
+ });
+ await allowConnectionForAgent(db, company.id, agent.id, connection.id);
+ const app = createRouteApp(db, agentJwtActor(company.id, agent.id, run.id));
+ const mint = () => request(app)
+ .post(`/api/agents/me/connections/${connection.id}/token`)
+ .send({ scope: "pages:publish:ns/dotta" });
+ const result = await mint();
+ expect(result.status).toBe(200);
+ expect(result.body).toMatchObject({ status: "minted", token: "real-http-child-token", scope: ["pages:publish:ns/dotta"] });
+ expect(received).toHaveLength(1);
+ if (protocol === "pages") {
+ expect(received[0].authorization).toBe("Bearer parent-deploy-token");
+ expect(JSON.parse(received[0].body)).toMatchObject({ namespace: "dotta", actor: { id: agent.id, runId: run.id, onBehalfOf: "user:user-for-run" } });
+ } else {
+ const form = new URLSearchParams(received[0].body);
+ expect(form.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:token-exchange");
+ expect(form.get("subject_token")).toBe("parent-deploy-token");
+ expect(form.get("scope")).toBe("pages:publish:ns/dotta");
+ }
+ failExchange = true;
+ const failed = await mint();
+ expect(failed.status).toBe(502);
+ expect(failed.body).toMatchObject({ code: "upstream_error" });
+ expect(received).toHaveLength(2);
+ const issuances = await db.select().from(connectionTokenIssuances)
+ .where(eq(connectionTokenIssuances.connectionId, connection.id));
+ expect(issuances).toHaveLength(2);
+ expect(issuances.find(row => row.outcome === "success")).toMatchObject({
+ tokenHash: createHash("sha256").update("real-http-child-token").digest("hex"),
+ companyId: company.id, agentId: agent.id, runId: run.id,
+ });
+ expect(issuances.find(row => row.outcome === "upstream_error")).toMatchObject({ tokenHash: null, errorCode: "upstream_error" });
+ const audits = await db.select().from(toolAccessAuditEvents)
+ .where(eq(toolAccessAuditEvents.connectionId, connection.id));
+ const persisted = JSON.stringify({ issuances, audits });
+ expect(persisted).not.toContain("parent-deploy-token");
+ expect(persisted).not.toContain("real-http-child-token");
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
+ }
+ });
+
it("mints generic exchange connection tokens through the agent route and stores only hashes", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts
index 8057451407..54e4185fd2 100644
--- a/server/src/services/tool-access.ts
+++ b/server/src/services/tool-access.ts
@@ -1,3 +1,6 @@
+import { createToolAccessAudit } from "./tool-access/audit.js";
+import { createConnectionTokenBroker } from "./tool-access/token-broker/service.js";
+import { assertConfiguredTokenBrokerEndpointsAllowed } from "./tool-access/token-broker/endpoint-policy.js";
import { createToolProfileService } from "./tool-access/profiles/service.js";
import { createToolProfileResolver } from "./tool-access/profiles/resolution.js";
import { toProfile, toProfileEntry, toProfileBinding, pendingNewToolsForProfile, profileCatalogColumns } from "./tool-access/profiles/projection.js";
@@ -65,7 +68,7 @@ import {
emitConnectionUpdated,
} from "./connector-telemetry.js";
import { canBrowseProjectRepositoryGrant, mergeProjectRepository } from "./project-repositories.js";
-import { captureRunIdentity } from "./run-identity.js";
+
import { measureRunPhase } from "./execution-preparation-timing.js";
import { measureRunTransaction } from "./execution-transaction-timing.js";
import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -89,7 +92,7 @@ import {
} from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agents, connectionGrantMembers, connectionGrantDelegations, connectionGrants, connectionTokenIssuances, authUsers, companyMemberships, companySecretBindings, companySecrets, principalPermissionGrants, userSecretDefinitions, userSecretDeclarations, heartbeatRuns, issues, issueThreadInteractions, plugins, toolAccessAuditEvents, toolApplications, toolActionRequests, toolCatalogEntries, toolConnectionInstalls, toolConnectionAppSnapshots, toolConnectionAppSyncs, toolConnections, toolOauthStates, toolStdioCommandTemplates, toolCallEvents, toolInvocations, toolPolicies, toolGatewaySessions, toolMcpGateways, toolMcpGatewayTokens, toolProfileBindings, toolProfileEntries, toolProfiles, toolRuntimeMetricCounters, toolRuntimeSlots } from "@paperclipai/db";
-import type { AppDefinition, ConnectionGrantKind, ConnectionTokenIssuanceOutcome, ConnectionTokenIssuancePath, ConnectionTokenRequest, ConnectionTokenResponse, CreateToolApplication, CreateToolConnection, ConnectToolApp, ConnectToolAppResult, CreateToolStdioCommandTemplate, FinishToolApp, FinishToolAppResult, FinalizeOAuthAccess, CreateToolProfileBindingForProfile, CreateToolProfileEntryForProfile, DeploymentExposure, DeploymentMode, ImportMcpJson, McpConnectionCredentialRef, McpJsonImportPreview, ToolApplication, ToolCatalogEntry, ToolCatalogRefreshResult, ToolConnection, ToolConnectionInstall, ToolConnectionInstallSnapshot, ToolConnectionRemovalResult, ToolConnectionRemovalSummary, ToolConnectionHealthCheckResult, ToolConnectionHealthStatus, ToolConnectionAuthKind, ToolConnectionCredentialPolicy, ToolConnectionCredentialSource, ToolConnectionTransport, ToolCredentialSecretRef, ToolOAuthStartResult, ToolAppsAttentionResponse, ToolAppMetadataPreflightResult, ToolActionRequest, ToolActionRequestListItem, ToolActionRequestStatus, ToolConnectionActivityResponse, ToolAppConnectionActionSummary, ToolExampleInstallResult, ToolExampleSmokeCheck, ToolExampleSmokeResult, ToolExampleSummary, ToolCallEvent, ToolInvocation, ToolProfileBinding, ToolProfileEntry, ToolPolicyDecision, ToolPolicy, ToolRiskLevel, ToolRuntimeAlertRecommendation, ToolRuntimeHealthSummary, ToolRunDecision, ToolRunDecisionLookup, ToolRuntimeSlot, ToolStdioCommandTemplate, UpdateToolApplication, UpdateToolConnection, PutToolConnectionInstalls, VercelConnectCredentialReference, VercelConnectGrantReference } from "@paperclipai/shared";
+import type { AppDefinition, ConnectionGrantKind, CreateToolApplication, CreateToolConnection, ConnectToolApp, ConnectToolAppResult, CreateToolStdioCommandTemplate, FinishToolApp, FinishToolAppResult, FinalizeOAuthAccess, CreateToolProfileBindingForProfile, CreateToolProfileEntryForProfile, DeploymentExposure, DeploymentMode, ImportMcpJson, McpConnectionCredentialRef, McpJsonImportPreview, ToolApplication, ToolCatalogEntry, ToolCatalogRefreshResult, ToolConnection, ToolConnectionInstall, ToolConnectionInstallSnapshot, ToolConnectionRemovalResult, ToolConnectionRemovalSummary, ToolConnectionHealthCheckResult, ToolConnectionHealthStatus, ToolConnectionAuthKind, ToolConnectionCredentialPolicy, ToolConnectionCredentialSource, ToolConnectionTransport, ToolCredentialSecretRef, ToolOAuthStartResult, ToolAppsAttentionResponse, ToolAppMetadataPreflightResult, ToolActionRequest, ToolActionRequestListItem, ToolActionRequestStatus, ToolConnectionActivityResponse, ToolAppConnectionActionSummary, ToolExampleInstallResult, ToolExampleSmokeCheck, ToolExampleSmokeResult, ToolExampleSummary, ToolCallEvent, ToolInvocation, ToolProfileBinding, ToolProfileEntry, ToolPolicyDecision, ToolPolicy, ToolRiskLevel, ToolRuntimeAlertRecommendation, ToolRuntimeHealthSummary, ToolRunDecision, ToolRunDecisionLookup, ToolRuntimeSlot, ToolStdioCommandTemplate, UpdateToolApplication, UpdateToolConnection, PutToolConnectionInstalls, VercelConnectCredentialReference, VercelConnectGrantReference } from "@paperclipai/shared";
import {
CLASS3_STATIC_LEASE_ALLOWLIST,
GITHUB_CONNECTOR_PROFILES,
@@ -149,13 +152,10 @@ import {
readSignedToolArgumentsPayload,
TOOL_ACTION_REQUEST_SIGNING_GRACE_MS,
} from "./tool-content-guards.js";
-import { narrowestScopeBindings, profileIdsInBindingOrder } from "./tool-profile-binding-precedence.js";
+
import { googleChatToolDescription } from "./google-chat-tool-policy.js";
import { gmailArchiveToolDescription } from "./gmail-archive-tool-policy.js";
-import {
- recordToolRuntimeAuditWriteFailure,
- TOOL_RUNTIME_AUDIT_WRITE_FAILURE_METRIC,
-} from "./tool-runtime-metrics.js";
+import { TOOL_RUNTIME_AUDIT_WRITE_FAILURE_METRIC } from "./tool-runtime-metrics.js";
import {
createToolRuntimeSupervisor,
ToolRuntimeSupervisorError,
@@ -181,8 +181,6 @@ import {
VercelConnectClientError,
type VercelConnectClient,
} from "./vercel-connect.js";
-
-const ACTIVE_BROKER_RUN_STATUSES = new Set(["running"]);
const REMOTE_HTTP_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
const MAX_REMOTE_HTTP_REDIRECTS = 5;
const OAUTH_REFRESH_LEASE_MS = 120_000;
@@ -492,7 +490,6 @@ const GOOGLE_SHEETS_GALLERY_KEY = "google-sheets";
const GOOGLE_SHEETS_TEMPLATE_ID = "paperclip.google-sheets";
const GOOGLE_SHEETS_ALLOWED_SPREADSHEET_IDS_ENV =
"GOOGLE_SHEETS_ALLOWED_SPREADSHEET_IDS";
-const CONNECTION_TOKEN_MINT_TOOL_NAME = "connection_token.mint";
type ToolExampleDefinition = {
id: string;
@@ -1777,6 +1774,8 @@ export function toolAccessService(
}
const policySvc = toolAccessPolicyService(db);
const now = options.now ?? (() => new Date());
+ const audit = createToolAccessAudit(db);
+ const { mintConnectionTokenForAgent, loadBrokerRunContext } = createConnectionTokenBroker(db, { now, secrets, policySvc, audit, getConnectionRow, ensureDefaultOrganizationGrant });
const profileService = createToolProfileService(db, now);
const profileDetails = profileService.getProfile;
const profileResolver = createToolProfileResolver(db, { assertOptionalAgent, resolveInstalledConnectionsForAgent, toCatalogEntry });
@@ -2068,77 +2067,6 @@ export function toolAccessService(
return assertRemoteHttpUrlAllowed(remoteEndpoint(config));
}
- function normalizeTokenBrokerAllowedHost(value: string): string | null {
- const trimmed = value.trim();
- if (!trimmed) return null;
- try {
- const parsed = new URL(
- trimmed.includes("://") ? trimmed : `http://${trimmed}`,
- );
- return (
- parsed.hostname
- .replace(/^\[|\]$/g, "")
- .replace(/\.$/, "")
- .toLowerCase() || null
- );
- } catch {
- // Invalid allowlist entries grant no access. The configured broker URL is
- // still evaluated under the public-only policy below.
- return null;
- }
- }
-
- function tokenBrokerAllowedPrivateHosts(): Set<string> {
- const configured = (process.env.PAPERCLIP_TOKEN_BROKER_ALLOWED_HOSTS ?? "")
- .split(/[,\s]+/)
- .map(normalizeTokenBrokerAllowedHost)
- .filter((host): host is string => host !== null);
- const pagesApiHost = normalizeTokenBrokerAllowedHost(
- process.env.PAPERCLIP_PAGES_API_URL ?? "",
- );
- if (pagesApiHost) configured.push(pagesApiHost);
- return new Set(configured);
- }
-
- function tokenBrokerAllowsPrivateNetwork(endpoint: URL): boolean {
- const hostname = endpoint.hostname
- .replace(/^\[|\]$/g, "")
- .replace(/\.$/, "")
- .toLowerCase();
- return tokenBrokerAllowedPrivateHosts().has(hostname);
- }
-
- function tokenBrokerHttpFetchOptions(
- endpoint: URL,
- ): GuardedRemoteHttpFetchOptions {
- return {
- allowPrivateNetwork: tokenBrokerAllowsPrivateNetwork(endpoint),
- error: (message, code) => badRequest(message, { code }),
- };
- }
-
- async function assertTokenBrokerHttpUrlAllowed(
- value: string,
- ): Promise<string> {
- const endpoint = parseRemoteHttpEndpoint(value, (message, code) =>
- badRequest(message, { code }),
- );
- await assertPublicRemoteHttpEndpoint(
- endpoint,
- { allowPrivateNetwork: tokenBrokerAllowsPrivateNetwork(endpoint) },
- (message, code) => badRequest(message, { code }),
- );
- return endpoint.toString();
- }
-
- async function assertConfiguredTokenBrokerEndpointsAllowed(
- config: Record<string, unknown>,
- ): Promise<void> {
- for (const url of configuredTokenBrokerExchangeUrls(config)) {
- await assertTokenBrokerHttpUrlAllowed(url);
- }
- }
-
async function assertRemoteConnectionEndpointsAllowed(
config: Record<string, unknown>,
): Promise<string> {
@@ -2581,1464 +2509,593 @@ export function toolAccessService(
return syncAggregatorApps(connectionId, true, actor);
}
- async function audit(input: {
- companyId: string;
- connectionId?: string | null;
- catalogEntryId?: string | null;
- action: string;
- outcome: "success" | "failure";
- reasonCode?: string | null;
- details?: Record<string, unknown>;
- actor?: ActorInfo;
- }) {
- try {
- await db.insert(toolAccessAuditEvents).values({
- companyId: input.companyId,
- connectionId: input.connectionId ?? null,
- catalogEntryId: input.catalogEntryId ?? null,
- actorType: input.actor?.actorType ?? "system",
- actorId: input.actor?.actorId ?? null,
- action: input.action,
- outcome: input.outcome,
- reasonCode: input.reasonCode ?? null,
- details: input.details ?? {},
- });
- } catch (error) {
- await recordToolRuntimeAuditWriteFailure(db, input.companyId);
- throw error;
- }
- }
-
- function readConfigString(
- record: Record<string, unknown>,
- key: string,
- ): string | null {
- const value = record[key];
- return typeof value === "string" && value.trim().length > 0
- ? value.trim()
- : null;
- }
-
- function readConfigStringArray(value: unknown): string[] {
- if (Array.isArray(value)) {
- return value
- .filter((item): item is string => typeof item === "string")
- .map((item) => item.trim())
- .filter(Boolean);
- }
- if (typeof value === "string")
- return value
- .split(/\s+/)
- .map((item) => item.trim())
- .filter(Boolean);
- return [];
- }
-
- function normalizeConnectionTokenScopes(
- scope: ConnectionTokenRequest["scope"],
- ): string[] {
- if (Array.isArray(scope))
- return [...new Set(scope.map((item) => item.trim()).filter(Boolean))];
- if (typeof scope === "string")
- return [
- ...new Set(
- scope
- .split(/\s+/)
- .map((item) => item.trim())
- .filter(Boolean),
- ),
- ];
- return [];
- }
-
- function tokenBrokerConfigFromConnectionConfig(
- config: Record<string, unknown>,
- ): Record<string, unknown> {
- const broker = asRecord(config.tokenBroker);
- if (Object.keys(broker).length > 0) return broker;
- return asRecord(config.broker);
- }
-
- function tokenBrokerConfig(
- connection: typeof toolConnections.$inferSelect,
- ): Record<string, unknown> {
- return tokenBrokerConfigFromConnectionConfig(asRecord(connection.config));
+ function runtimeAlert(
+ input: ToolRuntimeAlertRecommendation,
+ ): ToolRuntimeAlertRecommendation {
+ return input;
}
- function configuredTokenBrokerExchangeUrls(
- config: Record<string, unknown>,
- ): string[] {
- const broker = tokenBrokerConfigFromConnectionConfig(config);
+ function buildRuntimeAlerts(input: {
+ stuckStartingSlots: number;
+ stuckRunningSlots: number;
+ timeoutRate: number;
+ timeoutCount: number;
+ failureRate: number;
+ failureCount: number;
+ capacityDeferrals: number;
+ restartAttempts: number;
+ restartSuppressions: number;
+ degradedConnections: number;
+ disabledConnections: number;
+ missingSecretFailures: number;
+ auditWriteFailures: number;
+ }): ToolRuntimeAlertRecommendation[] {
+ const runbookSection = "doc/MCP-RUNTIME-OPERATIONS.md";
+ const timeoutSeverity =
+ input.timeoutCount >= 10 || input.timeoutRate >= 25
+ ? "critical"
+ : input.timeoutCount >= 3 && input.timeoutRate >= 10
+ ? "warning"
+ : "warning";
+ const failureSeverity =
+ input.failureCount >= 10 || input.failureRate >= 25
+ ? "critical"
+ : input.failureCount >= 5 && input.failureRate >= 10
+ ? "warning"
+ : "warning";
+ const restartSeverity =
+ input.restartSuppressions > 0 ? "critical" : "warning";
return [
- ...new Set(
- [
- readConfigString(broker, "tokenUrl"),
- readConfigString(broker, "exchangeTokenUrl"),
- readConfigString(config, "tokenExchangeUrl"),
- readConfigString(config, "pagesTokenExchangeUrl"),
- ].filter((url): url is string => url !== null),
- ),
+ runtimeAlert({
+ name: "mcp_runtime_stuck_starting_slot",
+ severity: "critical",
+ status: input.stuckStartingSlots > 0 ? "firing" : "ok",
+ threshold: "Any starting slot older than 5 minutes.",
+ observed: `${input.stuckStartingSlots} stuck starting slot(s).`,
+ description:
+ "A local stdio runtime slot is stuck before it reaches running state.",
+ firstResponderAction:
+ "Inspect the slot health/logs, stop the slot, restart it once, then disable the connection if the slot sticks again.",
+ runbookSection,
+ }),
+ runtimeAlert({
+ name: "mcp_runtime_stuck_running_slot",
+ severity: "critical",
+ status: input.stuckRunningSlots > 0 ? "firing" : "ok",
+ threshold: "Any running slot with no progress for 5 minutes.",
+ observed: `${input.stuckRunningSlots} stuck running slot(s).`,
+ description:
+ "A runtime slot is running but has not recorded progress inside the supervisor stuck-slot window.",
+ firstResponderAction:
+ "Inspect recent audit events and active tool calls; restart the slot only after confirming no healthy call is still in progress.",
+ runbookSection,
+ }),
+ runtimeAlert({
+ name: "mcp_runtime_high_timeout_rate",
+ severity: timeoutSeverity,
+ status:
+ input.timeoutCount >= 3 && input.timeoutRate >= 10 ? "firing" : "ok",
+ threshold:
+ "Warning at >=3 timeouts and >=10% timeout rate in 1 hour; critical at >=10 timeouts or >=25%.",
+ observed: `${input.timeoutCount} timeout(s), ${input.timeoutRate}% timeout rate.`,
+ description:
+ "Tool gateway calls are timing out or being runtime-deferred at an elevated rate.",
+ firstResponderAction:
+ "Check upstream MCP health, Paperclip runtime capacity, and recent gateway audit failures before retrying workloads.",
+ runbookSection,
+ }),
+ runtimeAlert({
+ name: "mcp_runtime_high_error_rate",
+ severity: failureSeverity,
+ status:
+ input.failureCount >= 5 && input.failureRate >= 10 ? "firing" : "ok",
+ threshold:
+ "Warning at >=5 failures and >=10% failure rate in 1 hour; critical at >=10 failures or >=25%.",
+ observed: `${input.failureCount} failure(s), ${input.failureRate}% failure rate.`,
+ description:
+ "Tool gateway calls are failing after policy authorization.",
+ firstResponderAction:
+ "Group audit failures by reasonCode, then fix credentials/config or disable the affected connection.",
+ runbookSection,
+ }),
+ runtimeAlert({
+ name: "mcp_runtime_capacity_deferrals_repeated",
+ severity: input.capacityDeferrals >= 10 ? "critical" : "warning",
+ status: input.capacityDeferrals >= 3 ? "firing" : "ok",
+ threshold:
+ "Warning at >=3 capacity deferrals in 1 hour; critical at >=10.",
+ observed: `${input.capacityDeferrals} capacity deferral(s) in 1 hour.`,
+ description:
+ "The runtime supervisor is refusing local stdio work because company or host slot capacity is exhausted.",
+ firstResponderAction:
+ "Stop idle/stale slots, lower noisy workloads, or raise slot caps only after confirming host capacity.",
+ runbookSection,
+ }),
+ runtimeAlert({
+ name: "mcp_runtime_restart_storm",
+ severity: restartSeverity,
+ status:
+ input.restartSuppressions > 0 || input.restartAttempts >= 3
+ ? "firing"
+ : "ok",
+ threshold:
+ "Warning at >=3 restarts in 1 hour; critical on any restart suppression.",
+ observed: `${input.restartAttempts} restart attempt(s), ${input.restartSuppressions} suppression(s).`,
+ description:
+ "Runtime slots are restarting repeatedly or have hit restart-storm suppression.",
+ firstResponderAction:
+ "Stop the affected slot, inspect stderr/audit reason codes, and keep the connection disabled until the template/upstream is fixed.",
+ runbookSection,
+ }),
+ runtimeAlert({
+ name: "mcp_runtime_connection_health_degraded",
+ severity: input.degradedConnections > 0 ? "critical" : "warning",
+ status:
+ input.degradedConnections > 0 || input.disabledConnections > 0
+ ? "firing"
+ : "ok",
+ threshold:
+ "Any active enabled connection with degraded/failed/missing-secret health, or any disabled enabled-path connection.",
+ observed: `${input.degradedConnections} degraded connection(s), ${input.disabledConnections} disabled connection(s).`,
+ description:
+ "A configured MCP connection is not healthy or has been disabled.",
+ firstResponderAction:
+ "Run a connection health check, refresh catalog after recovery, or keep the connection disabled and route agents to alternatives.",
+ runbookSection,
+ }),
+ runtimeAlert({
+ name: "mcp_runtime_missing_secret_failures",
+ severity: input.missingSecretFailures >= 3 ? "critical" : "warning",
+ status: input.missingSecretFailures > 0 ? "firing" : "ok",
+ threshold:
+ "Warning on any missing-secret failure; critical at >=3 in 1 hour.",
+ observed: `${input.missingSecretFailures} missing-secret failure(s) in 1 hour.`,
+ description:
+ "A connection or tool call needed a bound secret that could not be resolved.",
+ firstResponderAction:
+ "Check secret bindings and provider health without printing secret values; rotate or rebind missing secrets.",
+ runbookSection,
+ }),
+ runtimeAlert({
+ name: "mcp_runtime_audit_write_failures",
+ severity: "critical",
+ status: input.auditWriteFailures > 0 ? "firing" : "ok",
+ threshold: "Any audit write failure.",
+ observed: `${input.auditWriteFailures} audit write failure(s) in 1 hour.`,
+ description:
+ "Tool gateway audit writes failed, reducing incident traceability.",
+ firstResponderAction:
+ "Treat as a control-plane incident: check database writes, activity log writes, and retry only after audit durability is restored.",
+ runbookSection,
+ }),
];
}
- function connectionTokenBrokerEnabled(
- connection: typeof toolConnections.$inferSelect,
- ): boolean {
- const config = asRecord(connection.config);
- const tokenBroker = asRecord(config.tokenBroker);
- if (Object.keys(tokenBroker).length > 0)
- return tokenBroker.enabled === true;
- const broker = asRecord(config.broker);
- if (Object.keys(broker).length > 0) return broker.enabled === true;
- return false;
- }
-
- function isPagesTokenConnection(
- connection: typeof toolConnections.$inferSelect,
- application?: typeof toolApplications.$inferSelect | null,
- ) {
- const config = asRecord(connection.config);
- const broker = tokenBrokerConfig(connection);
- const applicationKey = application?.applicationKey ?? "";
- return Boolean(
- applicationKey === "paperclip-pages" ||
- applicationKey === "paperclip.pages" ||
- applicationKey === "pages.paperclip" ||
- readConfigString(config, "connectionType") === "pages" ||
- readConfigString(config, "service") === "pages" ||
- readConfigString(broker, "connectionType") === "pages" ||
- readConfigString(broker, "service") === "pages" ||
- asRecord(config.pages).enabled === true,
- );
- }
-
- async function getConnectionApplication(
- connection: typeof toolConnections.$inferSelect,
- ) {
- const [application] = await db
- .select()
- .from(toolApplications)
- .where(eq(toolApplications.id, connection.applicationId));
- return application ?? null;
- }
-
- function inferConnectionTokenPath(
- connection: typeof toolConnections.$inferSelect,
- application?: typeof toolApplications.$inferSelect | null,
- ): ConnectionTokenIssuancePath {
- const broker = tokenBrokerConfig(connection);
- const configuredPath =
- readConfigString(broker, "path") ??
- readConfigString(asRecord(connection.config), "tokenPath");
- if (
- configuredPath === "exchange" ||
- configuredPath === "oauth_access" ||
- configuredPath === "static"
- )
- return configuredPath;
- if (isPagesTokenConnection(connection, application)) return "exchange";
- if (
- readConfigString(broker, "tokenUrl") ||
- readConfigString(asRecord(connection.config), "tokenExchangeUrl")
- )
- return "exchange";
- return "static";
- }
-
- function parentScopesForConnection(
- connection: typeof toolConnections.$inferSelect,
- ): string[] {
- const config = asRecord(connection.config);
- const broker = tokenBrokerConfig(connection);
- const configured = [
- ...readConfigStringArray(broker.parentScopes),
- ...readConfigStringArray(broker.scopes),
- ...readConfigStringArray(config.parentScopes),
- ...readConfigStringArray(asRecord(config.oauth).scopes),
- ...readConfigStringArray(asRecord(config.oauth).scope),
- ];
- const namespaceAllowlist = readConfigStringArray(
- config.namespaceAllowlist,
- ).map((namespace) => `pages:publish:ns/${namespace}`);
- return [...new Set([...configured, ...namespaceAllowlist])];
- }
-
- function defaultScopesForConnection(
- connection: typeof toolConnections.$inferSelect,
- ): string[] {
- const broker = tokenBrokerConfig(connection);
- return [
- ...new Set([
- ...readConfigStringArray(broker.defaultScopes),
- ...readConfigStringArray(asRecord(connection.config).defaultScopes),
- ]),
- ];
- }
-
- function assertScopeSubset(input: {
- requestedScope: string[];
- parentScopes: string[];
- }) {
- if (input.requestedScope.length === 0) return;
- const parent = new Set(input.parentScopes);
- if (
- parent.size === 0 ||
- input.requestedScope.some((scope) => !parent.has(scope))
- ) {
- throw forbidden(
- "Requested token scope exceeds the connection parent scope",
- );
- }
- }
-
- function requestedTtlSeconds(
- body: ConnectionTokenRequest,
- connection: typeof toolConnections.$inferSelect,
- ): number {
- const broker = tokenBrokerConfig(connection);
- const configured = Number(
- broker.defaultTtlSeconds ?? broker.ttlSeconds ?? 900,
- );
- const requested = Number(body.requestedTtlSeconds ?? configured);
- const finite =
- Number.isFinite(requested) && requested > 0 ? Math.trunc(requested) : 900;
- return Math.max(1, Math.min(900, finite));
- }
-
- function sha256Hex(value: string): string {
- return createHash("sha256").update(value).digest("hex");
- }
-
- function bearerTokenHash(token: string): string {
- return sha256Hex(token);
- }
-
- function runSnapshotString(
- snapshot: Record<string, unknown>,
- ...keys: string[]
- ): string | null {
- for (const key of keys) {
- const value = snapshot[key];
- if (typeof value === "string" && value.trim().length > 0) return value;
- }
- return null;
- }
-
- async function loadBrokerRunContext(input: {
- companyId: string;
- agentId: string;
- runId: string;
- }) {
- const [initialRun] = await db
- .select()
- .from(heartbeatRuns)
- .where(eq(heartbeatRuns.id, input.runId));
- const run = initialRun?.activeIdentityContextId
- ? (await captureRunIdentity(db, input)).run
- : initialRun;
- if (
- !run ||
- run.companyId !== input.companyId ||
- run.agentId !== input.agentId
- ) {
- throw forbidden(
- "Agent run context does not match the authenticated actor",
- );
- }
- if (!ACTIVE_BROKER_RUN_STATUSES.has(run.status)) {
- throw forbidden("Agent run is not active");
- }
- const snapshot = asRecord(run.contextSnapshot);
- const paperclipIssue = asRecord(snapshot.paperclipIssue);
- const responsibleUserId = run.activeIdentityContextId
- ? run.responsibleUserId
- : (runSnapshotString(
- snapshot,
- "responsibleUserId",
- "responsible_user_id",
- ) ??
- runSnapshotString(
- paperclipIssue,
- "responsibleUserId",
- "responsible_user_id",
- ) ??
- run.responsibleUserId);
- if (!responsibleUserId) {
- throw forbidden(
- "Agent run has no responsible user for delegated connection access",
- );
- }
- const responsibleMembership = await db
- .select({
- status: companyMemberships.status,
- membershipRole: companyMemberships.membershipRole,
- })
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, run.companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, responsibleUserId),
- ),
- )
- .then((rows) => rows[0] ?? null);
- if (
- !responsibleMembership ||
- responsibleMembership.status !== "active" ||
- !responsibleMembership.membershipRole ||
- responsibleMembership.membershipRole === "viewer"
- ) {
- throw forbidden(
- "Responsible user is no longer authorized for company write access",
- );
- }
- return {
- run,
- issueId:
- runSnapshotString(snapshot, "issueId") ??
- runSnapshotString(paperclipIssue, "id"),
- projectId:
- runSnapshotString(snapshot, "projectId") ??
- runSnapshotString(paperclipIssue, "projectId"),
- routineId: runSnapshotString(snapshot, "routineId"),
- responsibleUserId,
- };
- }
-
- async function lockAuthorizedBrokerResponsibleMembership(
- input: {
- companyId: string;
- responsibleUserId: string;
- },
- tx: DbTransaction,
- ) {
- const membership = await tx
- .select({
- id: companyMemberships.id,
- status: companyMemberships.status,
- membershipRole: companyMemberships.membershipRole,
- })
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, input.companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, input.responsibleUserId),
- ),
- )
- .limit(1)
- .for("update")
- .then((rows) => rows[0] ?? null);
- if (
- !membership ||
- membership.status !== "active" ||
- !membership.membershipRole ||
- membership.membershipRole === "viewer"
- ) {
- throw new HttpError(
- 403,
- "Responsible user is no longer authorized for company write access",
- {
- code: "responsible_user_unauthorized",
- },
- );
- }
- return membership;
- }
-
- async function recordConnectionTokenIssuance(
- input: {
- companyId: string;
- applicationId: string | null;
- connectionId: string;
- agentId: string;
- runId: string | null;
- issueId: string | null;
- projectId: string | null;
- responsibleUserId: string | null;
- path: ConnectionTokenIssuancePath;
- requestedScope: string[];
- issuedScope: string[];
- ttlSeconds: number | null;
- expiresAt: Date | null;
- tokenHash: string | null;
- outcome: ConnectionTokenIssuanceOutcome;
- errorCode?: string | null;
- metadata?: Record<string, unknown>;
- },
- dbClient: ToolAccessMutationDb = db,
- ) {
- await dbClient.insert(connectionTokenIssuances).values({
- companyId: input.companyId,
- applicationId: input.applicationId,
- connectionId: input.connectionId,
- agentId: input.agentId,
- runId: input.runId,
- issueId: input.issueId,
- projectId: input.projectId,
- responsibleUserId: input.responsibleUserId,
- path: input.path,
- requestedScope: input.requestedScope,
- issuedScope: input.issuedScope,
- ttlSeconds: input.ttlSeconds,
- expiresAt: input.expiresAt,
- tokenHash: input.tokenHash,
- outcome: input.outcome,
- errorCode: input.errorCode ?? null,
- metadata: input.metadata ?? {},
- });
- }
-
- async function auditConnectionTokenIssuance(input: {
- companyId: string;
- connectionId: string;
- agentId: string;
- runId: string;
- path: ConnectionTokenIssuancePath;
- outcome: ConnectionTokenIssuanceOutcome;
- reasonCode?: string | null;
- details?: Record<string, unknown>;
- }) {
- const success = input.outcome === "success";
- await audit({
- companyId: input.companyId,
- connectionId: input.connectionId,
- action: success ? "connection_token.minted" : "connection_token.denied",
- outcome: success ? "success" : "failure",
- reasonCode: input.reasonCode ?? null,
- actor: { actorType: "agent", actorId: input.agentId },
- details: {
- path: input.path,
- outcome: input.outcome,
- runId: input.runId,
- ...(input.details ?? {}),
- },
- });
- await logActivity(db, {
- companyId: input.companyId,
- actorType: "agent",
- actorId: input.agentId,
- agentId: input.agentId,
- runId: input.runId,
- action: success ? "connection_token.minted" : "connection_token.denied",
- entityType: "tool_connection",
- entityId: input.connectionId,
- details: {
- path: input.path,
- outcome: input.outcome,
- reasonCode: input.reasonCode ?? null,
- ...(input.details ?? {}),
- },
- });
- }
-
- async function enforceDefaultConnectionTokenRateLimit(input: {
- connection: typeof toolConnections.$inferSelect;
- agentId: string;
- path: ConnectionTokenIssuancePath;
- }) {
- const broker = tokenBrokerConfig(input.connection);
- const configured = Number(broker.rateLimitPerHour ?? 30);
- const limit =
- Number.isFinite(configured) && configured > 0
- ? Math.trunc(configured)
- : 30;
- const since = new Date(now().getTime() - 60 * 60 * 1000);
- const [row] = await db
- .select({ count: sql<number>`count(*)::int` })
- .from(connectionTokenIssuances)
- .where(
- and(
- eq(connectionTokenIssuances.companyId, input.connection.companyId),
- eq(connectionTokenIssuances.connectionId, input.connection.id),
- eq(connectionTokenIssuances.agentId, input.agentId),
- eq(connectionTokenIssuances.outcome, "success"),
- gte(connectionTokenIssuances.createdAt, since),
+ async function runtimeHealth(
+ companyId: string,
+ ): Promise<ToolRuntimeHealthSummary> {
+ const generatedAt = now();
+ const windowStartedAt = new Date(generatedAt.getTime() - 60 * 60 * 1000);
+ const stuckSlotMs = 5 * 60 * 1000;
+ const [
+ slots,
+ connections,
+ auditRows,
+ callEvents,
+ auditWriteFailureCounterRows,
+ ] = await Promise.all([
+ db
+ .select()
+ .from(toolRuntimeSlots)
+ .where(eq(toolRuntimeSlots.companyId, companyId)),
+ db
+ .select()
+ .from(toolConnections)
+ .where(eq(toolConnections.companyId, companyId)),
+ db
+ .select()
+ .from(toolAccessAuditEvents)
+ .where(
+ and(
+ eq(toolAccessAuditEvents.companyId, companyId),
+ gte(toolAccessAuditEvents.createdAt, windowStartedAt),
+ ),
+ )
+ .orderBy(desc(toolAccessAuditEvents.createdAt)),
+ db
+ .select()
+ .from(toolCallEvents)
+ .where(
+ and(
+ eq(toolCallEvents.companyId, companyId),
+ gte(toolCallEvents.createdAt, windowStartedAt),
+ ),
+ )
+ .orderBy(desc(toolCallEvents.createdAt)),
+ db
+ .select({
+ count: sql<number>`coalesce(sum(${toolRuntimeMetricCounters.count}), 0)::int`,
+ })
+ .from(toolRuntimeMetricCounters)
+ .where(
+ and(
+ eq(toolRuntimeMetricCounters.companyId, companyId),
+ eq(
+ toolRuntimeMetricCounters.metric,
+ TOOL_RUNTIME_AUDIT_WRITE_FAILURE_METRIC,
+ ),
+ gte(toolRuntimeMetricCounters.bucketStartAt, windowStartedAt),
+ ),
),
- );
- const count = Number(row?.count ?? 0);
- if (count >= limit) {
- throw new HttpError(429, "Connection token mint rate limit exceeded", {
- code: "rate_limited",
- path: input.path,
- limit,
- windowSeconds: 3600,
- });
- }
- }
-
- async function hasExplicitConnectionTokenMintProfileGrant(input: {
- companyId: string;
- agentId: string;
- issueId: string | null;
- projectId: string | null;
- routineId: string | null;
- }) {
- const bindings = await db
- .select()
- .from(toolProfileBindings)
- .where(eq(toolProfileBindings.companyId, input.companyId));
- const matchingBindings = bindings.filter((binding) => {
- if (binding.targetType === "company")
- return binding.targetId === input.companyId;
- if (binding.targetType === "agent")
- return binding.targetId === input.agentId;
- if (binding.targetType === "issue")
- return Boolean(input.issueId && binding.targetId === input.issueId);
- if (binding.targetType === "project")
- return Boolean(input.projectId && binding.targetId === input.projectId);
- if (binding.targetType === "routine")
- return Boolean(input.routineId && binding.targetId === input.routineId);
- return false;
- });
- const profileIds = profileIdsInBindingOrder(
- narrowestScopeBindings(matchingBindings),
+ ]);
+ const activeSlots = slots.filter(
+ (slot) =>
+ slot.status === "starting" ||
+ slot.status === "running" ||
+ slot.status === "idle",
);
- if (profileIds.length === 0) return false;
- const profiles = await db
- .select()
- .from(toolProfiles)
- .where(
- and(
- eq(toolProfiles.companyId, input.companyId),
- inArray(toolProfiles.id, profileIds),
- ),
- );
- const activeProfileIds = profiles
- .filter((profile) => profile.status === "active")
- .map((profile) => profile.id);
- if (activeProfileIds.length === 0) return false;
- const entries = await db
- .select()
- .from(toolProfileEntries)
- .where(
- and(
- eq(toolProfileEntries.companyId, input.companyId),
- inArray(toolProfileEntries.profileId, activeProfileIds),
- ),
- );
- return activeProfileIds.some((profileId) => {
- const profileEntries = entries.filter(
- (entry) => entry.profileId === profileId,
- );
- const exactBrokerEntries = profileEntries.filter(
- (entry) =>
- entry.selectorType === "tool_name" &&
- entry.toolName === CONNECTION_TOKEN_MINT_TOOL_NAME &&
- Object.keys(asRecord(entry.conditions)).length === 0,
- );
- if (exactBrokerEntries.some((entry) => entry.effect === "exclude"))
- return false;
- return exactBrokerEntries.some((entry) => entry.effect === "include");
+ const staleActiveSlots = activeSlots.filter((slot) => {
+ const lastProgressAt =
+ slot.lastUsedAt ?? slot.startedAt ?? slot.updatedAt;
+ return generatedAt.getTime() - lastProgressAt.getTime() > stuckSlotMs;
});
- }
-
- function accessContextForBroker(input: {
- connection: typeof toolConnections.$inferSelect;
- agentId: string;
- runId: string;
- issueId: string | null;
- actorSource?: ActorInfo["actorType"] | null;
- configPath: string;
- }) {
- return {
- consumerType: "tool_connection" as const,
- consumerId: input.connection.id,
- configPath: input.configPath,
- actorType: "agent" as const,
- actorId: input.agentId,
- actorSource: "agent_jwt" as const,
- issueId: input.issueId,
- heartbeatRunId: input.runId,
- };
- }
-
- function findBrokerCredentialRef(
- connection: typeof toolConnections.$inferSelect,
- ) {
- const broker = tokenBrokerConfig(connection);
- const configuredPath =
- readConfigString(broker, "parentCredentialConfigPath") ??
- readConfigString(broker, "credentialConfigPath") ??
- readConfigString(broker, "secretConfigPath");
- const configuredName =
- readConfigString(broker, "parentCredentialName") ??
- readConfigString(broker, "credentialName");
- const secretCandidates = connection.credentialSecretRefs.filter(
- (ref) =>
- ref.configPath !== "oauth.access_token" &&
- ref.configPath !== "oauth.refresh_token" &&
- ref.configPath !== "oauth.client_secret",
- );
- const secretRef = configuredPath
- ? connection.credentialSecretRefs.find(
- (ref) => ref.configPath === configuredPath,
- )
- : (secretCandidates.find(
- (ref) => ref.configPath === "credentials.deploy_token",
- ) ??
- secretCandidates.find(
- (ref) => ref.configPath === "pages.deploy_token",
- ) ??
- secretCandidates[0]);
- if (secretRef)
- return {
- kind: "secret_ref" as const,
- ref: secretRef,
- configPath: secretRef.configPath,
- };
- const credentialRef = configuredName
- ? connection.credentialRefs.find((ref) => ref.name === configuredName)
- : connection.credentialRefs[0];
- if (credentialRef)
- return {
- kind: "credential_ref" as const,
- ref: credentialRef,
- configPath: `credentials.${credentialRef.name}`,
- };
- return null;
- }
-
- async function resolveBrokerParentCredential(
- input: {
- connection: typeof toolConnections.$inferSelect;
- agentId: string;
- runId: string;
- issueId: string | null;
- },
- secretClient: ReturnType<typeof secretService> = secrets,
- ) {
- const ref = findBrokerCredentialRef(input.connection);
- if (!ref) {
- throw unprocessable(
- "Connection token exchange requires a vault-backed parent credential",
- {
- code: "parent_credential_missing",
- },
- );
- }
- if (ref.kind === "secret_ref") {
- return secretClient.resolveSecretValue(
- input.connection.companyId,
- ref.ref.secretId,
- ref.ref.versionSelector ?? "latest",
- {
- accessContext: accessContextForBroker({
- ...input,
- configPath: ref.configPath,
- }),
- bindingContext: accessContextForBroker({
- ...input,
- configPath: ref.configPath,
- }),
- },
- );
- }
- return secretClient.resolveSecretValue(
- input.connection.companyId,
- ref.ref.secretId,
- ref.ref.version ?? "latest",
- {
- accessContext: accessContextForBroker({
- ...input,
- configPath: ref.configPath,
- }),
- bindingContext: accessContextForBroker({
- ...input,
- configPath: ref.configPath,
- }),
- },
+ const callTerminalEvents = callEvents.filter(
+ (event) =>
+ event.eventType === "call_completed" ||
+ event.eventType === "call_failed" ||
+ event.eventType === "call_denied",
);
- }
-
- function exchangeTokenUrl(
- connection: typeof toolConnections.$inferSelect,
- isPages: boolean,
- ): string {
- const broker = tokenBrokerConfig(connection);
- const config = asRecord(connection.config);
- const url =
- readConfigString(broker, "tokenUrl") ??
- readConfigString(broker, "exchangeTokenUrl") ??
- readConfigString(config, "tokenExchangeUrl") ??
- readConfigString(config, "pagesTokenExchangeUrl");
- if (url) return url;
- const pagesApiBase = process.env.PAPERCLIP_PAGES_API_URL?.trim();
- if (isPages && pagesApiBase)
- return new URL(
- "/v1/tokens/exchange",
- pagesApiBase.endsWith("/") ? pagesApiBase : `${pagesApiBase}/`,
- ).toString();
- throw unprocessable("Connection token exchange URL is not configured", {
- code: "exchange_url_missing",
- });
- }
-
- function pagesNamespaceFromScope(scope: string[]): string | null {
- const first = scope[0];
- if (!first) return null;
- const match = first.match(/^pages:publish:ns\/([^/\s]+)$/);
- return match?.[1] ?? null;
- }
-
- async function mintExchangeConnectionToken(
- input: {
- connection: typeof toolConnections.$inferSelect;
- application: typeof toolApplications.$inferSelect | null;
- agentId: string;
- runId: string;
- issueId: string | null;
- responsibleUserId: string | null;
- scope: string[];
- ttlSeconds: number;
- },
- secretClient: ReturnType<typeof secretService> = secrets,
- ) {
- const isPages = isPagesTokenConnection(input.connection, input.application);
- const parentToken = await resolveBrokerParentCredential(
- input,
- secretClient,
+ const toolCallsLastHour = callTerminalEvents.length;
+ const toolTimeoutsLastHour = callTerminalEvents.filter(
+ (event) => event.outcome === "timeout",
+ ).length;
+ const toolFailuresLastHour = callTerminalEvents.filter(
+ (event) => event.outcome === "failure",
+ ).length;
+ const durations = auditRows
+ .map((row) => numberValue(asRecord(row.details).durationMs))
+ .filter((value): value is number => value !== null && value >= 0);
+ const capacityDeferrals = auditRows.filter(
+ (row) =>
+ row.action === "runtime_deferred" ||
+ row.reasonCode === "runtime_company_capacity_exhausted" ||
+ row.reasonCode === "runtime_host_capacity_exhausted",
+ ).length;
+ const restartAttempts = auditRows.filter(
+ (row) =>
+ row.action === "runtime_started" && row.reasonCode !== "lazy_start",
+ ).length;
+ const restartSuppressions = auditRows.filter(
+ (row) =>
+ row.action === "runtime_restart_suppressed" ||
+ row.reasonCode === "runtime_restart_suppressed",
+ ).length;
+ const idleEvictions = auditRows.filter(
+ (row) =>
+ row.action === "runtime_stopped" &&
+ row.reasonCode === "idle_ttl_expired",
+ ).length;
+ const missingSecretFailures = auditRows.filter(
+ (row) =>
+ row.reasonCode === "missing_secret" ||
+ (row.outcome === "failure" && row.reasonCode?.includes("secret")),
+ ).length;
+ const legacyAuditWriteFailures = auditRows.filter(
+ (row) =>
+ row.action === "runtime_audit_write_failed" ||
+ row.reasonCode === "audit_write_failed",
+ ).length;
+ const auditWriteFailuresMetric =
+ Number(auditWriteFailureCounterRows[0]?.count ?? 0) +
+ legacyAuditWriteFailures;
+ const enabledPathConnections = connections.filter(
+ (connection) => connection.status === "active" && connection.enabled,
);
- const broker = tokenBrokerConfig(input.connection);
- const protocol =
- readConfigString(broker, "protocol") ??
- readConfigString(broker, "exchangeProtocol") ??
- (isPages ? "pages" : "generic");
- const url = exchangeTokenUrl(input.connection, isPages);
- const actor = {
- type: "agent",
- id: input.agentId,
- runId: input.runId,
- ...(input.responsibleUserId
- ? { onBehalfOf: `user:${input.responsibleUserId}` }
- : {}),
+ const activeConnections = enabledPathConnections.length;
+ const disabledConnections = connections.filter(
+ (connection) => connection.status === "disabled",
+ ).length;
+ const degradedConnections = enabledPathConnections.filter((connection) =>
+ ["degraded", "failed", "error", "missing_secret"].includes(
+ connection.healthStatus,
+ ),
+ ).length;
+ const metrics = {
+ windowStartedAt,
+ windowEndedAt: generatedAt,
+ activeSlots: activeSlots.length,
+ startingSlots: slots.filter((slot) => slot.status === "starting").length,
+ runningSlots: slots.filter((slot) => slot.status === "running").length,
+ idleSlots: slots.filter((slot) => slot.status === "idle").length,
+ failedSlots: slots.filter(
+ (slot) => slot.status === "failed" || slot.status === "error",
+ ).length,
+ stoppedSlots: slots.filter(
+ (slot) => slot.status === "stopped" || slot.status === "disabled",
+ ).length,
+ stuckStartingSlots: staleActiveSlots.filter(
+ (slot) => slot.status === "starting",
+ ).length,
+ stuckRunningSlots: staleActiveSlots.filter(
+ (slot) => slot.status === "running",
+ ).length,
+ capacityDeferralsLastHour: capacityDeferrals,
+ restartAttemptsLastHour: restartAttempts,
+ restartSuppressionsLastHour: restartSuppressions,
+ idleEvictionsLastHour: idleEvictions,
+ toolCallsLastHour,
+ toolTimeoutsLastHour,
+ toolFailuresLastHour,
+ timeoutRateLastHour: percent(toolTimeoutsLastHour, toolCallsLastHour),
+ failureRateLastHour: percent(toolFailuresLastHour, toolCallsLastHour),
+ averageToolLatencyMsLastHour:
+ durations.length > 0
+ ? Math.round(
+ durations.reduce((sum, value) => sum + value, 0) /
+ durations.length,
+ )
+ : null,
+ p95ToolLatencyMsLastHour: percentile(durations, 95),
+ missingSecretFailuresLastHour: missingSecretFailures,
+ auditWriteFailuresLastHour: auditWriteFailuresMetric,
+ activeConnections,
+ disabledConnections,
+ degradedConnections,
+ remoteHttpConnections: connections.filter(
+ (connection) =>
+ connection.status !== "archived" &&
+ connection.transport === "mcp_remote",
+ ).length,
+ localStdioConnections: connections.filter(
+ (connection) =>
+ connection.status !== "archived" &&
+ connection.transport === "local_stdio",
+ ).length,
};
- let response: Response;
- if (protocol === "rfc8693") {
- const body = new URLSearchParams();
- body.set("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange");
- body.set("subject_token", parentToken);
- body.set(
- "subject_token_type",
- readConfigString(broker, "subjectTokenType") ??
- "urn:ietf:params:oauth:token-type:access_token",
- );
- body.set("scope", input.scope.join(" "));
- const audience = readConfigString(broker, "audience");
- if (audience) body.set("audience", audience);
- body.set(
- "requested_token_type",
- readConfigString(broker, "requestedTokenType") ??
- "urn:ietf:params:oauth:token-type:access_token",
- );
- body.set(
- "actor_token",
- Buffer.from(JSON.stringify(actor)).toString("base64url"),
- );
- body.set(
- "actor_token_type",
- readConfigString(broker, "actorTokenType") ??
- "urn:ietf:params:oauth:token-type:jwt",
- );
- const endpoint = parseRemoteHttpEndpoint(url, (message, code) =>
- badRequest(message, { code }),
- );
- response = await guardedRemoteHttpFetch(
- endpoint,
- {
- method: "POST",
- headers: { "content-type": "application/x-www-form-urlencoded" },
- body,
- },
- tokenBrokerHttpFetchOptions(endpoint),
- );
- } else {
- const namespace = isPages ? pagesNamespaceFromScope(input.scope) : null;
- const body =
- isPages && namespace
- ? {
- namespace,
- ttlSeconds: input.ttlSeconds,
- actions: ["publish"],
- actor,
- }
- : {
- scope: input.scope,
- ttlSeconds: input.ttlSeconds,
- actor,
- audience: readConfigString(broker, "audience"),
- };
- const endpoint = parseRemoteHttpEndpoint(url, (message, code) =>
- badRequest(message, { code }),
- );
- response = await guardedRemoteHttpFetch(
- endpoint,
- {
- method: "POST",
- headers: {
- authorization: `Bearer ${parentToken}`,
- "content-type": "application/json",
- },
- body: JSON.stringify(body),
+ const recommendations = buildRuntimeAlerts({
+ stuckStartingSlots: metrics.stuckStartingSlots,
+ stuckRunningSlots: metrics.stuckRunningSlots,
+ timeoutRate: metrics.timeoutRateLastHour,
+ timeoutCount: metrics.toolTimeoutsLastHour,
+ failureRate: metrics.failureRateLastHour,
+ failureCount: metrics.toolFailuresLastHour,
+ capacityDeferrals,
+ restartAttempts,
+ restartSuppressions,
+ degradedConnections,
+ disabledConnections,
+ missingSecretFailures,
+ auditWriteFailures: metrics.auditWriteFailuresLastHour,
+ });
+ const firing = recommendations.filter((alert) => alert.status === "firing");
+ const status = firing.some((alert) => alert.severity === "critical")
+ ? "critical"
+ : firing.length > 0
+ ? "degraded"
+ : "ok";
+ const deploymentMode = options.deploymentMode ?? "local_trusted";
+ const deploymentExposure = options.deploymentExposure ?? "private";
+ const localStdioSupported =
+ deploymentMode === "local_trusted" || Boolean(trustedRuntimeHost());
+ return {
+ status,
+ generatedAt,
+ runbookPath: "doc/MCP-RUNTIME-OPERATIONS.md",
+ metrics,
+ supportMatrix: {
+ remoteHttp: {
+ supported: true,
+ note: "mcp_remote MCP connections are supported in hosted cloud and local deployments.",
},
- tokenBrokerHttpFetchOptions(endpoint),
- );
- }
- const payload = (await response.json().catch(() => ({}))) as unknown;
- const record = asRecord(payload);
- if (!response.ok) {
- const code =
- typeof record.code === "string"
- ? record.code
- : typeof record.error === "string"
- ? record.error
- : "upstream_error";
- throw new HttpError(
- response.status === 401 || response.status === 403 ? 409 : 502,
- "Connection token exchange failed",
- {
- code:
- code === "parent_revoked" ? "credential_revoked" : "upstream_error",
- upstreamCode: code,
- upstreamStatus: response.status,
- upstreamRequestId:
- typeof record.requestId === "string" ? record.requestId : null,
+ localStdio: {
+ supported: localStdioSupported,
+ note: localStdioSupported
+ ? "local_stdio is available for local trusted mode or through the configured trusted MCP runtime host."
+ : `local_stdio should stay disabled for ${deploymentMode}/${deploymentExposure}; use mcp_remote or configure a trusted runtime worker.`,
},
- );
- }
- const token =
- typeof record.token === "string"
- ? record.token
- : typeof record.access_token === "string"
- ? record.access_token
- : null;
- if (!token)
- throw new HttpError(
- 502,
- "Connection token exchange did not return a token",
- { code: "upstream_token_missing" },
- );
- const expiresIn =
- typeof record.expires_in === "number"
- ? record.expires_in
- : Number(record.expires_in);
- const expiresAt =
- typeof record.expiresAt === "string" &&
- Number.isFinite(Date.parse(record.expiresAt))
- ? new Date(record.expiresAt)
- : typeof record.expires_at === "string" &&
- Number.isFinite(Date.parse(record.expires_at))
- ? new Date(record.expires_at)
- : new Date(
- now().getTime() +
- Math.min(
- input.ttlSeconds,
- Number.isFinite(expiresIn) && expiresIn > 0
- ? expiresIn
- : input.ttlSeconds,
- ) *
- 1000,
- );
- const responseScope =
- readConfigStringArray(record.scope).length > 0
- ? readConfigStringArray(record.scope)
- : input.scope;
- return {
- token,
- tokenType:
- typeof record.token_type === "string" ? record.token_type : "Bearer",
- expiresAt,
- scope: responseScope,
+ },
+ alerts: firing,
+ recommendations,
};
}
- function runtimeAlert(
- input: ToolRuntimeAlertRecommendation,
- ): ToolRuntimeAlertRecommendation {
- return input;
+ async function runtimeSlotById(
+ companyId: string,
+ slotId: string,
+ ): Promise<ToolRuntimeSlot> {
+ const [row] = await db
+ .select()
+ .from(toolRuntimeSlots)
+ .where(
+ and(
+ eq(toolRuntimeSlots.companyId, companyId),
+ eq(toolRuntimeSlots.id, slotId),
+ ),
+ )
+ .limit(1);
+ if (!row) throw notFound("Runtime slot not found");
+ return toRuntimeSlot(row);
}
- function buildRuntimeAlerts(input: {
- stuckStartingSlots: number;
- stuckRunningSlots: number;
- timeoutRate: number;
- timeoutCount: number;
- failureRate: number;
- failureCount: number;
- capacityDeferrals: number;
- restartAttempts: number;
- restartSuppressions: number;
- degradedConnections: number;
- disabledConnections: number;
- missingSecretFailures: number;
- auditWriteFailures: number;
- }): ToolRuntimeAlertRecommendation[] {
- const runbookSection = "doc/MCP-RUNTIME-OPERATIONS.md";
- const timeoutSeverity =
- input.timeoutCount >= 10 || input.timeoutRate >= 25
- ? "critical"
- : input.timeoutCount >= 3 && input.timeoutRate >= 10
- ? "warning"
- : "warning";
- const failureSeverity =
- input.failureCount >= 10 || input.failureRate >= 25
- ? "critical"
- : input.failureCount >= 5 && input.failureRate >= 10
- ? "warning"
- : "warning";
- const restartSeverity =
- input.restartSuppressions > 0 ? "critical" : "warning";
- return [
- runtimeAlert({
- name: "mcp_runtime_stuck_starting_slot",
- severity: "critical",
- status: input.stuckStartingSlots > 0 ? "firing" : "ok",
- threshold: "Any starting slot older than 5 minutes.",
- observed: `${input.stuckStartingSlots} stuck starting slot(s).`,
- description:
- "A local stdio runtime slot is stuck before it reaches running state.",
- firstResponderAction:
- "Inspect the slot health/logs, stop the slot, restart it once, then disable the connection if the slot sticks again.",
- runbookSection,
- }),
- runtimeAlert({
- name: "mcp_runtime_stuck_running_slot",
- severity: "critical",
- status: input.stuckRunningSlots > 0 ? "firing" : "ok",
- threshold: "Any running slot with no progress for 5 minutes.",
- observed: `${input.stuckRunningSlots} stuck running slot(s).`,
- description:
- "A runtime slot is running but has not recorded progress inside the supervisor stuck-slot window.",
- firstResponderAction:
- "Inspect recent audit events and active tool calls; restart the slot only after confirming no healthy call is still in progress.",
- runbookSection,
- }),
- runtimeAlert({
- name: "mcp_runtime_high_timeout_rate",
- severity: timeoutSeverity,
- status:
- input.timeoutCount >= 3 && input.timeoutRate >= 10 ? "firing" : "ok",
- threshold:
- "Warning at >=3 timeouts and >=10% timeout rate in 1 hour; critical at >=10 timeouts or >=25%.",
- observed: `${input.timeoutCount} timeout(s), ${input.timeoutRate}% timeout rate.`,
- description:
- "Tool gateway calls are timing out or being runtime-deferred at an elevated rate.",
- firstResponderAction:
- "Check upstream MCP health, Paperclip runtime capacity, and recent gateway audit failures before retrying workloads.",
- runbookSection,
- }),
- runtimeAlert({
- name: "mcp_runtime_high_error_rate",
- severity: failureSeverity,
- status:
- input.failureCount >= 5 && input.failureRate >= 10 ? "firing" : "ok",
- threshold:
- "Warning at >=5 failures and >=10% failure rate in 1 hour; critical at >=10 failures or >=25%.",
- observed: `${input.failureCount} failure(s), ${input.failureRate}% failure rate.`,
- description:
- "Tool gateway calls are failing after policy authorization.",
- firstResponderAction:
- "Group audit failures by reasonCode, then fix credentials/config or disable the affected connection.",
- runbookSection,
- }),
- runtimeAlert({
- name: "mcp_runtime_capacity_deferrals_repeated",
- severity: input.capacityDeferrals >= 10 ? "critical" : "warning",
- status: input.capacityDeferrals >= 3 ? "firing" : "ok",
- threshold:
- "Warning at >=3 capacity deferrals in 1 hour; critical at >=10.",
- observed: `${input.capacityDeferrals} capacity deferral(s) in 1 hour.`,
- description:
- "The runtime supervisor is refusing local stdio work because company or host slot capacity is exhausted.",
- firstResponderAction:
- "Stop idle/stale slots, lower noisy workloads, or raise slot caps only after confirming host capacity.",
- runbookSection,
- }),
- runtimeAlert({
- name: "mcp_runtime_restart_storm",
- severity: restartSeverity,
- status:
- input.restartSuppressions > 0 || input.restartAttempts >= 3
- ? "firing"
- : "ok",
- threshold:
- "Warning at >=3 restarts in 1 hour; critical on any restart suppression.",
- observed: `${input.restartAttempts} restart attempt(s), ${input.restartSuppressions} suppression(s).`,
- description:
- "Runtime slots are restarting repeatedly or have hit restart-storm suppression.",
- firstResponderAction:
- "Stop the affected slot, inspect stderr/audit reason codes, and keep the connection disabled until the template/upstream is fixed.",
- runbookSection,
- }),
- runtimeAlert({
- name: "mcp_runtime_connection_health_degraded",
- severity: input.degradedConnections > 0 ? "critical" : "warning",
- status:
- input.degradedConnections > 0 || input.disabledConnections > 0
- ? "firing"
- : "ok",
- threshold:
- "Any active enabled connection with degraded/failed/missing-secret health, or any disabled enabled-path connection.",
- observed: `${input.degradedConnections} degraded connection(s), ${input.disabledConnections} disabled connection(s).`,
- description:
- "A configured MCP connection is not healthy or has been disabled.",
- firstResponderAction:
- "Run a connection health check, refresh catalog after recovery, or keep the connection disabled and route agents to alternatives.",
- runbookSection,
- }),
- runtimeAlert({
- name: "mcp_runtime_missing_secret_failures",
- severity: input.missingSecretFailures >= 3 ? "critical" : "warning",
- status: input.missingSecretFailures > 0 ? "firing" : "ok",
- threshold:
- "Warning on any missing-secret failure; critical at >=3 in 1 hour.",
- observed: `${input.missingSecretFailures} missing-secret failure(s) in 1 hour.`,
- description:
- "A connection or tool call needed a bound secret that could not be resolved.",
- firstResponderAction:
- "Check secret bindings and provider health without printing secret values; rotate or rebind missing secrets.",
- runbookSection,
- }),
- runtimeAlert({
- name: "mcp_runtime_audit_write_failures",
- severity: "critical",
- status: input.auditWriteFailures > 0 ? "firing" : "ok",
- threshold: "Any audit write failure.",
- observed: `${input.auditWriteFailures} audit write failure(s) in 1 hour.`,
- description:
- "Tool gateway audit writes failed, reducing incident traceability.",
- firstResponderAction:
- "Treat as a control-plane incident: check database writes, activity log writes, and retry only after audit durability is restored.",
- runbookSection,
- }),
- ];
+ function runtimeSupervisorHttpError(error: ToolRuntimeSupervisorError) {
+ return new HttpError(error.status, error.message, {
+ code: error.reasonCode,
+ ...error.details,
+ });
}
- async function runtimeHealth(
+ async function controlRuntimeSlot(input: {
+ companyId: string;
+ slotId: string;
+ action: "stop" | "restart";
+ actor?: ActorInfo;
+ }): Promise<ToolRuntimeSlot> {
+ try {
+ if (input.action === "stop") {
+ await runtimeSupervisor.stopSlot({
+ companyId: input.companyId,
+ slotId: input.slotId,
+ reason: "operator_stop",
+ });
+ } else {
+ await runtimeSupervisor.restartSlot({
+ companyId: input.companyId,
+ slotId: input.slotId,
+ });
+ }
+ const slot = await runtimeSlotById(input.companyId, input.slotId);
+ await logActivity(db, {
+ companyId: input.companyId,
+ actorType: input.actor?.actorType ?? "system",
+ actorId: input.actor?.actorId ?? "tool-access-service",
+ action:
+ input.action === "stop"
+ ? "tool_runtime_slot.operator_stopped"
+ : "tool_runtime_slot.operator_restarted",
+ entityType: "tool_runtime_slot",
+ entityId: input.slotId,
+ details: {
+ runtimeKind: slot.runtimeKind,
+ status: slot.status,
+ slotKey: slot.slotKey,
+ },
+ });
+ return slot;
+ } catch (error) {
+ if (error instanceof ToolRuntimeSupervisorError) {
+ throw runtimeSupervisorHttpError(error);
+ }
+ throw error;
+ }
+ }
+
+ async function assertApplication(companyId: string, applicationId: string) {
+ const [row] = await db
+ .select()
+ .from(toolApplications)
+ .where(
+ and(
+ eq(toolApplications.id, applicationId),
+ eq(toolApplications.companyId, companyId),
+ ),
+ );
+ if (!row) throw notFound("Tool application not found");
+ return row;
+ }
+
+ async function assertOptionalAgent(
companyId: string,
- ): Promise<ToolRuntimeHealthSummary> {
- const generatedAt = now();
- const windowStartedAt = new Date(generatedAt.getTime() - 60 * 60 * 1000);
- const stuckSlotMs = 5 * 60 * 1000;
- const [
- slots,
- connections,
- auditRows,
- callEvents,
- auditWriteFailureCounterRows,
- ] = await Promise.all([
- db
- .select()
- .from(toolRuntimeSlots)
- .where(eq(toolRuntimeSlots.companyId, companyId)),
- db
- .select()
- .from(toolConnections)
- .where(eq(toolConnections.companyId, companyId)),
- db
- .select()
- .from(toolAccessAuditEvents)
- .where(
- and(
- eq(toolAccessAuditEvents.companyId, companyId),
- gte(toolAccessAuditEvents.createdAt, windowStartedAt),
- ),
- )
- .orderBy(desc(toolAccessAuditEvents.createdAt)),
- db
- .select()
- .from(toolCallEvents)
+ agentId: string | null | undefined,
+ label: string,
+ ) {
+ if (!agentId) return;
+ const [row] = await db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(eq(agents.id, agentId), eq(agents.companyId, companyId)));
+ if (!row) throw unprocessable(`${label} must belong to the same company`);
+ }
+
+ async function assertOptionalPlugin(pluginId: string | null | undefined) {
+ if (!pluginId) return;
+ const [row] = await db
+ .select({ id: plugins.id })
+ .from(plugins)
+ .where(eq(plugins.id, pluginId));
+ if (!row) throw unprocessable("Tool application plugin was not found");
+ }
+
+ async function assertSecretRefs(
+ companyId: string,
+ refs: Array<{
+ secretId: string;
+ configPath?: string | null;
+ projectionClass?: string | null;
+ projectionAllowlistKey?: string | null;
+ }>,
+ ) {
+ if (refs.length === 0) return;
+ for (const ref of refs) {
+ assertClass3ToolCredentialRefAllowed(ref);
+ }
+ const secretIds = [...new Set(refs.map((ref) => ref.secretId))];
+ for (const secretId of secretIds) {
+ const [secret] = await db
+ .select({ id: companySecrets.id })
+ .from(companySecrets)
.where(
and(
- eq(toolCallEvents.companyId, companyId),
- gte(toolCallEvents.createdAt, windowStartedAt),
+ eq(companySecrets.id, secretId),
+ eq(companySecrets.companyId, companyId),
),
- )
- .orderBy(desc(toolCallEvents.createdAt)),
- db
- .select({
- count: sql<number>`coalesce(sum(${toolRuntimeMetricCounters.count}), 0)::int`,
- })
- .from(toolRuntimeMetricCounters)
- .where(
- and(
- eq(toolRuntimeMetricCounters.companyId, companyId),
- eq(
- toolRuntimeMetricCounters.metric,
- TOOL_RUNTIME_AUDIT_WRITE_FAILURE_METRIC,
- ),
- gte(toolRuntimeMetricCounters.bucketStartAt, windowStartedAt),
- ),
- ),
- ]);
- const activeSlots = slots.filter(
- (slot) =>
- slot.status === "starting" ||
- slot.status === "running" ||
- slot.status === "idle",
- );
- const staleActiveSlots = activeSlots.filter((slot) => {
- const lastProgressAt =
- slot.lastUsedAt ?? slot.startedAt ?? slot.updatedAt;
- return generatedAt.getTime() - lastProgressAt.getTime() > stuckSlotMs;
- });
- const callTerminalEvents = callEvents.filter(
- (event) =>
- event.eventType === "call_completed" ||
- event.eventType === "call_failed" ||
- event.eventType === "call_denied",
- );
- const toolCallsLastHour = callTerminalEvents.length;
- const toolTimeoutsLastHour = callTerminalEvents.filter(
- (event) => event.outcome === "timeout",
- ).length;
- const toolFailuresLastHour = callTerminalEvents.filter(
- (event) => event.outcome === "failure",
- ).length;
- const durations = auditRows
- .map((row) => numberValue(asRecord(row.details).durationMs))
- .filter((value): value is number => value !== null && value >= 0);
- const capacityDeferrals = auditRows.filter(
- (row) =>
- row.action === "runtime_deferred" ||
- row.reasonCode === "runtime_company_capacity_exhausted" ||
- row.reasonCode === "runtime_host_capacity_exhausted",
- ).length;
- const restartAttempts = auditRows.filter(
- (row) =>
- row.action === "runtime_started" && row.reasonCode !== "lazy_start",
- ).length;
- const restartSuppressions = auditRows.filter(
- (row) =>
- row.action === "runtime_restart_suppressed" ||
- row.reasonCode === "runtime_restart_suppressed",
- ).length;
- const idleEvictions = auditRows.filter(
- (row) =>
- row.action === "runtime_stopped" &&
- row.reasonCode === "idle_ttl_expired",
- ).length;
- const missingSecretFailures = auditRows.filter(
- (row) =>
- row.reasonCode === "missing_secret" ||
- (row.outcome === "failure" && row.reasonCode?.includes("secret")),
- ).length;
- const legacyAuditWriteFailures = auditRows.filter(
- (row) =>
- row.action === "runtime_audit_write_failed" ||
- row.reasonCode === "audit_write_failed",
- ).length;
- const auditWriteFailuresMetric =
- Number(auditWriteFailureCounterRows[0]?.count ?? 0) +
- legacyAuditWriteFailures;
- const enabledPathConnections = connections.filter(
- (connection) => connection.status === "active" && connection.enabled,
- );
- const activeConnections = enabledPathConnections.length;
- const disabledConnections = connections.filter(
- (connection) => connection.status === "disabled",
- ).length;
- const degradedConnections = enabledPathConnections.filter((connection) =>
- ["degraded", "failed", "error", "missing_secret"].includes(
- connection.healthStatus,
- ),
- ).length;
- const metrics = {
- windowStartedAt,
- windowEndedAt: generatedAt,
- activeSlots: activeSlots.length,
- startingSlots: slots.filter((slot) => slot.status === "starting").length,
- runningSlots: slots.filter((slot) => slot.status === "running").length,
- idleSlots: slots.filter((slot) => slot.status === "idle").length,
- failedSlots: slots.filter(
- (slot) => slot.status === "failed" || slot.status === "error",
- ).length,
- stoppedSlots: slots.filter(
- (slot) => slot.status === "stopped" || slot.status === "disabled",
- ).length,
- stuckStartingSlots: staleActiveSlots.filter(
- (slot) => slot.status === "starting",
- ).length,
- stuckRunningSlots: staleActiveSlots.filter(
- (slot) => slot.status === "running",
- ).length,
- capacityDeferralsLastHour: capacityDeferrals,
- restartAttemptsLastHour: restartAttempts,
- restartSuppressionsLastHour: restartSuppressions,
- idleEvictionsLastHour: idleEvictions,
- toolCallsLastHour,
- toolTimeoutsLastHour,
- toolFailuresLastHour,
- timeoutRateLastHour: percent(toolTimeoutsLastHour, toolCallsLastHour),
- failureRateLastHour: percent(toolFailuresLastHour, toolCallsLastHour),
- averageToolLatencyMsLastHour:
- durations.length > 0
- ? Math.round(
- durations.reduce((sum, value) => sum + value, 0) /
- durations.length,
- )
- : null,
- p95ToolLatencyMsLastHour: percentile(durations, 95),
- missingSecretFailuresLastHour: missingSecretFailures,
- auditWriteFailuresLastHour: auditWriteFailuresMetric,
- activeConnections,
- disabledConnections,
- degradedConnections,
- remoteHttpConnections: connections.filter(
- (connection) =>
- connection.status !== "archived" &&
- connection.transport === "mcp_remote",
- ).length,
- localStdioConnections: connections.filter(
- (connection) =>
- connection.status !== "archived" &&
- connection.transport === "local_stdio",
- ).length,
- };
- const recommendations = buildRuntimeAlerts({
- stuckStartingSlots: metrics.stuckStartingSlots,
- stuckRunningSlots: metrics.stuckRunningSlots,
- timeoutRate: metrics.timeoutRateLastHour,
- timeoutCount: metrics.toolTimeoutsLastHour,
- failureRate: metrics.failureRateLastHour,
- failureCount: metrics.toolFailuresLastHour,
- capacityDeferrals,
- restartAttempts,
- restartSuppressions,
- degradedConnections,
- disabledConnections,
- missingSecretFailures,
- auditWriteFailures: metrics.auditWriteFailuresLastHour,
- });
- const firing = recommendations.filter((alert) => alert.status === "firing");
- const status = firing.some((alert) => alert.severity === "critical")
- ? "critical"
- : firing.length > 0
- ? "degraded"
- : "ok";
- const deploymentMode = options.deploymentMode ?? "local_trusted";
- const deploymentExposure = options.deploymentExposure ?? "private";
- const localStdioSupported =
- deploymentMode === "local_trusted" || Boolean(trustedRuntimeHost());
- return {
- status,
- generatedAt,
- runbookPath: "doc/MCP-RUNTIME-OPERATIONS.md",
- metrics,
- supportMatrix: {
- remoteHttp: {
- supported: true,
- note: "mcp_remote MCP connections are supported in hosted cloud and local deployments.",
- },
- localStdio: {
- supported: localStdioSupported,
- note: localStdioSupported
- ? "local_stdio is available for local trusted mode or through the configured trusted MCP runtime host."
- : `local_stdio should stay disabled for ${deploymentMode}/${deploymentExposure}; use mcp_remote or configure a trusted runtime worker.`,
+ );
+ if (!secret)
+ throw unprocessable(
+ "Tool connection credential secrets must belong to the same company",
+ );
+ }
+ }
+
+ async function assertGoogleSheetsSpreadsheetOwnership(
+ companyId: string,
+ config: Record<string, unknown>,
+ options: { excludeConnectionId?: string } = {},
+ ) {
+ if (!isGoogleSheetsConnectionConfig(config)) return;
+ const allowedSpreadsheetIds = googleSheetsAllowedSpreadsheetIds(config);
+ if (allowedSpreadsheetIds.length === 0) return;
+ const allowed = new Set(allowedSpreadsheetIds);
+ const rows = await db
+ .select({
+ id: toolConnections.id,
+ companyId: toolConnections.companyId,
+ config: toolConnections.config,
+ })
+ .from(toolConnections)
+ .where(ne(toolConnections.status, "archived"));
+
+ const conflictingSpreadsheetIds = new Set<string>();
+ for (const row of rows) {
+ if (row.id === options.excludeConnectionId || row.companyId === companyId)
+ continue;
+ if (!isGoogleSheetsConnectionConfig(row.config)) continue;
+ for (const spreadsheetId of googleSheetsAllowedSpreadsheetIds(
+ row.config,
+ )) {
+ if (allowed.has(spreadsheetId))
+ conflictingSpreadsheetIds.add(spreadsheetId);
+ }
+ }
+
+ if (conflictingSpreadsheetIds.size > 0) {
+ throw conflict(
+ "Google Sheets spreadsheet is already connected to another company.",
+ {
+ code: "google_sheets_spreadsheet_already_bound",
+ spreadsheetIds: Array.from(conflictingSpreadsheetIds).sort(),
},
- },
- alerts: firing,
- recommendations,
- };
+ );
+ }
}
- async function runtimeSlotById(
+ async function assertCatalogEntry(
companyId: string,
- slotId: string,
- ): Promise<ToolRuntimeSlot> {
+ catalogEntryId: string | null | undefined,
+ ) {
+ if (!catalogEntryId) return;
const [row] = await db
- .select()
- .from(toolRuntimeSlots)
+ .select({ id: toolCatalogEntries.id })
+ .from(toolCatalogEntries)
.where(
and(
- eq(toolRuntimeSlots.companyId, companyId),
- eq(toolRuntimeSlots.id, slotId),
+ eq(toolCatalogEntries.id, catalogEntryId),
+ eq(toolCatalogEntries.companyId, companyId),
),
- )
- .limit(1);
- if (!row) throw notFound("Runtime slot not found");
- return toRuntimeSlot(row);
- }
-
- function runtimeSupervisorHttpError(error: ToolRuntimeSupervisorError) {
- return new HttpError(error.status, error.message, {
- code: error.reasonCode,
- ...error.details,
- });
- }
-
- async function controlRuntimeSlot(input: {
- companyId: string;
- slotId: string;
- action: "stop" | "restart";
- actor?: ActorInfo;
- }): Promise<ToolRuntimeSlot> {
- try {
- if (input.action === "stop") {
- await runtimeSupervisor.stopSlot({
- companyId: input.companyId,
- slotId: input.slotId,
- reason: "operator_stop",
- });
- } else {
- await runtimeSupervisor.restartSlot({
- companyId: input.companyId,
- slotId: input.slotId,
- });
- }
- const slot = await runtimeSlotById(input.companyId, input.slotId);
- await logActivity(db, {
- companyId: input.companyId,
- actorType: input.actor?.actorType ?? "system",
- actorId: input.actor?.actorId ?? "tool-access-service",
- action:
- input.action === "stop"
- ? "tool_runtime_slot.operator_stopped"
- : "tool_runtime_slot.operator_restarted",
- entityType: "tool_runtime_slot",
- entityId: input.slotId,
- details: {
- runtimeKind: slot.runtimeKind,
- status: slot.status,
- slotKey: slot.slotKey,
- },
- });
- return slot;
- } catch (error) {
- if (error instanceof ToolRuntimeSupervisorError) {
- throw runtimeSupervisorHttpError(error);
- }
- throw error;
- }
- }
-
- async function assertApplication(companyId: string, applicationId: string) {
- const [row] = await db
- .select()
- .from(toolApplications)
- .where(
- and(
- eq(toolApplications.id, applicationId),
- eq(toolApplications.companyId, companyId),
- ),
- );
- if (!row) throw notFound("Tool application not found");
- return row;
- }
-
- async function assertOptionalAgent(
- companyId: string,
- agentId: string | null | undefined,
- label: string,
- ) {
- if (!agentId) return;
- const [row] = await db
- .select({ id: agents.id })
- .from(agents)
- .where(and(eq(agents.id, agentId), eq(agents.companyId, companyId)));
- if (!row) throw unprocessable(`${label} must belong to the same company`);
- }
-
- async function assertOptionalPlugin(pluginId: string | null | undefined) {
- if (!pluginId) return;
- const [row] = await db
- .select({ id: plugins.id })
- .from(plugins)
- .where(eq(plugins.id, pluginId));
- if (!row) throw unprocessable("Tool application plugin was not found");
- }
-
- async function assertSecretRefs(
- companyId: string,
- refs: Array<{
- secretId: string;
- configPath?: string | null;
- projectionClass?: string | null;
- projectionAllowlistKey?: string | null;
- }>,
- ) {
- if (refs.length === 0) return;
- for (const ref of refs) {
- assertClass3ToolCredentialRefAllowed(ref);
- }
- const secretIds = [...new Set(refs.map((ref) => ref.secretId))];
- for (const secretId of secretIds) {
- const [secret] = await db
- .select({ id: companySecrets.id })
- .from(companySecrets)
- .where(
- and(
- eq(companySecrets.id, secretId),
- eq(companySecrets.companyId, companyId),
- ),
- );
- if (!secret)
- throw unprocessable(
- "Tool connection credential secrets must belong to the same company",
- );
- }
- }
-
- async function assertGoogleSheetsSpreadsheetOwnership(
- companyId: string,
- config: Record<string, unknown>,
- options: { excludeConnectionId?: string } = {},
- ) {
- if (!isGoogleSheetsConnectionConfig(config)) return;
- const allowedSpreadsheetIds = googleSheetsAllowedSpreadsheetIds(config);
- if (allowedSpreadsheetIds.length === 0) return;
- const allowed = new Set(allowedSpreadsheetIds);
- const rows = await db
- .select({
- id: toolConnections.id,
- companyId: toolConnections.companyId,
- config: toolConnections.config,
- })
- .from(toolConnections)
- .where(ne(toolConnections.status, "archived"));
-
- const conflictingSpreadsheetIds = new Set<string>();
- for (const row of rows) {
- if (row.id === options.excludeConnectionId || row.companyId === companyId)
- continue;
- if (!isGoogleSheetsConnectionConfig(row.config)) continue;
- for (const spreadsheetId of googleSheetsAllowedSpreadsheetIds(
- row.config,
- )) {
- if (allowed.has(spreadsheetId))
- conflictingSpreadsheetIds.add(spreadsheetId);
- }
- }
-
- if (conflictingSpreadsheetIds.size > 0) {
- throw conflict(
- "Google Sheets spreadsheet is already connected to another company.",
- {
- code: "google_sheets_spreadsheet_already_bound",
- spreadsheetIds: Array.from(conflictingSpreadsheetIds).sort(),
- },
- );
- }
- }
-
- async function assertCatalogEntry(
- companyId: string,
- catalogEntryId: string | null | undefined,
- ) {
- if (!catalogEntryId) return;
- const [row] = await db
- .select({ id: toolCatalogEntries.id })
- .from(toolCatalogEntries)
- .where(
- and(
- eq(toolCatalogEntries.id, catalogEntryId),
- eq(toolCatalogEntries.companyId, companyId),
- ),
- );
- if (!row)
- throw unprocessable(
- "Tool profile catalog entry selector must belong to the same company",
- );
+ );
+ if (!row)
+ throw unprocessable(
+ "Tool profile catalog entry selector must belong to the same company",
+ );
}
async function appProfileForConnection(
@@ -12781,1032 +11838,39 @@ export function toolAccessService(
if (profile.id === "workspace.all") {
const requested = normalizeOauthScopes(stateRow.requestedScopes);
credentials.scopes = googleWorkspaceEffectiveScopes(requested, 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 tx.select({ id: toolConnections.id }).from(toolConnections)
- .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
- .for("update");
- 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] : []),
- ];
- 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,
- tokenType: credentials.tokenType,
- ...(credentials.refreshTokenExpiresAt
- ? { refreshTokenExpiresAt: credentials.refreshTokenExpiresAt }
- : {}),
- ...(credentials.accessTokenExpiresAt
- ? { refreshedAt: now().toISOString() }
- : {}),
- },
- ...(githubMetadata ? { github: githubMetadata } : {}),
- },
- 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 linkedInteractionKind = stateRow.interactionId
- ? await tx
- .select({ kind: issueThreadInteractions.kind })
- .from(issueThreadInteractions)
- .where(eq(issueThreadInteractions.id, stateRow.interactionId))
- .limit(1)
- .then((rows) => rows[0]?.kind ?? null)
- : null;
- if (
- stateRow.interactionId &&
- linkedInteractionKind === "request_confirmation"
- ) {
- 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");
- if (githubMetadata) {
- const [githubGrant] = await db
- .select({ id: connectionGrants.id })
- .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 (!githubGrant) throw new Error("GitHub grant was not persisted");
- await Promise.all(
- githubMetadata.installationIds.map((installationId) =>
- cloudConnector.setWebhookBinding({
- subject: connectorSubject,
- companyId: connection.companyId,
- id: `${githubGrant.id}_${installationId}`,
- installationId,
- connectionId: connection.id,
- grantId: githubGrant.id,
- active: true,
- accessToken: credentials.accessToken,
- }),
- ),
- );
- }
- 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;
- 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,
- };
- }
-
- async function completeVercelConnectCallback(input: {
- state: string;
- error?: string | null;
- actor?: ActorInfo;
- }): Promise<ConnectToolAppResult> {
- const stateRow = await consumeOAuthState(input.state, input.actor);
- if (stateRow.codeVerifier !== "vercel-connect") {
- throw badRequest("OAuth state does not belong to a Vercel Connect flow");
- }
- if (input.error) {
- await rejectPendingOAuthInteraction(stateRow, input.actor);
- throw new HttpError(
- 400,
- "Vercel Connect authorization did not complete. Start a new authorization to try again.",
- {
- code:
- input.error === "access_denied"
- ? "oauth_authorization_denied"
- : "vercel_connect_authorization_required",
- },
- );
- }
- if (!vercelConnect)
- throw vercelConnectHttpError(
- new VercelConnectClientError("vercel_connect_unavailable", 503),
- );
- let connection = await getConnectionRow(
- stateRow.connectionId,
- stateRow.companyId,
- );
- const credential = vercelCredentialFor(connection);
- if (
- credential.principalMode !== "user" ||
- connection.authKind !== "oauth"
- ) {
- throw badRequest(
- "Vercel Connect callback does not match this connection",
- );
- }
- const grantKind: ConnectionGrantKind = stateRow.subjectUserId
- ? "user"
- : "organization";
- if (stateRow.subjectUserId) {
- const [membership] = await db
- .select({ id: companyMemberships.id })
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, connection.companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, stateRow.subjectUserId),
- eq(companyMemberships.status, "active"),
- ne(companyMemberships.membershipRole, "viewer"),
- ),
- )
- .limit(1);
- if (!membership) {
- throw forbidden(
- "Your company membership no longer permits connection changes. Restore non-viewer access before authorizing this connection.",
- );
- }
- }
- const [existingGrant] = await db
- .select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, grantKind),
- grantKind === "user"
- ? eq(connectionGrants.subjectUserId, stateRow.subjectUserId!)
- : eq(connectionGrants.isDefault, true),
- ),
- )
- .limit(1);
- const derived = deriveVercelConnectSubject({
- credential,
- connectionId: connection.id,
- companyId: connection.companyId,
- grantKind,
- subjectUserId: stateRow.subjectUserId,
- });
- const request = vercelTokenRequest({
- credential,
- connectionId: connection.id,
- companyId: connection.companyId,
- resources: vercelConnectResourcesFor(connection),
- grant: {
- kind: grantKind,
- subjectUserId: stateRow.subjectUserId,
- externalCredential: existingGrant?.externalCredential,
- },
- });
- let token;
- try {
- token = await vercelConnect.getToken(request, { forceRefresh: true });
- } catch (error) {
- throw vercelConnectHttpError(error);
- }
- if (
- token.connector.id !== credential.connectorId &&
- token.connector.uid !== credential.connectorUid
- ) {
- throw new HttpError(
- 502,
- "Vercel Connect returned a token for a different connector.",
- {
- code: "vercel_connect_connector_mismatch",
- },
- );
- }
- const externalGrant = vercelGrantReference({
- credential,
- token,
- subjectId: derived.subjectId,
- verifiedAt: now(),
- });
- const grantValues = {
- providerTenant: token.tenantId
- ? { name: credential.service, externalId: token.tenantId }
- : { name: credential.service },
- credentialSecretRefs: [],
- externalCredential: externalGrant,
- status: "active" as const,
- isDefault: grantKind === "organization",
- revokedAt: null,
- revokedByAgentId: null,
- revokedByUserId: null,
- updatedAt: now(),
- };
- if (existingGrant) {
- await db
- .update(connectionGrants)
- .set(grantValues)
- .where(eq(connectionGrants.id, existingGrant.id));
- } else {
- await db.insert(connectionGrants).values({
- companyId: connection.companyId,
- connectionId: connection.id,
- kind: grantKind,
- subjectUserId: stateRow.subjectUserId,
- ...grantValues,
- createdByUserId:
- input.actor?.actorType === "user"
- ? (input.actor.actorId ?? null)
- : null,
- });
- }
- const preActivationLifecycle = {
- status: connection.status,
- enabled: connection.enabled,
- };
- [connection] = await db
- .update(toolConnections)
- .set({
- status: "active",
- enabled: true,
- credentialRefs: [],
- credentialSecretRefs: [],
- updatedAt: now(),
- })
- .where(
- and(
- eq(toolConnections.id, connection.id),
- eq(toolConnections.companyId, connection.companyId),
- ),
- )
- .returning();
- emitConnectionUpdated(
- connection,
- preActivationLifecycle,
- "oauth_callback",
- );
- await db
- .update(toolApplications)
- .set({ status: "active", updatedAt: now() })
- .where(eq(toolApplications.id, connection.applicationId));
- const sourceTemplateKey =
- typeof connection.config.sourceTemplateKey === "string"
- ? connection.config.sourceTemplateKey
- : null;
- const galleryEntry = sourceTemplateKey
- ? getConnectableAppDefinition(sourceTemplateKey)
- : null;
- if (!galleryEntry)
- throw badRequest(
- "Vercel Connect connection is missing its reviewed app definition",
- );
- const method = connectionMethodForConnection(galleryEntry, connection);
- const refresh = await refreshCatalog(connection.id, input.actor, {
- enableAllByDefault: true,
- skipDefaultProfileSync: true,
- credentialHeaders: {
- ...projectedConnectionHeaders(connection),
- [credential.headerName]: `${credential.headerPrefix ?? ""}${token.token}`,
- },
- });
- const suggestedDefaults = recommendedDefaultsForApp(
- galleryEntry,
- method.key,
- );
- const finished = await finishOAuthCatalogWithRecommendedDefaults({
- interactionId: stateRow.interactionId,
- connection,
- catalog: refresh.catalog,
- suggestedDefaults,
- actor: input.actor,
- });
- const [application] = await db
- .select()
- .from(toolApplications)
- .where(eq(toolApplications.id, connection.applicationId));
- return {
- connectionId: connection.id,
- application: toApplication(application),
- connection: finished.connection,
- catalog: refresh.catalog,
- actions: groupedActions(refresh.catalog),
- suggestedDefaults,
- auth: null,
- };
- }
-
- async function completeOAuthCallback(input: {
- state: string;
- code?: string | null;
- /**
- * RFC 6749 `error`. Untrusted, and deliberately the *only* thing read from a
- * failed callback — `error_description` and `error_uri` are not accepted as
- * input at all, so there is nothing for a hostile provider to reflect
- * through (PAP-17108).
- */
- error?: string | null;
- redirectUri: string;
- /** RFC 9207 `iss`, when the authorization server returns it. */
- iss?: string | null;
- actor?: ActorInfo;
- }): Promise<ConnectToolAppResult> {
- // Binding first, outcome second: the provider's report of a failure is only
- // acted on once the callback is bound to a state Paperclip issued and to the
- // actor that started the flow, so an unsolicited callback cannot drive any
- // path here. Consuming the state up front is what makes a denial terminal —
- // a refused request must not stay completable by a later code (PAP-17109).
- const stateRow = await consumeOAuthState(input.state, input.actor);
- if (input.error) {
- await rejectPendingOAuthInteraction(stateRow, input.actor);
- const providerError = normalizeOAuthProviderError(input.error);
- throw new HttpError(
- 400,
- oauthProviderErrorMessage(
- providerError,
- "The authorization server denied the request.",
- ),
- {
- code: "oauth_authorization_denied",
- providerError,
- },
- );
- }
- // Neither a code nor an error is not a usable answer either. It still spends
- // the request: the recovery is a fresh authorization, not a state left live
- // waiting for a better callback.
- if (!input.code) throw badRequest("OAuth callback is missing a code");
-
- let connection = await getConnectionRow(
- stateRow.connectionId,
- stateRow.companyId,
- );
- // Reauthorization refreshes credentials and catalog without rebuilding the
- // operator's action profile, policy rules, or access bindings.
- const shouldFinalizeDefaults = connection.status === "draft";
- const preCallbackLifecycle = {
- status: connection.status,
- enabled: connection.enabled,
- };
- await assertConnectorConnectionSetupEnabled(connection);
- const sourceTemplateKey =
- typeof connection.config.sourceTemplateKey === "string"
- ? connection.config.sourceTemplateKey
- : null;
- const galleryEntry = sourceTemplateKey
- ? getConnectableAppDefinition(sourceTemplateKey)
- : null;
- assertOAuthRedirectConstraints(galleryEntry, input.redirectUri);
- const endpoints = await oauthEndpointsForConnection(
- connection,
- null,
- input.redirectUri,
- );
- assertOAuthCallbackIssuer(connection, endpoints, input.iss);
- // Generic states created before requested scopes were persisted may still
- // complete after an upgrade. Keep their original cached/discovered scope set.
- const authorizedScopes = normalizeOauthScopes(
- stateRow.requestedScopes ?? (galleryEntry ? [] : endpoints.scopes),
- );
- const client = await oauthClientForConnection(
- connection,
- endpoints.provider,
- input.actor,
- );
- if (!client.clientId)
- throw unprocessable(
- `OAuth client id is not configured for ${endpoints.provider}`,
- );
-
- const token = await exchangeOAuthToken({
- tokenUrl: endpoints.tokenUrl,
- clientId: client.clientId,
- clientSecret: client.clientSecret,
- tokenEndpointAuthMethod: storedOAuthTokenEndpointAuthMethod(
- oauthConfig(connection),
- client.clientSecret,
- ),
- redirectUri: input.redirectUri,
- codeVerifier: stateRow.codeVerifier,
- code: input.code,
- resource: endpoints.resource,
- });
- if (sourceTemplateKey === "google-workspace" && !isGoogleWorkspaceScopeGrant(normalizeOauthScopes(token.scope))) {
- throw unprocessable("Google did not return a supported permission grant. Reconnect and choose the Google services you want to use.", { code: "oauth_scope_grant_invalid" });
- }
- if (sourceTemplateKey === "google-workspace") {
- token.scope = googleWorkspaceEffectiveScopes(authorizedScopes, normalizeOauthScopes(token.scope)).join(" ");
- if (!token.scope) throw unprocessable("Google did not grant any selected service permissions", { code: "oauth_scope_grant_invalid" });
- }
- const connectedAt = now();
- const expiresAt = token.expiresIn
- ? new Date(connectedAt.getTime() + token.expiresIn * 1000).toISOString()
- : null;
- if (stateRow.subjectUserId) {
- let personalCredentialSecretRefs: typeof connectionGrants.$inferSelect.credentialSecretRefs =
- [];
- await db.transaction(async (tx) => {
- // Serialize callback persistence with suspension/removal. Those paths
- // lock this same membership row before sweeping personal credentials.
- const [membership] = await tx
- .select({ id: companyMemberships.id })
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, connection.companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, stateRow.subjectUserId!),
- eq(companyMemberships.status, "active"),
- ne(companyMemberships.membershipRole, "viewer"),
- ),
- )
- .limit(1)
- .for("update");
- if (!membership) {
- throw forbidden(
- "Your company membership no longer permits connection changes. Ask a company owner to restore non-viewer access before you authorize this connection again.",
- );
- }
- const txSecrets = secretService(tx);
- const txSecretContext = { dbClient: tx, secretClient: txSecrets };
-
- const [existingUserGrant] = await tx
- .select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "user"),
- eq(connectionGrants.subjectUserId, stateRow.subjectUserId!),
- ),
- )
- .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 tx.select({ id: toolConnections.id }).from(toolConnections)
- .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
- .for("update");
- const subjectCredentialSecretRefs =
- existingUserGrant?.credentialSecretRefs ?? [];
- const accessRef = await createOrRotateOAuthSecret(
- {
- companyId: connection.companyId,
- connection,
- configPath: "oauth.access_token",
- label: "OAuth access token",
- value: token.accessToken,
- actor: input.actor,
- existingRefs: subjectCredentialSecretRefs,
- ownerUserId: stateRow.subjectUserId!,
- },
- txSecretContext,
- );
- const nextCredentialSecretRefs = [
- ...subjectCredentialSecretRefs.filter(
- (ref) =>
- ref.configPath !== "oauth.access_token" &&
- ref.configPath !== "oauth.refresh_token",
- ),
- accessRef,
- ];
- if (token.refreshToken) {
- nextCredentialSecretRefs.push(
- await createOrRotateOAuthSecret(
- {
- companyId: connection.companyId,
- connection,
- configPath: "oauth.refresh_token",
- label: "OAuth refresh token",
- value: token.refreshToken,
- actor: input.actor,
- existingRefs: subjectCredentialSecretRefs,
- ownerUserId: stateRow.subjectUserId!,
- },
- txSecretContext,
- ),
- );
- } else {
- const existingRefreshRef = subjectCredentialSecretRefs.find(
- (ref) => ref.configPath === "oauth.refresh_token",
- );
- if (existingRefreshRef)
- nextCredentialSecretRefs.push(existingRefreshRef);
- }
-
- const grantedScopes = resolveGrantedOauthScopes({
- tokenScope: token.scope,
- requestedScopes: authorizedScopes,
- });
- const grantValues = {
- providerTenant: {
- ...(existingUserGrant?.providerTenant ?? {}),
- oauth: {
- ...asRecord(asRecord(existingUserGrant?.providerTenant).oauth),
- strategy: "direct_oauth",
- accessTokenExpiresAt: expiresAt ?? undefined,
- scopes: grantedScopes.scopes,
- scopeSource: grantedScopes.scopeSource,
- unrequestedScopes: grantedScopes.unrequestedScopes,
- // Per-grant, because two users can authorize the same connection with
- // different scopes. The connection-level list is whichever callback ran last,
- // so it is the wrong baseline for anyone else's refresh.
- requestedScopes: authorizedScopes,
- tokenType: token.tokenType,
- refreshedAt: connectedAt.toISOString(),
- },
- },
- credentialSecretRefs: nextCredentialSecretRefs,
- status: "active" as const,
- revokedAt: null,
- revokedByAgentId: null,
- revokedByUserId: null,
- updatedAt: new Date(),
- };
- if (existingUserGrant) {
- await tx
- .update(connectionGrants)
- .set(grantValues)
- .where(eq(connectionGrants.id, existingUserGrant.id));
- } else {
- await tx.insert(connectionGrants).values({
- companyId: connection.companyId,
- connectionId: connection.id,
- kind: "user",
- subjectUserId: stateRow.subjectUserId!,
- ...grantValues,
- isDefault: false,
- createdByUserId: stateRow.subjectUserId!,
- });
- }
- personalCredentialSecretRefs = nextCredentialSecretRefs;
- const nextConfig = {
- ...connection.config,
- oauth: {
- ...withoutOAuthRefreshLease(oauthConfig(connection)),
- provider: endpoints.provider,
- authorizationUrl: endpoints.authorizationUrl,
- tokenUrl: endpoints.tokenUrl,
- metadataUrl: endpoints.metadataUrl ?? null,
- scopes: authorizedScopes,
- clientIdEnv: client.clientIdEnv,
- clientSecretEnv: client.clientSecret
- ? client.clientSecretEnv
- : null,
- credentialScope: credentialScope(connection, input.actor),
- issuer: endpoints.issuer ?? oauthConfig(connection).issuer ?? null,
- resource:
- endpoints.resource ?? oauthConfig(connection).resource ?? null,
- expiresAt,
- scope: token.scope,
- tokenType: token.tokenType,
- connectedAt: connectedAt.toISOString(),
- },
- providerMetadata: {
- ...asRecord(connection.config.providerMetadata),
- oauth: {
- expiresAt,
- scope: token.scope,
- scopeSource: grantedScopes.scopeSource,
- unrequestedScopes: grantedScopes.unrequestedScopes,
- tokenType: token.tokenType,
- },
- },
- };
- const [updatedConnection] = await tx
- .update(toolConnections)
- .set({
- status: "active",
- enabled: true,
- authKind: "oauth",
- credentialPolicy: connection.credentialPolicy,
- config: nextConfig,
- transportConfig: nextConfig,
- // A personal-only connection keeps tokens exclusively on its user
- // grant. Adding a personal identity to an existing shared/fallback
- // connection must not erase that connection's organization token.
- credentialRefs:
- connection.credentialPolicy === "per_user"
- ? connection.credentialRefs.filter(
- (ref) => ref.name !== "oauth.access_token",
- )
- : connection.credentialRefs,
- credentialSecretRefs:
- connection.credentialPolicy === "per_user"
- ? connection.credentialSecretRefs.filter(
- (ref) =>
- ref.configPath !== "oauth.access_token" &&
- ref.configPath !== "oauth.refresh_token",
- )
- : connection.credentialSecretRefs,
- updatedAt: new Date(),
- })
- .where(eq(toolConnections.id, connection.id))
- .returning();
- if (!updatedConnection)
- throw new Error("OAuth connection was not found");
- connection = updatedConnection;
- await tx
- .update(toolApplications)
- .set({
- status: "active",
- updatedAt: new Date(),
- })
- .where(eq(toolApplications.id, connection.applicationId));
- const linkedInteractionKind = stateRow.interactionId
- ? await tx
- .select({ kind: issueThreadInteractions.kind })
- .from(issueThreadInteractions)
- .where(eq(issueThreadInteractions.id, stateRow.interactionId))
- .limit(1)
- .then((rows) => rows[0]?.kind ?? null)
- : null;
- if (
- stateRow.interactionId &&
- linkedInteractionKind === "request_confirmation"
- ) {
- await tx
- .update(issueThreadInteractions)
- .set({
- status: "accepted",
- result: { version: 1, outcome: "accepted" },
- resolvedByUserId: stateRow.subjectUserId!,
- resolvedAt: new Date(),
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(issueThreadInteractions.id, stateRow.interactionId),
- eq(issueThreadInteractions.companyId, connection.companyId),
- ),
- );
- }
- await syncCredentialBindings(
- connection,
- connection.credentialPolicy === "per_user"
- ? personalCredentialSecretRefs
- : [],
- tx,
- );
- });
- emitConnectionUpdated(
- connection,
- preCallbackLifecycle,
- "oauth_callback",
- );
-
- // Personal OAuth used to return immediately after saving the grant. That
- // left the connection draft/paused and its catalog empty, so the person
- // who had just consented landed on a false "Nothing to test" state.
- // Activate and discover with the just-issued token before returning.
- const refresh = await refreshCatalog(connection.id, input.actor, {
- enableAllByDefault: shouldFinalizeDefaults,
- skipDefaultProfileSync: shouldFinalizeDefaults,
- credentialHeaders: { Authorization: `Bearer ${token.accessToken}` },
- });
- const [application] = await db
- .select()
- .from(toolApplications)
- .where(eq(toolApplications.id, connection.applicationId));
- if (!application)
- throw new Error("OAuth connection application was not found");
- const suggestedDefaults = galleryEntry
- ? recommendedDefaultsForApp(
- galleryEntry,
- connectionMethodForConnection(galleryEntry, connection).key,
+ 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,
)
- : { access: "all_agents" as const, askFirstRiskLevels: [] };
- const finished = shouldFinalizeDefaults
- ? await finishOAuthCatalogWithRecommendedDefaults({
- interactionId: stateRow.interactionId,
- connection,
- catalog: refresh.catalog,
- suggestedDefaults,
- actor: input.actor,
- })
: null;
- return {
- connectionId: refresh.connection.id,
- application: toApplication(application),
- connection: finished?.connection ?? refresh.connection,
- catalog: refresh.catalog,
- actions: groupedActions(refresh.catalog),
- suggestedDefaults,
- auth: null,
- };
- }
-
- const organizationActorUserId =
- stateRow.createdByActorType === "user" ? stateRow.createdByActorId : null;
- if (!organizationActorUserId) {
+ const authorizingUserId =
+ subjectUserId ??
+ (stateRow.createdByActorType === "user"
+ ? stateRow.createdByActorId
+ : null);
+ if (!authorizingUserId)
throw forbidden(
- "Organization OAuth completion requires the user who started sign-in",
+ `A signed-in connection manager must authorize ${providerName}`,
);
- }
+
await db.transaction(async (tx) => {
- // Keep callback persistence serialized with membership suspension, role
- // downgrade, and removal. Once this row is locked, authority cannot be
- // revoked between the live check and the shared credential/grant writes.
+ // 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,
@@ -13817,7 +11881,7 @@ export function toolAccessService(
and(
eq(companyMemberships.companyId, connection.companyId),
eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, organizationActorUserId),
+ eq(companyMemberships.principalId, authorizingUserId),
eq(companyMemberships.status, "active"),
ne(companyMemberships.membershipRole, "viewer"),
),
@@ -13826,43 +11890,77 @@ export function toolAccessService(
.for("update");
if (!membership) {
throw forbidden(
- "Your company membership no longer permits connection changes. Ask a company owner to restore non-viewer access before you authorize this connection again.",
+ `Your company membership no longer permits connection changes. Restore non-viewer access before you connect ${providerName} again.`,
);
}
- 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,
- organizationActorUserId,
- ),
- eq(
- principalPermissionGrants.permissionKey,
- "tools:manage_connections",
+ 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 company owner, admin, or member with connection-manager permission can share credentials with the organization.",
- );
+ )
+ .limit(1)
+ .for("update");
+ if (!roleCanManage && !explicitManagerGrant) {
+ throw forbidden(
+ "Only a connection manager can authorize a dedicated agent identity.",
+ );
+ }
}
- await tx.select({ id: connectionGrants.id }).from(connectionGrants)
- .where(and(eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "organization"), eq(connectionGrants.isDefault, true)))
+ 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)))
@@ -13870,1993 +11968,2592 @@ export function toolAccessService(
await tx.select({ id: toolConnections.id }).from(toolConnections)
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
.for("update");
- const txSecrets = secretService(tx);
- const txSecretContext = { dbClient: tx, secretClient: txSecrets };
-
- const subjectCredentialSecretRefs = connection.credentialSecretRefs;
+ const existingRefs =
+ existingCredentialGrant?.credentialSecretRefs ??
+ (personalCredential || agentCredential
+ ? []
+ : connection.credentialSecretRefs);
const accessRef = await createOrRotateOAuthSecret(
{
companyId: connection.companyId,
connection,
configPath: "oauth.access_token",
- label: "OAuth access token",
- value: token.accessToken,
+ label: `${providerName} access token`,
+ value: credentials.accessToken,
actor: input.actor,
+ existingRefs,
+ ownerUserId: personalCredential ? subjectUserId! : undefined,
},
txSecretContext,
);
- const nextCredentialSecretRefs = [
- ...subjectCredentialSecretRefs.filter(
- (ref) =>
- ref.configPath !== "oauth.access_token" &&
- ref.configPath !== "oauth.refresh_token",
- ),
- accessRef,
- ];
- if (token.refreshToken) {
- nextCredentialSecretRefs.push(
- await createOrRotateOAuthSecret(
+ const refreshRef = refreshToken
+ ? await createOrRotateOAuthSecret(
{
companyId: connection.companyId,
connection,
configPath: "oauth.refresh_token",
- label: "OAuth refresh token",
- value: token.refreshToken,
+ 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] : []),
+ ];
+ 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,
+ tokenType: credentials.tokenType,
+ ...(credentials.refreshTokenExpiresAt
+ ? { refreshTokenExpiresAt: credentials.refreshTokenExpiresAt }
+ : {}),
+ ...(credentials.accessTokenExpiresAt
+ ? { refreshedAt: now().toISOString() }
+ : {}),
+ },
+ ...(githubMetadata ? { github: githubMetadata } : {}),
+ },
+ 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 {
- const existingRefreshRef = subjectCredentialSecretRefs.find(
- (ref) => ref.configPath === "oauth.refresh_token",
- );
- if (existingRefreshRef)
- nextCredentialSecretRefs.push(existingRefreshRef);
- }
- const organizationGrantedScopes = resolveGrantedOauthScopes({
- tokenScope: token.scope,
- requestedScopes: authorizedScopes,
- });
+ 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: {
- ...withoutOAuthRefreshLease(oauthConfig(connection)),
- provider: endpoints.provider,
- authorizationUrl: endpoints.authorizationUrl,
- tokenUrl: endpoints.tokenUrl,
- metadataUrl: endpoints.metadataUrl ?? null,
- scopes: authorizedScopes,
- clientIdEnv: client.clientIdEnv,
- clientSecretEnv: client.clientSecret ? client.clientSecretEnv : null,
- credentialScope: credentialScope(connection, input.actor),
- // Keep the issuer and resource this grant was minted against so refresh,
- // reconnect, revoke and diagnostics resolve the same authorization server
- // instead of re-discovering one from a possibly-changed endpoint.
- issuer: endpoints.issuer ?? oauthConfig(connection).issuer ?? null,
- resource:
- endpoints.resource ?? oauthConfig(connection).resource ?? null,
- expiresAt,
- scope: token.scope,
- tokenType: token.tokenType,
- connectedAt: connectedAt.toISOString(),
- },
- providerMetadata: {
- ...asRecord(connection.config.providerMetadata),
- oauth: {
- expiresAt,
- scope: token.scope,
- scopeSource: organizationGrantedScopes.scopeSource,
- unrequestedScopes: organizationGrantedScopes.unrequestedScopes,
- tokenType: token.tokenType,
- },
+ ...oauthConfig(connection),
+ strategy: "paperclip_cloud_connector",
+ provider: galleryEntry?.slug,
+ connectorProfile,
+ connectorSubjectUserId: subjectUserId,
+ connectorSubjectAgentId: subjectAgentId,
+ resource: method.defaults?.serverUrl,
+ scopes: [...profile.scopes],
},
};
- const [updatedConnection] = await tx
+ [connection] = await tx
.update(toolConnections)
.set({
- status: "active",
- enabled: true,
+ status: shouldFinalizeManagedDefaults ? "draft" : "active",
+ enabled: shouldFinalizeManagedDefaults ? false : true,
authKind: "oauth",
config: nextConfig,
transportConfig: nextConfig,
- credentialSecretRefs: nextCredentialSecretRefs,
- credentialRefs: [
- ...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 ",
- },
- ],
- updatedAt: new Date(),
+ 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();
- connection = updatedConnection;
await tx
.update(toolApplications)
- .set({ status: "active", updatedAt: new Date() })
- .where(eq(toolApplications.id, connection.applicationId));
- // The organization grant is created before OAuth has any secrets to attach.
- // Synchronize it after every successful callback/rotation so all real tool
- // execution paths receive the credentials that setup and catalog discovery
- // just proved.
- await ensureDefaultOrganizationGrant(connection, tx, undefined, {
- scopes: organizationGrantedScopes.scopes,
- scopeSource: organizationGrantedScopes.scopeSource,
- unrequestedScopes: organizationGrantedScopes.unrequestedScopes,
- requestedScopes: authorizedScopes,
- });
- await syncCredentialBindings(connection, [], tx);
- });
- emitConnectionUpdated(
- connection,
- preCallbackLifecycle,
- "oauth_callback",
- );
-
- await checkConnectionHealth(connection.id, input.actor);
- const refresh = await refreshCatalog(connection.id, input.actor, {
- enableAllByDefault: shouldFinalizeDefaults,
- skipDefaultProfileSync: shouldFinalizeDefaults,
- });
- const [application] = await db
- .select()
- .from(toolApplications)
- .where(eq(toolApplications.id, connection.applicationId));
- const suggestedDefaults = galleryEntry
- ? recommendedDefaultsForApp(
- galleryEntry,
- connectionMethodForConnection(galleryEntry, connection).key,
- )
- : {
- access: "all_agents" as const,
- askFirstRiskLevels: [],
- };
- const finished = shouldFinalizeDefaults
- ? await finishOAuthCatalogWithRecommendedDefaults({
- interactionId: stateRow.interactionId,
- connection,
- catalog: refresh.catalog,
- suggestedDefaults,
- actor: input.actor,
- })
- : null;
- return {
- connectionId: refresh.connection.id,
- application: toApplication(application),
- connection: finished?.connection ?? refresh.connection,
- catalog: refresh.catalog,
- actions: groupedActions(refresh.catalog),
- suggestedDefaults,
- auth: null,
- };
- }
-
- /**
- * Finish the one decision that cannot safely be guessed for a browser OAuth
- * connection: whether the consenting identity stays personal or becomes the
- * company's shared identity. The provider callback always writes a fresh
- * token to the consenting user's grant first. Only this explicit endpoint may
- * promote it to company-scoped secrets.
- */
- async function finalizeOAuthAccess(
- companyId: string,
- connectionId: string,
- input: FinalizeOAuthAccess,
- actor?: ActorInfo,
- requestingAgentId?: string,
- ): Promise<FinishToolAppResult> {
- if (requestingAgentId)
- await assertAgentsInCompany(companyId, [requestingAgentId]);
- let connection = await getConnectionRow(connectionId, companyId);
- const preFinalizeLifecycle = {
- status: connection.status,
- enabled: connection.enabled,
- };
- if (connection.authKind !== "oauth")
- throw badRequest("This connection does not use browser sign-in");
- if (connection.status === "archived")
- throw conflict("Archived app connections cannot be finished");
- const actorUserId = actor?.actorType === "user" ? actor.actorId : null;
- if (!actorUserId)
- throw badRequest("Finishing browser sign-in requires a signed-in user");
-
- const [personalGrant] = await db
- .select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.companyId, companyId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "user"),
- eq(connectionGrants.subjectUserId, actorUserId),
- ),
- )
- .limit(1);
-
- if (connection.credentialSource === "vercel_connect") {
- const [organizationGrant] = await db
- .select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.companyId, companyId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "organization"),
- eq(connectionGrants.isDefault, true),
- ),
- )
- .limit(1);
- const selectedGrant =
- input.grantKind === "user" ? personalGrant : organizationGrant;
- if (
- !selectedGrant ||
- selectedGrant.status !== "active" ||
- !selectedGrant.externalCredential
- ) {
- throw conflict(
- "The selected Vercel Connect identity is missing. Authorize this connection again.",
- );
- }
- const expectedPolicy = input.grantKind === "user" ? "per_user" : "shared";
- if (connection.credentialPolicy !== expectedPolicy) {
- throw conflict(
- "Vercel Connect identity scope is fixed when the connector is attached. Create a new connection to change it.",
- );
- }
- } else if (input.grantKind === "user") {
- if (
- !personalGrant ||
- personalGrant.status !== "active" ||
- personalGrant.credentialSecretRefs.length === 0
- ) {
- throw conflict(
- "Your connected identity is missing. Connect this app again before choosing Just me.",
- );
- }
- if (
- connection.credentialPolicy === "shared" &&
- connection.credentialSecretRefs.length > 0
- ) {
- throw conflict("This connection already uses a company identity");
- }
- [connection] = await db
- .update(toolConnections)
.set({
- credentialPolicy: "per_user",
- credentialRefs: connection.credentialRefs.filter(
- (ref) => ref.name !== "oauth.access_token",
- ),
- credentialSecretRefs: connection.credentialSecretRefs.filter(
- (ref) =>
- ref.configPath !== "oauth.access_token" &&
- ref.configPath !== "oauth.refresh_token",
- ),
- status: "active",
- enabled: true,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(toolConnections.id, connection.id),
- eq(toolConnections.companyId, companyId),
- ),
- )
- .returning();
+ status: shouldFinalizeManagedDefaults ? "draft" : "active",
+ updatedAt: now(),
+ })
+ .where(eq(toolApplications.id, connection.applicationId));
await syncCredentialBindings(
connection,
- personalGrant.credentialSecretRefs,
+ personalCredential || agentCredential ? credentialSecretRefs : [],
+ tx,
);
- } else if (
- connection.credentialPolicy !== "shared" ||
- connection.credentialSecretRefs.length === 0
- ) {
+ const linkedInteractionKind = stateRow.interactionId
+ ? await tx
+ .select({ kind: issueThreadInteractions.kind })
+ .from(issueThreadInteractions)
+ .where(eq(issueThreadInteractions.id, stateRow.interactionId))
+ .limit(1)
+ .then((rows) => rows[0]?.kind ?? null)
+ : null;
if (
- !personalGrant ||
- personalGrant.status !== "active" ||
- personalGrant.credentialSecretRefs.length === 0
+ stateRow.interactionId &&
+ linkedInteractionKind === "request_confirmation"
) {
- throw conflict(
- "Your connected identity is missing. Connect this app again before sharing it.",
- );
+ await tx
+ .update(issueThreadInteractions)
+ .set({
+ status: "accepted",
+ result: { version: 1, outcome: "accepted" },
+ resolvedByUserId: authorizingUserId,
+ resolvedAt: now(),
+ updatedAt: now(),
+ })
+ .where(eq(issueThreadInteractions.id, stateRow.interactionId));
}
-
- const personalSecretIds = personalGrant.credentialSecretRefs.map(
- (ref) => ref.secretId,
- );
- const personalSecretRows = await db
- .select({
- id: companySecrets.id,
- scope: companySecrets.scope,
- ownerUserId: companySecrets.ownerUserId,
- userSecretDefinitionId: companySecrets.userSecretDefinitionId,
- })
- .from(companySecrets)
+ });
+ // 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");
+ if (githubMetadata) {
+ const [githubGrant] = await db
+ .select({ id: connectionGrants.id })
+ .from(connectionGrants)
.where(
and(
- eq(companySecrets.companyId, companyId),
- inArray(companySecrets.id, personalSecretIds),
- ),
- );
- const personalSecretById = new Map(
- personalSecretRows.map((row) => [row.id, row]),
- );
- const promotedRefs: ToolCredentialSecretRef[] = [];
- try {
- for (const ref of personalGrant.credentialSecretRefs) {
- const secretRow = personalSecretById.get(ref.secretId);
- if (
- !secretRow ||
- secretRow.scope !== "user" ||
- secretRow.ownerUserId !== actorUserId ||
- !secretRow.userSecretDefinitionId
- ) {
- throw forbidden(
- "Only your own connected identity can be shared with the company",
- );
- }
- if (
- ref.configPath !== "oauth.access_token" &&
- ref.configPath !== "oauth.refresh_token" &&
- ref.configPath !== "oauth.client_secret"
- ) {
- throw badRequest(
- "The connected identity contains an unsupported OAuth credential",
- );
- }
- const resolved = await secrets.resolveUserSecretValue(
- companyId,
- {
- definitionId: secretRow.userSecretDefinitionId,
- responsibleUserId: actorUserId,
- version: ref.versionSelector ?? "latest",
- },
- {
- consumerType: "tool_connection",
- consumerId: connection.id,
- responsibleUserId: actorUserId,
- actorType: "user",
- actorId: actorUserId,
- },
- );
- if (!resolved)
- throw unprocessable("The connected identity could not be read");
- const promoted = await createOrRotateOAuthSecret({
- companyId,
- connection,
- configPath: ref.configPath,
- label: ref.label ?? "OAuth credential",
- value: resolved.value,
- actor,
- existingRefs: promotedRefs,
- });
- promotedRefs.push({ ...ref, ...promoted });
- }
-
- const accessRef = promotedRefs.find(
- (ref) => ref.configPath === "oauth.access_token",
- );
- if (!accessRef)
- throw unprocessable(
- "The connected identity is missing its OAuth access token",
- );
- const connectionCredentialSecretRefs = [
- ...connection.credentialSecretRefs.filter(
- (ref) =>
- ref.configPath !== "oauth.access_token" &&
- ref.configPath !== "oauth.refresh_token",
- ),
- ...promotedRefs,
- ];
- const nowAt = new Date();
- await db.transaction(async (tx) => {
- await tx.select({ id: connectionGrants.id }).from(connectionGrants)
- .where(and(eq(connectionGrants.companyId, companyId), eq(connectionGrants.connectionId, connection.id),
- or(eq(connectionGrants.id, personalGrant.id), and(eq(connectionGrants.kind, "organization"), eq(connectionGrants.isDefault, true)))))
- .orderBy(connectionGrants.id).for("update");
- await tx.select({ id: toolApplications.id }).from(toolApplications)
- .where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, companyId)))
- .for("update");
- await tx.select({ id: toolConnections.id }).from(toolConnections)
- .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId)))
- .for("update");
- const [existingOrganizationGrant] = await tx
- .select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.companyId, companyId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "organization"),
- eq(connectionGrants.isDefault, true),
- ),
- )
- .limit(1);
- let organizationGrantId: string;
- if (existingOrganizationGrant) {
- organizationGrantId = existingOrganizationGrant.id;
- await tx
- .update(connectionGrants)
- .set({
- providerTenant: personalGrant.providerTenant,
- credentialSecretRefs: connectionCredentialSecretRefs,
- status: "active",
- revokedAt: null,
- revokedByAgentId: null,
- revokedByUserId: null,
- updatedAt: nowAt,
- })
- .where(eq(connectionGrants.id, existingOrganizationGrant.id));
- } else {
- const [createdOrganizationGrant] = await tx
- .insert(connectionGrants)
- .values({
- companyId,
- connectionId: connection.id,
- kind: "organization",
- subjectUserId: null,
- providerTenant: personalGrant.providerTenant,
- credentialSecretRefs: connectionCredentialSecretRefs,
- status: "active",
- isDefault: true,
- createdByUserId: actorUserId,
- })
- .returning({ id: connectionGrants.id });
- organizationGrantId = createdOrganizationGrant.id;
- }
- // Empty audience rows are the canonical "everyone in the company".
- await tx
- .delete(connectionGrantMembers)
- .where(
- and(
- eq(connectionGrantMembers.companyId, companyId),
- eq(connectionGrantMembers.grantId, organizationGrantId),
- ),
- );
- await tx
- .delete(connectionGrantDelegations)
- .where(
- and(
- eq(connectionGrantDelegations.companyId, companyId),
- eq(connectionGrantDelegations.grantId, personalGrant.id),
- ),
- );
- await tx
- .update(connectionGrants)
- .set({
- credentialSecretRefs: [],
- status: "revoked",
- revokedAt: nowAt,
- revokedByUserId: actorUserId,
- updatedAt: nowAt,
- })
- .where(eq(connectionGrants.id, personalGrant.id));
- [connection] = await tx
- .update(toolConnections)
- .set({
- credentialPolicy: "shared",
- credentialSecretRefs: connectionCredentialSecretRefs,
- credentialRefs: [
- {
- name: "oauth.access_token",
- secretId: accessRef.secretId,
- version: "latest",
- placement: "header",
- key: "Authorization",
- prefix: "Bearer ",
- },
- ],
- status: "active",
- enabled: true,
- updatedAt: nowAt,
- })
- .where(
- and(
- eq(toolConnections.id, connection.id),
- eq(toolConnections.companyId, companyId),
- ),
- )
- .returning();
- });
- } catch (error) {
- await Promise.all(
- promotedRefs.map((ref) =>
- secrets.remove(ref.secretId).catch(() => undefined),
+ 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!),
+ ),
),
- );
- throw error;
- }
- await syncCredentialBindings(connection);
- // The source values are no longer referenced by either grant or
- // connection. Removing them makes the promotion a move, not a copy.
- for (const secretId of personalSecretIds) await secrets.remove(secretId);
- }
-
- // Both identity branches above commit their own lifecycle write (draft ->
- // active) before `finishGalleryAppConnection` re-reads the row, so that
- // step alone would never observe this transition. This is the OAuth
- // access-finalization step of the same gallery setup flow (Apps and inline
- // task cards both reach it), hence `gallery`.
- emitConnectionUpdated(connection, preFinalizeLifecycle, "gallery");
- const catalog = await db
- .select()
- .from(toolCatalogEntries)
- .where(
- and(
- eq(toolCatalogEntries.companyId, companyId),
- eq(toolCatalogEntries.connectionId, connection.id),
- eq(toolCatalogEntries.status, "active"),
+ )
+ .limit(1);
+ if (!githubGrant) throw new Error("GitHub grant was not persisted");
+ await Promise.all(
+ githubMetadata.installationIds.map((installationId) =>
+ cloudConnector.setWebhookBinding({
+ subject: connectorSubject,
+ companyId: connection.companyId,
+ id: `${githubGrant.id}_${installationId}`,
+ installationId,
+ connectionId: connection.id,
+ grantId: githubGrant.id,
+ active: true,
+ accessToken: credentials.accessToken,
+ }),
),
);
- const sourceTemplateKey =
- typeof connection.config.sourceTemplateKey === "string"
- ? connection.config.sourceTemplateKey
- : null;
- const galleryEntry = sourceTemplateKey
- ? getConnectableAppDefinition(sourceTemplateKey)
+ }
+ 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;
- const defaults = galleryEntry
- ? recommendedDefaultsForApp(
- galleryEntry,
- connectionMethodForConnection(galleryEntry, connection).key,
- )
- : { askFirstRiskLevels: [] };
- const askFirstRiskLevels = new Set(
- Array.isArray(defaults.askFirstRiskLevels)
- ? defaults.askFirstRiskLevels.filter(
- (value): value is string => typeof value === "string",
- )
+ const activatedCatalogEntryIds = new Set(
+ shouldFinalizeManagedDefaults
+ ? refresh.catalog
+ .filter((entry) => entry.status === "quarantined")
+ .map((entry) => entry.id)
: [],
);
- const finished = await finishGalleryAppConnection(
- companyId,
- connection.id,
- {
- enabledCatalogEntryIds: catalog.map((entry) => entry.id),
- askFirstCatalogEntryIds: catalog
- .filter((entry) => askFirstRiskLevels.has(entry.riskLevel))
- .map((entry) => entry.id),
- access: requestingAgentId
- ? { agentIds: [requestingAgentId] }
- : "all_agents",
- preserveExistingAccess: Boolean(requestingAgentId),
- },
- actor,
+ const catalog = refresh.catalog.map((entry) =>
+ activatedCatalogEntryIds.has(entry.id)
+ ? { ...entry, status: "active" as const }
+ : entry,
);
- await db
- .insert(toolConnectionInstalls)
- .values({
- companyId,
- connectionId: connection.id,
- targetType: requestingAgentId ? "agent" : "company",
- targetId: requestingAgentId ?? companyId,
- createdByUserId: actorUserId,
- })
- .onConflictDoNothing();
- return finished;
+ 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,
+ };
}
- async function preflightGalleryAppMetadata(
- galleryKey: string,
- methodKey?: string | null,
- ): Promise<ToolAppMetadataPreflightResult> {
- const app = getConnectableAppDefinition(galleryKey);
- if (!app || app.availability?.available === false)
- throw notFound("App not found");
- const method = connectionMethodFor(app, methodKey);
- await assertExperimentalConnectorSetupEnabled(app.slug);
- if (method.transport !== "mcp_remote" || !method.defaults?.serverUrl) {
- throw unprocessable(
- "This app method does not use a hosted remote MCP endpoint",
+ async function completeVercelConnectCallback(input: {
+ state: string;
+ error?: string | null;
+ actor?: ActorInfo;
+ }): Promise<ConnectToolAppResult> {
+ const stateRow = await consumeOAuthState(input.state, input.actor);
+ if (stateRow.codeVerifier !== "vercel-connect") {
+ throw badRequest("OAuth state does not belong to a Vercel Connect flow");
+ }
+ if (input.error) {
+ await rejectPendingOAuthInteraction(stateRow, input.actor);
+ throw new HttpError(
+ 400,
+ "Vercel Connect authorization did not complete. Start a new authorization to try again.",
+ {
+ code:
+ input.error === "access_denied"
+ ? "oauth_authorization_denied"
+ : "vercel_connect_authorization_required",
+ },
);
}
-
- const serverUrl = await assertRemoteHttpUrlAllowed(
- method.defaults.serverUrl,
+ if (!vercelConnect)
+ throw vercelConnectHttpError(
+ new VercelConnectClientError("vercel_connect_unavailable", 503),
+ );
+ let connection = await getConnectionRow(
+ stateRow.connectionId,
+ stateRow.companyId,
);
- return preflightConnectionMetadata(app, method, method.defaults, serverUrl, () => options.now?.() ?? new Date());
- }
-
- return {
- /** Identity-only verification: no bot installation/repository access required. */
- verifyPersonalGitHubIdentity: async (companyId: string, connectionId: string, userId: string) => {
- const [connection] = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, companyId), eq(toolConnections.id, connectionId), eq(toolConnections.enabled, true)));
- if (!connection || (connection.config.sourceTemplateKey !== "github" && connection.transportConfig?.sourceTemplateKey !== "github")) throw notFound("GitHub connection not found");
- const [ownGrant] = await db.select().from(connectionGrants).where(and(eq(connectionGrants.companyId, companyId), eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.kind, "user"), eq(connectionGrants.subjectUserId, userId), eq(connectionGrants.status, "active")));
- if (!ownGrant) throw forbidden("Connect your own GitHub account first. Shared and agent connections cannot prove your identity.");
- const actor = { actorType: "user" as const, actorId: userId };
- const grant = await refreshOAuthGrantCredentials({ companyId, connectionId, grantId: ownGrant.id, actor });
- const accessRef = grant.credentialSecretRefs.find(ref => ref.configPath === "oauth.access_token");
- if (!accessRef) throw unprocessable("Reconnect your personal GitHub connection");
- const { value } = await resolveOAuthGrantSecret(connection, grant, accessRef, actor, undefined);
- const identity = await githubBotRequest<{ id?: number; login?: string; avatar_url?: string }>(fetch, value, "/user");
- if (!Number.isSafeInteger(identity.id) || !identity.id || !identity.login || !/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}$/.test(identity.login)) throw unprocessable("GitHub returned an invalid account identity");
- const [current] = await db.select({ id: connectionGrants.id }).from(connectionGrants).where(and(eq(connectionGrants.id, grant.id), eq(connectionGrants.companyId, companyId), eq(connectionGrants.subjectUserId, userId), eq(connectionGrants.status, "active")));
- if (!current) throw forbidden("Your GitHub connection was revoked. Connect it again.");
- return { githubUserId: String(identity.id), login: identity.login, avatarUrl: identity.avatar_url ?? null, connectionId, grantId: grant.id };
- },
- preflightGalleryAppMetadata,
- approvedStdioTemplates: async (
- companyId: string,
- ): Promise<ToolStdioCommandTemplate[]> => {
- const adminTemplates = await db
- .select()
- .from(toolStdioCommandTemplates)
- .where(eq(toolStdioCommandTemplates.companyId, companyId))
- .orderBy(asc(toolStdioCommandTemplates.templateKey));
- return [
- ...Object.keys(APPROVED_STDIO_TEMPLATES)
- .sort()
- .map((templateId) => builtInStdioTemplate(templateId)!),
- ...adminTemplates.map(toStdioCommandTemplate),
- ];
- },
-
- createStdioCommandTemplate: async (
- companyId: string,
- input: CreateToolStdioCommandTemplate,
- actor?: ActorInfo,
- ): Promise<ToolStdioCommandTemplate> => {
- if (builtInStdioTemplate(input.templateId)) {
- throw conflict(
- "A built-in stdio template already uses this templateId",
- );
- }
- const existing = await getAdminStdioTemplate(companyId, input.templateId);
- if (existing)
- throw conflict("A stdio command template already uses this templateId");
- const tools = input.tools
- .map((tool) => normalizeToolDescriptor(tool))
- .filter((tool): tool is McpToolDescriptor => Boolean(tool));
- const [row] = await db
- .insert(toolStdioCommandTemplates)
- .values({
- companyId,
- templateKey: input.templateId,
- name: input.name,
- description: input.description ?? null,
- status: "active",
- command: input.command,
- args: input.args,
- envKeys: input.envKeys,
- tools,
- createdByAgentId:
- actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
- createdByUserId:
- actor?.actorType === "user" ? (actor.actorId ?? null) : null,
- })
- .returning();
- return toStdioCommandTemplate(row);
- },
-
- disableStdioCommandTemplate: async (
- companyId: string,
- templateId: string,
- ): Promise<ToolStdioCommandTemplate> => {
- if (builtInStdioTemplate(templateId))
- throw unprocessable("Built-in stdio templates cannot be disabled");
- const existing = await getAdminStdioTemplate(companyId, templateId);
- if (!existing) throw notFound("Stdio command template not found");
- if (existing.status === "disabled")
- return toStdioCommandTemplate(existing);
- const at = now();
- const [row] = await db
- .update(toolStdioCommandTemplates)
- .set({ status: "disabled", disabledAt: at, updatedAt: at })
+ const credential = vercelCredentialFor(connection);
+ if (
+ credential.principalMode !== "user" ||
+ connection.authKind !== "oauth"
+ ) {
+ throw badRequest(
+ "Vercel Connect callback does not match this connection",
+ );
+ }
+ const grantKind: ConnectionGrantKind = stateRow.subjectUserId
+ ? "user"
+ : "organization";
+ if (stateRow.subjectUserId) {
+ const [membership] = await db
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
.where(
and(
- eq(toolStdioCommandTemplates.companyId, companyId),
- eq(toolStdioCommandTemplates.templateKey, templateId),
+ eq(companyMemberships.companyId, connection.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, stateRow.subjectUserId),
+ eq(companyMemberships.status, "active"),
+ ne(companyMemberships.membershipRole, "viewer"),
),
)
- .returning();
- return toStdioCommandTemplate(row);
- },
-
- async setupComposioApp(connectionId: string, toolkit: string, input: ComposioAppSetupInput, actor: ActorInfo): Promise<ComposioAppSetupResult> {
- if (!findComposioCatalogApp(toolkit)) throw notFound("This Composio app is not in the catalog");
- const { connection, manage } = await openComposioGateway(connectionId, actor);
- let result = composioAppSetupResult(await manage([{ name: toolkit, action: "list" }]), toolkit);
- if (input.action === "start" && result.status !== "connected") {
- result = composioAppSetupResult(await manage([{ name: toolkit, action: "add" }]), toolkit);
- if (result.status === "not_connected") throw unprocessable("Composio did not return a sign-in link for this app. Manage it in Composio to check its setup requirements.");
- }
- if (input.action === "complete") {
- if (result.status !== "connected") throw conflict("Finish connecting this app in Composio, then check again");
- const currentConnection = await getConnectionRow(connectionId);
- if (currentConnection.status !== "active" || !currentConnection.enabled) {
- throw conflict("The gateway is no longer active. Restore it before connecting this app.");
- }
- }
- await audit({ companyId: connection.companyId, connectionId, action: "tool_connection.upstream_app_setup", outcome: "success", actor,
- details: { toolkit, action: input.action, status: result.status } });
- return result;
- },
-
- listAggregatorApps: async (connectionId: string, actor: ActorInfo) => aggregatorAppsResponse(await getConnectionRow(connectionId), actor),
- syncAggregatorApps,
- refreshAggregatorApps: async (connectionId: string, requested: string[], actor: ActorInfo) => {
- const connection = await getConnectionRow(connectionId);
- if (aggregatorProvider(connection) === "composio" && requested.length) {
- const { manage } = await openComposioGateway(connectionId, actor);
- if (requested.some(toolkit => !findComposioCatalogApp(toolkit))) throw notFound("This Composio app is not in the catalog");
- await manage(requested.map(name => ({ name, action: "list" })));
- return aggregatorAppsResponse(connection, actor);
- }
- return syncAggregatorApps(connectionId, true, actor);
- },
- configureArcadeDiscovery,
- syncComposioApps: startComposioAppSync,
-
- async listComposioApps(connectionId: string, actor: ActorInfo) {
- const connection = await getConnectionRow(connectionId);
- if (actor.actorType !== "user" || !actor.actorId) throw forbidden("Board access required");
- if (connection.config.sourceTemplateKey !== "composio") throw notFound("Composio gateway not found");
- return composioAppsResponse(connection, actor);
- },
-
- async refreshComposioApps(connectionId: string, requested: string[], actor: ActorInfo) {
- if (requested.some(toolkit => !findComposioCatalogApp(toolkit))) throw notFound("This Composio app is not in the catalog");
- const { connection, manage } = await openComposioGateway(connectionId, actor);
- const existing = await cachedComposioApps(connection, actor);
- // Migrate observations from the original direct setup flow on the first visit.
- const history = await db.select({ details: toolAccessAuditEvents.details }).from(toolAccessAuditEvents).where(and(
- eq(toolAccessAuditEvents.companyId, connection.companyId), eq(toolAccessAuditEvents.connectionId, connectionId),
- eq(toolAccessAuditEvents.actorId, actor.actorId!), eq(toolAccessAuditEvents.action, "tool_connection.upstream_app_setup"),
- )).orderBy(desc(toolAccessAuditEvents.createdAt)).limit(128);
- const known = [...existing.filter(app => app.accounts.length > 0).map(app => app.toolkit),
- ...history.map(row => row.details.toolkit).filter((toolkit): toolkit is string => typeof toolkit === "string" && Boolean(findComposioCatalogApp(toolkit)))];
- const toolkits = [...new Set([...requested, ...known])];
- for (let start = 0; start < toolkits.length; start += 32) {
- await manage(toolkits.slice(start, start + 32).map(name => ({ name, action: "list" })));
- }
- return composioAppsResponse(connection, actor);
- },
-
- async manageComposioAppAccount(connectionId: string, toolkit: string, input: ComposioAppAccountInput, actor: ActorInfo) {
- if (!findComposioCatalogApp(toolkit)) throw notFound("This Composio app is not in the catalog");
- const { connection, manage } = await openComposioGateway(connectionId, actor);
- if (input.action !== "add") {
- const before = composioAppAccounts(await manage([{ name: toolkit, action: "list" }]), toolkit);
- if (!before?.some(account => account.id === input.accountId)) throw notFound("This account is no longer available in the selected Composio app");
- }
- const details = { toolkit, ...(input.action !== "add" ? { accountId: input.accountId } : {}) };
- await logActivity(db, { companyId: connection.companyId, actorType: "user", actorId: actor.actorId!,
- action: `tool_connection.upstream_account_${input.action}_requested`, entityType: "tool_connection", entityId: connectionId, details });
- let payload: unknown;
- try {
- payload = await manage([{ name: toolkit, action: input.action,
- ...(input.action !== "add" ? { account_id: input.accountId } : {}), ...(input.action === "rename" ? { alias: input.alias } : {}) }]);
- } catch (error) {
- await audit({ companyId: connection.companyId, connectionId, actor, action: `tool_connection.upstream_account_${input.action}`,
- outcome: "failure", reasonCode: "provider_unconfirmed", details });
- throw error;
- }
- const result = composioAppSetupResult(payload, toolkit); // Reject provider errors before reporting success.
- if (input.action === "add" && !result.authorizationUrl) throw unprocessable("Composio did not return a sign-in link. Check the app in Composio.");
- if (input.action !== "add") {
- const after = composioAppAccounts(await manage([{ name: toolkit, action: "list" }]), toolkit);
- if (!after || (input.action === "remove" ? after.some(account => account.id === input.accountId)
- : !after.some(account => account.id === input.accountId && account.alias === input.alias))) {
- throw conflict("Composio has not confirmed this change. Refresh the accounts before trying again.");
- }
+ .limit(1);
+ if (!membership) {
+ throw forbidden(
+ "Your company membership no longer permits connection changes. Restore non-viewer access before authorizing this connection.",
+ );
}
- await logActivity(db, { companyId: connection.companyId, actorType: "user", actorId: actor.actorId!,
- action: `tool_connection.upstream_account_${input.action}`, entityType: "tool_connection", entityId: connectionId,
- details: { toolkit, ...(input.action !== "add" ? { accountId: input.accountId } : {}) } });
- return { ...result, apps: await cachedComposioApps(connection, actor) };
- },
-
- connectGalleryApp,
-
- finishGalleryAppConnection,
-
- reconnectGalleryApp,
-
- storeConnectorOAuthSecret: createOrRotateOAuthSecret,
- resolveConnectorOAuthGrantSecret: resolveOAuthGrantSecret,
- startOAuth,
-
- startAuthorizationForAgent: async (input: {
- companyId: string;
- connectionId: string;
- agentId: string;
- runId: string;
- subjectUserId: string;
- scopes?: string[];
- returnTo?: string;
- redirectUri: string;
- }) => {
- const runContext = await loadBrokerRunContext(input);
- const connection = await getConnectionRow(
- input.connectionId,
- input.companyId,
+ }
+ const [existingGrant] = await db
+ .select()
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, grantKind),
+ grantKind === "user"
+ ? eq(connectionGrants.subjectUserId, stateRow.subjectUserId!)
+ : eq(connectionGrants.isDefault, true),
+ ),
+ )
+ .limit(1);
+ const derived = deriveVercelConnectSubject({
+ credential,
+ connectionId: connection.id,
+ companyId: connection.companyId,
+ grantKind,
+ subjectUserId: stateRow.subjectUserId,
+ });
+ const request = vercelTokenRequest({
+ credential,
+ connectionId: connection.id,
+ companyId: connection.companyId,
+ resources: vercelConnectResourcesFor(connection),
+ grant: {
+ kind: grantKind,
+ subjectUserId: stateRow.subjectUserId,
+ externalCredential: existingGrant?.externalCredential,
+ },
+ });
+ let token;
+ try {
+ token = await vercelConnect.getToken(request, { forceRefresh: true });
+ } catch (error) {
+ throw vercelConnectHttpError(error);
+ }
+ if (
+ token.connector.id !== credential.connectorId &&
+ token.connector.uid !== credential.connectorUid
+ ) {
+ throw new HttpError(
+ 502,
+ "Vercel Connect returned a token for a different connector.",
+ {
+ code: "vercel_connect_connector_mismatch",
+ },
+ );
+ }
+ const externalGrant = vercelGrantReference({
+ credential,
+ token,
+ subjectId: derived.subjectId,
+ verifiedAt: now(),
+ });
+ const grantValues = {
+ providerTenant: token.tenantId
+ ? { name: credential.service, externalId: token.tenantId }
+ : { name: credential.service },
+ credentialSecretRefs: [],
+ externalCredential: externalGrant,
+ status: "active" as const,
+ isDefault: grantKind === "organization",
+ revokedAt: null,
+ revokedByAgentId: null,
+ revokedByUserId: null,
+ updatedAt: now(),
+ };
+ if (existingGrant) {
+ await db
+ .update(connectionGrants)
+ .set(grantValues)
+ .where(eq(connectionGrants.id, existingGrant.id));
+ } else {
+ await db.insert(connectionGrants).values({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ kind: grantKind,
+ subjectUserId: stateRow.subjectUserId,
+ ...grantValues,
+ createdByUserId:
+ input.actor?.actorType === "user"
+ ? (input.actor.actorId ?? null)
+ : null,
+ });
+ }
+ const preActivationLifecycle = {
+ status: connection.status,
+ enabled: connection.enabled,
+ };
+ [connection] = await db
+ .update(toolConnections)
+ .set({
+ status: "active",
+ enabled: true,
+ credentialRefs: [],
+ credentialSecretRefs: [],
+ updatedAt: now(),
+ })
+ .where(
+ and(
+ eq(toolConnections.id, connection.id),
+ eq(toolConnections.companyId, connection.companyId),
+ ),
+ )
+ .returning();
+ emitConnectionUpdated(
+ connection,
+ preActivationLifecycle,
+ "oauth_callback",
+ );
+ await db
+ .update(toolApplications)
+ .set({ status: "active", updatedAt: now() })
+ .where(eq(toolApplications.id, connection.applicationId));
+ const sourceTemplateKey =
+ typeof connection.config.sourceTemplateKey === "string"
+ ? connection.config.sourceTemplateKey
+ : null;
+ const galleryEntry = sourceTemplateKey
+ ? getConnectableAppDefinition(sourceTemplateKey)
+ : null;
+ if (!galleryEntry)
+ throw badRequest(
+ "Vercel Connect connection is missing its reviewed app definition",
);
- if (
- !runContext.responsibleUserId ||
- runContext.responsibleUserId !== input.subjectUserId
- ) {
- throw new HttpError(
- 403,
- "The agent run cannot start authorization for the requested user",
- {
- code: "subject_not_permitted",
- connection: { uid: connection.uid },
- subject: { type: "user", userId: input.subjectUserId },
- },
- );
- }
- return startOAuth(input.companyId, connection.id, {
- redirectUri: input.redirectUri,
- actor: { actorType: "agent", actorId: input.agentId },
- subjectUserId: input.subjectUserId,
- scopes: input.scopes,
- returnTo: input.returnTo,
- issueId: runContext.issueId ?? undefined,
- });
- },
-
- peekOAuthState,
-
- completePaperclipCloudConnectorCallback,
-
- completeVercelConnectCallback,
-
- completeOAuthCallback,
- refreshOAuthGrantCredentials,
- finalizeOAuthAccess,
+ const method = connectionMethodForConnection(galleryEntry, connection);
+ const refresh = await refreshCatalog(connection.id, input.actor, {
+ enableAllByDefault: true,
+ skipDefaultProfileSync: true,
+ credentialHeaders: {
+ ...projectedConnectionHeaders(connection),
+ [credential.headerName]: `${credential.headerPrefix ?? ""}${token.token}`,
+ },
+ });
+ const suggestedDefaults = recommendedDefaultsForApp(
+ galleryEntry,
+ method.key,
+ );
+ const finished = await finishOAuthCatalogWithRecommendedDefaults({
+ interactionId: stateRow.interactionId,
+ connection,
+ catalog: refresh.catalog,
+ suggestedDefaults,
+ actor: input.actor,
+ });
+ const [application] = await db
+ .select()
+ .from(toolApplications)
+ .where(eq(toolApplications.id, connection.applicationId));
+ return {
+ connectionId: connection.id,
+ application: toApplication(application),
+ connection: finished.connection,
+ catalog: refresh.catalog,
+ actions: groupedActions(refresh.catalog),
+ suggestedDefaults,
+ auth: null,
+ };
+ }
- listExamples: async (companyId: string): Promise<ToolExampleSummary[]> => {
- return Promise.all(
- TOOL_EXAMPLES.map(async (definition) => {
- const rows = await exampleRows(companyId, definition);
- return exampleSummary(definition, rows);
- }),
+ async function completeOAuthCallback(input: {
+ state: string;
+ code?: string | null;
+ /**
+ * RFC 6749 `error`. Untrusted, and deliberately the *only* thing read from a
+ * failed callback — `error_description` and `error_uri` are not accepted as
+ * input at all, so there is nothing for a hostile provider to reflect
+ * through (PAP-17108).
+ */
+ error?: string | null;
+ redirectUri: string;
+ /** RFC 9207 `iss`, when the authorization server returns it. */
+ iss?: string | null;
+ actor?: ActorInfo;
+ }): Promise<ConnectToolAppResult> {
+ // Binding first, outcome second: the provider's report of a failure is only
+ // acted on once the callback is bound to a state Paperclip issued and to the
+ // actor that started the flow, so an unsolicited callback cannot drive any
+ // path here. Consuming the state up front is what makes a denial terminal —
+ // a refused request must not stay completable by a later code (PAP-17109).
+ const stateRow = await consumeOAuthState(input.state, input.actor);
+ if (input.error) {
+ await rejectPendingOAuthInteraction(stateRow, input.actor);
+ const providerError = normalizeOAuthProviderError(input.error);
+ throw new HttpError(
+ 400,
+ oauthProviderErrorMessage(
+ providerError,
+ "The authorization server denied the request.",
+ ),
+ {
+ code: "oauth_authorization_denied",
+ providerError,
+ },
);
- },
+ }
+ // Neither a code nor an error is not a usable answer either. It still spends
+ // the request: the recovery is a fresh authorization, not a state left live
+ // waiting for a better callback.
+ if (!input.code) throw badRequest("OAuth callback is missing a code");
- installExample: async (
- companyId: string,
- exampleId: string,
- actor?: ActorInfo,
- ): Promise<ToolExampleInstallResult> => {
- const definition = findExample(exampleId);
- const blocker = localStdioInstallBlocker();
- if (blocker) throw unprocessable(blocker);
- assertLocalStdioCanBeEnabled("local_stdio", true);
- await stdioTemplateId(companyId, { templateId: definition.templateId });
- const before = await exampleRows(companyId, definition);
- const application = await upsertExampleApplication(
- companyId,
- definition,
- before.application,
- );
- const connection = await upsertExampleConnection(
- companyId,
- definition,
- application.row.id,
- before.connection,
+ let connection = await getConnectionRow(
+ stateRow.connectionId,
+ stateRow.companyId,
+ );
+ // Reauthorization refreshes credentials and catalog without rebuilding the
+ // operator's action profile, policy rules, or access bindings.
+ const shouldFinalizeDefaults = connection.status === "draft";
+ const preCallbackLifecycle = {
+ status: connection.status,
+ enabled: connection.enabled,
+ };
+ await assertConnectorConnectionSetupEnabled(connection);
+ const sourceTemplateKey =
+ typeof connection.config.sourceTemplateKey === "string"
+ ? connection.config.sourceTemplateKey
+ : null;
+ const galleryEntry = sourceTemplateKey
+ ? getConnectableAppDefinition(sourceTemplateKey)
+ : null;
+ assertOAuthRedirectConstraints(galleryEntry, input.redirectUri);
+ const endpoints = await oauthEndpointsForConnection(
+ connection,
+ null,
+ input.redirectUri,
+ );
+ assertOAuthCallbackIssuer(connection, endpoints, input.iss);
+ // Generic states created before requested scopes were persisted may still
+ // complete after an upgrade. Keep their original cached/discovered scope set.
+ const authorizedScopes = normalizeOauthScopes(
+ stateRow.requestedScopes ?? (galleryEntry ? [] : endpoints.scopes),
+ );
+ const client = await oauthClientForConnection(
+ connection,
+ endpoints.provider,
+ input.actor,
+ );
+ if (!client.clientId)
+ throw unprocessable(
+ `OAuth client id is not configured for ${endpoints.provider}`,
);
- const refresh = await refreshCatalog(connection.row.id, actor);
- let catalog = refresh.catalog;
- const safeReadEntryIds = catalog
- .filter((entry) => entry.riskLevel === "read")
- .map((entry) => entry.id);
- if (safeReadEntryIds.length > 0) {
- const reviewedAt = new Date();
- await db
- .update(toolCatalogEntries)
- .set({
- status: "active",
- reviewedAt,
- reviewedByAgentId:
- actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
- reviewedByUserId:
- actor?.actorType === "user" ? (actor.actorId ?? null) : null,
- quarantinedAt: null,
- quarantineReason: null,
- updatedAt: reviewedAt,
- })
+
+ const token = await exchangeOAuthToken({
+ tokenUrl: endpoints.tokenUrl,
+ clientId: client.clientId,
+ clientSecret: client.clientSecret,
+ tokenEndpointAuthMethod: storedOAuthTokenEndpointAuthMethod(
+ oauthConfig(connection),
+ client.clientSecret,
+ ),
+ redirectUri: input.redirectUri,
+ codeVerifier: stateRow.codeVerifier,
+ code: input.code,
+ resource: endpoints.resource,
+ });
+ if (sourceTemplateKey === "google-workspace" && !isGoogleWorkspaceScopeGrant(normalizeOauthScopes(token.scope))) {
+ throw unprocessable("Google did not return a supported permission grant. Reconnect and choose the Google services you want to use.", { code: "oauth_scope_grant_invalid" });
+ }
+ if (sourceTemplateKey === "google-workspace") {
+ token.scope = googleWorkspaceEffectiveScopes(authorizedScopes, normalizeOauthScopes(token.scope)).join(" ");
+ if (!token.scope) throw unprocessable("Google did not grant any selected service permissions", { code: "oauth_scope_grant_invalid" });
+ }
+ const connectedAt = now();
+ const expiresAt = token.expiresIn
+ ? new Date(connectedAt.getTime() + token.expiresIn * 1000).toISOString()
+ : null;
+ if (stateRow.subjectUserId) {
+ let personalCredentialSecretRefs: typeof connectionGrants.$inferSelect.credentialSecretRefs =
+ [];
+ await db.transaction(async (tx) => {
+ // Serialize callback persistence with suspension/removal. Those paths
+ // lock this same membership row before sweeping personal credentials.
+ const [membership] = await tx
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, connection.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, stateRow.subjectUserId!),
+ eq(companyMemberships.status, "active"),
+ ne(companyMemberships.membershipRole, "viewer"),
+ ),
+ )
+ .limit(1)
+ .for("update");
+ if (!membership) {
+ throw forbidden(
+ "Your company membership no longer permits connection changes. Ask a company owner to restore non-viewer access before you authorize this connection again.",
+ );
+ }
+ const txSecrets = secretService(tx);
+ const txSecretContext = { dbClient: tx, secretClient: txSecrets };
+
+ const [existingUserGrant] = await tx
+ .select()
+ .from(connectionGrants)
.where(
and(
- eq(toolCatalogEntries.companyId, companyId),
- inArray(toolCatalogEntries.id, safeReadEntryIds),
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "user"),
+ eq(connectionGrants.subjectUserId, stateRow.subjectUserId!),
),
- );
- catalog = catalog.map((entry) =>
- safeReadEntryIds.includes(entry.id)
- ? {
- ...entry,
- status: "active",
- reviewedAt,
- quarantinedAt: null,
- quarantineReason: null,
- updatedAt: reviewedAt,
- }
- : entry,
+ )
+ .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 tx.select({ id: toolConnections.id }).from(toolConnections)
+ .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
+ .for("update");
+ const subjectCredentialSecretRefs =
+ existingUserGrant?.credentialSecretRefs ?? [];
+ const accessRef = await createOrRotateOAuthSecret(
+ {
+ companyId: connection.companyId,
+ connection,
+ configPath: "oauth.access_token",
+ label: "OAuth access token",
+ value: token.accessToken,
+ actor: input.actor,
+ existingRefs: subjectCredentialSecretRefs,
+ ownerUserId: stateRow.subjectUserId!,
+ },
+ txSecretContext,
);
- }
- const profile = await upsertExampleProfile(
- companyId,
- definition,
- before.profile,
- );
- const profileEntries = await syncExampleProfileEntries(
- companyId,
- profile.row.id,
- catalog,
- );
- const profileBinding = await upsertExampleProfileBinding(
- companyId,
- profile.row.id,
- before.profileBinding,
- actor,
- );
- const after = await exampleRows(companyId, definition);
- return {
- example: exampleSummary(definition, after),
- created:
- application.created ||
- connection.created ||
- profile.created ||
- !before.profileBinding,
- application: toApplication(application.row),
- connection: refresh.connection,
- profile: toProfile(profile.row),
- profileEntries,
- profileBinding,
- catalog,
- };
- },
+ const nextCredentialSecretRefs = [
+ ...subjectCredentialSecretRefs.filter(
+ (ref) =>
+ ref.configPath !== "oauth.access_token" &&
+ ref.configPath !== "oauth.refresh_token",
+ ),
+ accessRef,
+ ];
+ if (token.refreshToken) {
+ nextCredentialSecretRefs.push(
+ await createOrRotateOAuthSecret(
+ {
+ companyId: connection.companyId,
+ connection,
+ configPath: "oauth.refresh_token",
+ label: "OAuth refresh token",
+ value: token.refreshToken,
+ actor: input.actor,
+ existingRefs: subjectCredentialSecretRefs,
+ ownerUserId: stateRow.subjectUserId!,
+ },
+ txSecretContext,
+ ),
+ );
+ } else {
+ const existingRefreshRef = subjectCredentialSecretRefs.find(
+ (ref) => ref.configPath === "oauth.refresh_token",
+ );
+ if (existingRefreshRef)
+ nextCredentialSecretRefs.push(existingRefreshRef);
+ }
- smokeExample: async (
- companyId: string,
- exampleId: string,
- actor?: ActorInfo,
- ): Promise<ToolExampleSmokeResult> => {
- const definition = findExample(exampleId);
- const rows = await exampleRows(companyId, definition);
- if (!rows.connection || !rows.profile || !rows.profileBinding) {
- throw conflict("Install this tool example before running smoke checks");
- }
- const catalog =
- rows.catalog.length > 0
- ? rows.catalog.map(toCatalogEntry)
- : (await refreshCatalog(rows.connection.id, actor)).catalog;
- const readEntry = catalog.find(
- (entry) => entry.riskLevel === "read" && entry.status === "active",
- );
- const deniedEntry = catalog.find(
- (entry) =>
- entry.riskLevel === "write" || entry.riskLevel === "destructive",
- );
- if (!readEntry || !deniedEntry) {
- throw unprocessable(
- "Example smoke requires at least one read tool and one denied write/destructive tool",
+ const grantedScopes = resolveGrantedOauthScopes({
+ tokenScope: token.scope,
+ requestedScopes: authorizedScopes,
+ });
+ const grantValues = {
+ providerTenant: {
+ ...(existingUserGrant?.providerTenant ?? {}),
+ oauth: {
+ ...asRecord(asRecord(existingUserGrant?.providerTenant).oauth),
+ strategy: "direct_oauth",
+ accessTokenExpiresAt: expiresAt ?? undefined,
+ scopes: grantedScopes.scopes,
+ scopeSource: grantedScopes.scopeSource,
+ unrequestedScopes: grantedScopes.unrequestedScopes,
+ // Per-grant, because two users can authorize the same connection with
+ // different scopes. The connection-level list is whichever callback ran last,
+ // so it is the wrong baseline for anyone else's refresh.
+ requestedScopes: authorizedScopes,
+ tokenType: token.tokenType,
+ refreshedAt: connectedAt.toISOString(),
+ },
+ },
+ credentialSecretRefs: nextCredentialSecretRefs,
+ status: "active" as const,
+ revokedAt: null,
+ revokedByAgentId: null,
+ revokedByUserId: null,
+ updatedAt: new Date(),
+ };
+ if (existingUserGrant) {
+ await tx
+ .update(connectionGrants)
+ .set(grantValues)
+ .where(eq(connectionGrants.id, existingUserGrant.id));
+ } else {
+ await tx.insert(connectionGrants).values({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ kind: "user",
+ subjectUserId: stateRow.subjectUserId!,
+ ...grantValues,
+ isDefault: false,
+ createdByUserId: stateRow.subjectUserId!,
+ });
+ }
+ personalCredentialSecretRefs = nextCredentialSecretRefs;
+ const nextConfig = {
+ ...connection.config,
+ oauth: {
+ ...withoutOAuthRefreshLease(oauthConfig(connection)),
+ provider: endpoints.provider,
+ authorizationUrl: endpoints.authorizationUrl,
+ tokenUrl: endpoints.tokenUrl,
+ metadataUrl: endpoints.metadataUrl ?? null,
+ scopes: authorizedScopes,
+ clientIdEnv: client.clientIdEnv,
+ clientSecretEnv: client.clientSecret
+ ? client.clientSecretEnv
+ : null,
+ credentialScope: credentialScope(connection, input.actor),
+ issuer: endpoints.issuer ?? oauthConfig(connection).issuer ?? null,
+ resource:
+ endpoints.resource ?? oauthConfig(connection).resource ?? null,
+ expiresAt,
+ scope: token.scope,
+ tokenType: token.tokenType,
+ connectedAt: connectedAt.toISOString(),
+ },
+ providerMetadata: {
+ ...asRecord(connection.config.providerMetadata),
+ oauth: {
+ expiresAt,
+ scope: token.scope,
+ scopeSource: grantedScopes.scopeSource,
+ unrequestedScopes: grantedScopes.unrequestedScopes,
+ tokenType: token.tokenType,
+ },
+ },
+ };
+ const [updatedConnection] = await tx
+ .update(toolConnections)
+ .set({
+ status: "active",
+ enabled: true,
+ authKind: "oauth",
+ credentialPolicy: connection.credentialPolicy,
+ config: nextConfig,
+ transportConfig: nextConfig,
+ // A personal-only connection keeps tokens exclusively on its user
+ // grant. Adding a personal identity to an existing shared/fallback
+ // connection must not erase that connection's organization token.
+ credentialRefs:
+ connection.credentialPolicy === "per_user"
+ ? connection.credentialRefs.filter(
+ (ref) => ref.name !== "oauth.access_token",
+ )
+ : connection.credentialRefs,
+ credentialSecretRefs:
+ connection.credentialPolicy === "per_user"
+ ? connection.credentialSecretRefs.filter(
+ (ref) =>
+ ref.configPath !== "oauth.access_token" &&
+ ref.configPath !== "oauth.refresh_token",
+ )
+ : connection.credentialSecretRefs,
+ updatedAt: new Date(),
+ })
+ .where(eq(toolConnections.id, connection.id))
+ .returning();
+ if (!updatedConnection)
+ throw new Error("OAuth connection was not found");
+ connection = updatedConnection;
+ await tx
+ .update(toolApplications)
+ .set({
+ status: "active",
+ updatedAt: new Date(),
+ })
+ .where(eq(toolApplications.id, connection.applicationId));
+ const linkedInteractionKind = stateRow.interactionId
+ ? await tx
+ .select({ kind: issueThreadInteractions.kind })
+ .from(issueThreadInteractions)
+ .where(eq(issueThreadInteractions.id, stateRow.interactionId))
+ .limit(1)
+ .then((rows) => rows[0]?.kind ?? null)
+ : null;
+ if (
+ stateRow.interactionId &&
+ linkedInteractionKind === "request_confirmation"
+ ) {
+ await tx
+ .update(issueThreadInteractions)
+ .set({
+ status: "accepted",
+ result: { version: 1, outcome: "accepted" },
+ resolvedByUserId: stateRow.subjectUserId!,
+ resolvedAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(issueThreadInteractions.id, stateRow.interactionId),
+ eq(issueThreadInteractions.companyId, connection.companyId),
+ ),
+ );
+ }
+ await syncCredentialBindings(
+ connection,
+ connection.credentialPolicy === "per_user"
+ ? personalCredentialSecretRefs
+ : [],
+ tx,
);
- }
- const smokeActor = await exampleSmokeActor(companyId, actor);
- const connection = toConnection(rows.connection);
- const allowCheck = await runSmokeDecisionCheck({
- companyId,
- actor: smokeActor,
- connection,
- catalogEntry: readEntry,
- expectedDecision: "allow",
- name: "allow_read_tool",
- });
- const denyCheck = await runSmokeDecisionCheck({
- companyId,
- actor: smokeActor,
- connection,
- catalogEntry: deniedEntry,
- expectedDecision: "deny",
- name: "deny_write_tool",
});
- const auditCheck: ToolExampleSmokeCheck = {
- name: "audit_written",
- ok: Boolean(
- allowCheck.auditEventId &&
- allowCheck.toolCallEventId &&
- denyCheck.auditEventId &&
- denyCheck.toolCallEventId,
- ),
- details: {
- auditEventIds: [allowCheck.auditEventId, denyCheck.auditEventId],
- toolCallEventIds: [
- allowCheck.toolCallEventId,
- denyCheck.toolCallEventId,
- ],
- },
- };
- const checks = [allowCheck, denyCheck, auditCheck];
- return {
- exampleId: definition.id,
- ok: checks.every((check) => check.ok),
- actor: smokeActor,
+ emitConnectionUpdated(
connection,
- profile: toProfile(rows.profile),
- checks,
- };
- },
+ preCallbackLifecycle,
+ "oauth_callback",
+ );
- listApplications: async (companyId: string): Promise<ToolApplication[]> => {
- const rows = await db
+ // Personal OAuth used to return immediately after saving the grant. That
+ // left the connection draft/paused and its catalog empty, so the person
+ // who had just consented landed on a false "Nothing to test" state.
+ // Activate and discover with the just-issued token before returning.
+ const refresh = await refreshCatalog(connection.id, input.actor, {
+ enableAllByDefault: shouldFinalizeDefaults,
+ skipDefaultProfileSync: shouldFinalizeDefaults,
+ credentialHeaders: { Authorization: `Bearer ${token.accessToken}` },
+ });
+ const [application] = await db
.select()
.from(toolApplications)
- .where(eq(toolApplications.companyId, companyId))
- .orderBy(desc(toolApplications.updatedAt));
- return rows.map(toApplication);
- },
+ .where(eq(toolApplications.id, connection.applicationId));
+ if (!application)
+ throw new Error("OAuth connection application was not found");
+ const suggestedDefaults = galleryEntry
+ ? recommendedDefaultsForApp(
+ galleryEntry,
+ connectionMethodForConnection(galleryEntry, connection).key,
+ )
+ : { access: "all_agents" as const, askFirstRiskLevels: [] };
+ const finished = shouldFinalizeDefaults
+ ? await finishOAuthCatalogWithRecommendedDefaults({
+ interactionId: stateRow.interactionId,
+ connection,
+ catalog: refresh.catalog,
+ suggestedDefaults,
+ actor: input.actor,
+ })
+ : null;
+ return {
+ connectionId: refresh.connection.id,
+ application: toApplication(application),
+ connection: finished?.connection ?? refresh.connection,
+ catalog: refresh.catalog,
+ actions: groupedActions(refresh.catalog),
+ suggestedDefaults,
+ auth: null,
+ };
+ }
- createApplication: async (
- companyId: string,
- input: CreateToolApplication,
- ): Promise<ToolApplication> => {
- await assertOptionalPlugin(input.pluginId);
- await assertOptionalAgent(
- companyId,
- input.ownerAgentId,
- "Tool application owner agent",
+ const organizationActorUserId =
+ stateRow.createdByActorType === "user" ? stateRow.createdByActorId : null;
+ if (!organizationActorUserId) {
+ throw forbidden(
+ "Organization OAuth completion requires the user who started sign-in",
);
- const [row] = await db
- .insert(toolApplications)
- .values({
- companyId,
- applicationKey: input.applicationKey ?? normalizeKey(input.name),
- name: input.name,
- description: input.description ?? null,
- type: input.type,
- status: input.status ?? "active",
- pluginId: input.pluginId ?? null,
- ownerAgentId: input.ownerAgentId ?? null,
- ownerUserId: input.ownerUserId ?? null,
- metadata: input.metadata ?? {},
+ }
+ await db.transaction(async (tx) => {
+ // Keep callback persistence serialized with membership suspension, role
+ // downgrade, and removal. Once this row is locked, authority cannot be
+ // revoked between the live check and the shared credential/grant writes.
+ const [membership] = await tx
+ .select({
+ id: companyMemberships.id,
+ membershipRole: companyMemberships.membershipRole,
})
- .returning();
- return toApplication(row);
- },
-
- getApplication: async (
- applicationId: string,
- companyId?: string,
- ): Promise<ToolApplication> => {
- const where = companyId
- ? and(
- eq(toolApplications.id, applicationId),
- eq(toolApplications.companyId, companyId),
- )
- : eq(toolApplications.id, applicationId);
- const [row] = await db.select().from(toolApplications).where(where);
- if (!row) throw notFound("Tool application not found");
- return toApplication(row);
- },
-
- updateApplication: async (
- applicationId: string,
- input: UpdateToolApplication,
- ): Promise<ToolApplication> => {
- const [existing] = await db
- .select()
- .from(toolApplications)
- .where(eq(toolApplications.id, applicationId));
- if (!existing) throw notFound("Tool application not found");
- await assertOptionalPlugin(input.pluginId);
- await assertOptionalAgent(
- existing.companyId,
- input.ownerAgentId,
- "Tool application owner agent",
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, connection.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, organizationActorUserId),
+ eq(companyMemberships.status, "active"),
+ ne(companyMemberships.membershipRole, "viewer"),
+ ),
+ )
+ .limit(1)
+ .for("update");
+ if (!membership) {
+ throw forbidden(
+ "Your company membership no longer permits connection changes. Ask a company owner to restore non-viewer access before you authorize this connection again.",
+ );
+ }
+ 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,
+ organizationActorUserId,
+ ),
+ eq(
+ principalPermissionGrants.permissionKey,
+ "tools:manage_connections",
+ ),
+ ),
+ )
+ .limit(1)
+ .for("update");
+ if (!roleCanManage && !explicitManagerGrant) {
+ throw forbidden(
+ "Only a company owner, admin, or member with connection-manager permission can share credentials with the organization.",
+ );
+ }
+ await tx.select({ id: connectionGrants.id }).from(connectionGrants)
+ .where(and(eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "organization"), eq(connectionGrants.isDefault, true)))
+ .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 tx.select({ id: toolConnections.id }).from(toolConnections)
+ .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, connection.companyId)))
+ .for("update");
+ const txSecrets = secretService(tx);
+ const txSecretContext = { dbClient: tx, secretClient: txSecrets };
+
+ const subjectCredentialSecretRefs = connection.credentialSecretRefs;
+ const accessRef = await createOrRotateOAuthSecret(
+ {
+ companyId: connection.companyId,
+ connection,
+ configPath: "oauth.access_token",
+ label: "OAuth access token",
+ value: token.accessToken,
+ actor: input.actor,
+ },
+ txSecretContext,
);
- if (input.name && input.name !== existing.name) {
- const [duplicate] = await db
- .select({ id: toolApplications.id })
- .from(toolApplications)
- .where(
- and(
- eq(toolApplications.companyId, existing.companyId),
- eq(toolApplications.name, input.name),
- ne(toolApplications.id, applicationId),
- ),
- )
- .limit(1);
- if (duplicate) {
- throw conflict("A tool access record with that name already exists", {
- code: "tool_access_name_conflict",
- });
- }
+ const nextCredentialSecretRefs = [
+ ...subjectCredentialSecretRefs.filter(
+ (ref) =>
+ ref.configPath !== "oauth.access_token" &&
+ ref.configPath !== "oauth.refresh_token",
+ ),
+ accessRef,
+ ];
+ if (token.refreshToken) {
+ nextCredentialSecretRefs.push(
+ await createOrRotateOAuthSecret(
+ {
+ companyId: connection.companyId,
+ connection,
+ configPath: "oauth.refresh_token",
+ label: "OAuth refresh token",
+ value: token.refreshToken,
+ actor: input.actor,
+ },
+ txSecretContext,
+ ),
+ );
+ } else {
+ const existingRefreshRef = subjectCredentialSecretRefs.find(
+ (ref) => ref.configPath === "oauth.refresh_token",
+ );
+ if (existingRefreshRef)
+ nextCredentialSecretRefs.push(existingRefreshRef);
}
- const [row] = await db
- .update(toolApplications)
+ const organizationGrantedScopes = resolveGrantedOauthScopes({
+ tokenScope: token.scope,
+ requestedScopes: authorizedScopes,
+ });
+ const nextConfig = {
+ ...connection.config,
+ oauth: {
+ ...withoutOAuthRefreshLease(oauthConfig(connection)),
+ provider: endpoints.provider,
+ authorizationUrl: endpoints.authorizationUrl,
+ tokenUrl: endpoints.tokenUrl,
+ metadataUrl: endpoints.metadataUrl ?? null,
+ scopes: authorizedScopes,
+ clientIdEnv: client.clientIdEnv,
+ clientSecretEnv: client.clientSecret ? client.clientSecretEnv : null,
+ credentialScope: credentialScope(connection, input.actor),
+ // Keep the issuer and resource this grant was minted against so refresh,
+ // reconnect, revoke and diagnostics resolve the same authorization server
+ // instead of re-discovering one from a possibly-changed endpoint.
+ issuer: endpoints.issuer ?? oauthConfig(connection).issuer ?? null,
+ resource:
+ endpoints.resource ?? oauthConfig(connection).resource ?? null,
+ expiresAt,
+ scope: token.scope,
+ tokenType: token.tokenType,
+ connectedAt: connectedAt.toISOString(),
+ },
+ providerMetadata: {
+ ...asRecord(connection.config.providerMetadata),
+ oauth: {
+ expiresAt,
+ scope: token.scope,
+ scopeSource: organizationGrantedScopes.scopeSource,
+ unrequestedScopes: organizationGrantedScopes.unrequestedScopes,
+ tokenType: token.tokenType,
+ },
+ },
+ };
+ const [updatedConnection] = await tx
+ .update(toolConnections)
.set({
- name: input.name ?? existing.name,
- description: input.description ?? existing.description,
- status: input.status ?? existing.status,
- pluginId: input.pluginId ?? existing.pluginId,
- ownerAgentId: input.ownerAgentId ?? existing.ownerAgentId,
- ownerUserId: input.ownerUserId ?? existing.ownerUserId,
- metadata: input.metadata ?? existing.metadata,
+ status: "active",
+ enabled: true,
+ authKind: "oauth",
+ config: nextConfig,
+ transportConfig: nextConfig,
+ credentialSecretRefs: nextCredentialSecretRefs,
+ credentialRefs: [
+ ...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 ",
+ },
+ ],
updatedAt: new Date(),
})
- .where(eq(toolApplications.id, applicationId))
+ .where(eq(toolConnections.id, connection.id))
.returning();
- return toApplication(row);
- },
-
- deleteApplication: async (
- applicationId: string,
- ): Promise<ToolApplication> => {
- const [existing] = await db
- .select()
- .from(toolApplications)
- .where(eq(toolApplications.id, applicationId));
- if (!existing) throw notFound("Tool application not found");
- // Guard: never orphan connections. The caller must remove the connections
- // or archive the application instead — there is no force-cascade in v1.
- const linkedConnections = await db
- .select({ id: toolConnections.id })
- .from(toolConnections)
- .where(eq(toolConnections.applicationId, applicationId));
- if (linkedConnections.length > 0) {
- throw conflict(
- "This application still has connections. Remove its connections or archive the application instead of deleting it.",
- { connectionCount: linkedConnections.length },
- );
- }
- // The pre-check above gives a friendly 409 in the common case, but it cannot close the
- // race where a connection is created in the gap before this delete runs. The FK is now
- // ON DELETE RESTRICT, so such a delete fails closed with a foreign_key_violation instead
- // of silently cascading the new connection away. Translate that into the same 409 so the
- // endpoint keeps its contract instead of surfacing a 500.
- let row: typeof toolApplications.$inferSelect | undefined;
- try {
- [row] = await db
- .delete(toolApplications)
- .where(eq(toolApplications.id, applicationId))
- .returning();
- } catch (error) {
- if (isToolConnectionForeignKeyViolation(error)) {
- throw conflict(
- "This application still has connections. Remove its connections or archive the application instead of deleting it.",
- );
- }
- throw error;
- }
- if (!row) throw notFound("Tool application not found");
- return toApplication(row);
- },
-
- // Repository discovery uses credential audiences, not connection-management
- // visibility. An administrator cannot browse another user's private repos.
- listProjectRepositories: async (companyId: string, userId: string | null, localTrusted = false) =>
- toolAccessService(db).listGitHubRepositories(companyId, userId, localTrusted),
-
- // Return identifiers, never credentials, so each attempted read can recheck its grant.
- githubReadConnectionIds: async (companyId: string, userId: string | null, localTrusted = false): Promise<string[]> => {
- const connections = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, companyId), eq(toolConnections.enabled, true))).orderBy(desc(toolConnections.updatedAt));
- const ids: string[] = [];
- for (const connection of connections) {
- if (connection.status !== "active" || asRecord(connection.config).sourceTemplateKey !== "github") continue;
- try {
- await gitHubReadGrantAccess(db, companyId, connection.id, userId, localTrusted);
- ids.push(connection.id);
- } catch (error) {
- // Only ineligible grants are skipped; database/service failures must surface.
- if (!(error instanceof Error && "status" in error && error.status === 403)) throw error;
- }
- }
- return ids;
- },
+ connection = updatedConnection;
+ await tx
+ .update(toolApplications)
+ .set({ status: "active", updatedAt: new Date() })
+ .where(eq(toolApplications.id, connection.applicationId));
+ // The organization grant is created before OAuth has any secrets to attach.
+ // Synchronize it after every successful callback/rotation so all real tool
+ // execution paths receive the credentials that setup and catalog discovery
+ // just proved.
+ await ensureDefaultOrganizationGrant(connection, tx, undefined, {
+ scopes: organizationGrantedScopes.scopes,
+ scopeSource: organizationGrantedScopes.scopeSource,
+ unrequestedScopes: organizationGrantedScopes.unrequestedScopes,
+ requestedScopes: authorizedScopes,
+ });
+ await syncCredentialBindings(connection, [], tx);
+ });
+ emitConnectionUpdated(
+ connection,
+ preCallbackLifecycle,
+ "oauth_callback",
+ );
- githubReadGrantIds: async (companyId: string, connectionId: string, userId: string | null, localTrusted = false): Promise<Array<string | null>> => {
- const { allowed, legacyShared } = await gitHubReadGrantAccess(db, companyId, connectionId, userId, localTrusted);
- return legacyShared ? [null] : allowed.map(grant => grant.id);
- },
+ await checkConnectionHealth(connection.id, input.actor);
+ const refresh = await refreshCatalog(connection.id, input.actor, {
+ enableAllByDefault: shouldFinalizeDefaults,
+ skipDefaultProfileSync: shouldFinalizeDefaults,
+ });
+ const [application] = await db
+ .select()
+ .from(toolApplications)
+ .where(eq(toolApplications.id, connection.applicationId));
+ const suggestedDefaults = galleryEntry
+ ? recommendedDefaultsForApp(
+ galleryEntry,
+ connectionMethodForConnection(galleryEntry, connection).key,
+ )
+ : {
+ access: "all_agents" as const,
+ askFirstRiskLevels: [],
+ };
+ const finished = shouldFinalizeDefaults
+ ? await finishOAuthCatalogWithRecommendedDefaults({
+ interactionId: stateRow.interactionId,
+ connection,
+ catalog: refresh.catalog,
+ suggestedDefaults,
+ actor: input.actor,
+ })
+ : null;
+ return {
+ connectionId: refresh.connection.id,
+ application: toApplication(application),
+ connection: finished?.connection ?? refresh.connection,
+ catalog: refresh.catalog,
+ actions: groupedActions(refresh.catalog),
+ suggestedDefaults,
+ auth: null,
+ };
+ }
- // Server-side reads share the same grant audience and credential lifecycle as discovery.
- githubReadHeaders: async (companyId: string, connectionId: string, userId: string | null, localTrusted = false, forceRefresh = false, grantId?: string | null): Promise<Record<string, string>> => {
- const { connection, allowed, legacyShared } = await gitHubReadGrantAccess(db, companyId, connectionId, userId, localTrusted);
- const actor: ActorInfo = { actorType: "user", actorId: userId ?? "board" };
- if (legacyShared && !grantId) return resolveCredentialHeaders(connection, actor);
- let grant = grantId ? allowed.find(candidate => candidate.id === grantId) : allowed.length === 1 ? allowed[0] : undefined;
- if (!grant) throw forbidden("Choose an active GitHub authorization you can use.");
- if (asRecord(asRecord(connection.config).oauth).connectorProfile === "github.code") {
- grant = await refreshOAuthGrantCredentials({ companyId, connectionId, grantId: grant.id, actor, forceRefresh });
- }
- const ref = grant.credentialSecretRefs.find(ref => ref.configPath === "oauth.access_token" || /authorization|token|api_key/i.test(ref.configPath));
- if (!ref) throw unprocessable("Reconnect GitHub to read repository files.");
- const secret = await resolveOAuthGrantSecret(connection, grant, ref, actor, undefined);
- return { Authorization: `Bearer ${secret.value}` };
- },
+ /**
+ * Finish the one decision that cannot safely be guessed for a browser OAuth
+ * connection: whether the consenting identity stays personal or becomes the
+ * company's shared identity. The provider callback always writes a fresh
+ * token to the consenting user's grant first. Only this explicit endpoint may
+ * promote it to company-scoped secrets.
+ */
+ async function finalizeOAuthAccess(
+ companyId: string,
+ connectionId: string,
+ input: FinalizeOAuthAccess,
+ actor?: ActorInfo,
+ requestingAgentId?: string,
+ ): Promise<FinishToolAppResult> {
+ if (requestingAgentId)
+ await assertAgentsInCompany(companyId, [requestingAgentId]);
+ let connection = await getConnectionRow(connectionId, companyId);
+ const preFinalizeLifecycle = {
+ status: connection.status,
+ enabled: connection.enabled,
+ };
+ if (connection.authKind !== "oauth")
+ throw badRequest("This connection does not use browser sign-in");
+ if (connection.status === "archived")
+ throw conflict("Archived app connections cannot be finished");
+ const actorUserId = actor?.actorType === "user" ? actor.actorId : null;
+ if (!actorUserId)
+ throw badRequest("Finishing browser sign-in requires a signed-in user");
- listGitHubRepositories: async (
- companyId: string,
- userId: string | null,
- localTrusted = false,
- ) => measureRunPhase("connectors.github.catalog", async () => {
- const [connections, grants, members, memberships] = await Promise.all([
- measureRunPhase("connectors.github.connections", () => db
- .select()
- .from(toolConnections)
- .where(
- and(
- eq(toolConnections.companyId, companyId),
- eq(toolConnections.enabled, true),
- ),
- )),
- measureRunPhase("connectors.github.grants", () => db
- .select()
- .from(connectionGrants)
- .where(eq(connectionGrants.companyId, companyId))),
- measureRunPhase("connectors.github.grant_members", () => db
- .select()
- .from(connectionGrantMembers)
- .where(eq(connectionGrantMembers.companyId, companyId))),
- userId
- ? measureRunPhase("connectors.github.membership", () => db
- .select()
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, userId),
- eq(companyMemberships.status, "active"),
- ),
- ))
- : Promise.resolve([]),
- ]);
- const repositories = new Map<
- string,
- import("@paperclipai/shared").ProjectRepository
- >();
- const usableConnections: Array<{ id: string; name: string }> = [];
- let connectionCount = 0;
- let failedConnectionCount = 0;
- for (const connection of connections) {
- if (
- connection.status !== "active" ||
- asRecord(connection.config).sourceTemplateKey !== "github"
+ const [personalGrant] = await db
+ .select()
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.companyId, companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "user"),
+ eq(connectionGrants.subjectUserId, actorUserId),
+ ),
+ )
+ .limit(1);
+
+ if (connection.credentialSource === "vercel_connect") {
+ const [organizationGrant] = await db
+ .select()
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.companyId, companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "organization"),
+ eq(connectionGrants.isDefault, true),
+ ),
)
- continue;
- const connectionGrants = grants.filter(
- (grant) => grant.connectionId === connection.id,
+ .limit(1);
+ const selectedGrant =
+ input.grantKind === "user" ? personalGrant : organizationGrant;
+ if (
+ !selectedGrant ||
+ selectedGrant.status !== "active" ||
+ !selectedGrant.externalCredential
+ ) {
+ throw conflict(
+ "The selected Vercel Connect identity is missing. Authorize this connection again.",
);
- const availableGrants = connectionGrants.filter(
- (grant) =>
- !(
- grant.kind === "organization" &&
- ["per_user", "per_agent"].includes(connection.credentialPolicy)
- ) &&
- canBrowseProjectRepositoryGrant({
- grant,
- userId,
- activeMember: localTrusted || memberships.length > 0,
- audience: members
- .filter((member) => member.grantId === grant.id)
- .map((member) => member.subjectId),
- }),
+ }
+ const expectedPolicy = input.grantKind === "user" ? "per_user" : "shared";
+ if (connection.credentialPolicy !== expectedPolicy) {
+ throw conflict(
+ "Vercel Connect identity scope is fixed when the connector is attached. Create a new connection to change it.",
);
- // Legacy shared PAT connections predate grants. Never fall back when a
- // grant exists but is revoked, private, or outside the caller's audience.
- const legacyShared =
- connectionGrants.length === 0 &&
- connection.credentialPolicy === "shared" &&
- (localTrusted || (!!userId && memberships.length > 0));
- if (!availableGrants.length && !legacyShared) continue;
- connectionCount += 1;
- usableConnections.push({ id: connection.id, name: connection.name });
- const actor: ActorInfo = {
- actorType: "user",
- actorId: userId ?? "board",
- };
- let failed = false;
- for (const initialGrant of legacyShared ? [null] : availableGrants) {
- try {
- let rows: Array<{
- id: string;
- fullName: string;
- private?: boolean;
- }>;
- if (
- initialGrant &&
- asRecord(asRecord(connection.config).oauth).connectorProfile ===
- "github.code"
- ) {
- const grant = await refreshManagedGitHubGrantAccess(
- connection,
- initialGrant,
- actor,
- );
- rows = grant.providerTenant?.github?.repositories ?? [];
- } else {
- const headers = await measureRunPhase("connectors.github.credentials", () => initialGrant
- ? (async () => {
- const ref = initialGrant.credentialSecretRefs.find(
- (ref) =>
- ref.configPath === "oauth.access_token" ||
- /authorization|token|api_key/i.test(ref.configPath),
- );
- if (!ref)
- throw unprocessable(
- "Reconnect GitHub to load repositories",
- );
- const secret = await resolveOAuthGrantSecret(
- connection,
- initialGrant,
- ref,
- actor,
- undefined,
- );
- return { Authorization: `Bearer ${secret.value}` };
- })()
- : resolveCredentialHeaders(connection, actor));
- rows = await measureRunPhase("connectors.github.repositories", () => loadGitHubTokenRepositories(headers));
- }
- for (const row of rows) {
- mergeProjectRepository(repositories, row, connection.name, connection.id);
- }
- } catch {
- // Credential/provider errors may contain secrets. Only expose an
- // aggregate failure; successful connections remain usable.
- failed = true;
- }
- }
- if (failed) failedConnectionCount += 1;
}
- return {
- repositories: [...repositories.values()].sort((a, b) =>
- a.fullName.localeCompare(b.fullName),
- ),
- connections: usableConnections,
- connectionCount,
- failedConnectionCount,
- };
- }),
-
- listConnections: async (
- companyId: string,
- viewerUserId?: string,
- ): Promise<ToolConnection[]> => {
- const rows = await db
- .select()
- .from(toolConnections)
- .where(eq(toolConnections.companyId, companyId))
- .orderBy(desc(toolConnections.updatedAt));
- const connections = rows.map(toConnection);
- if (connections.length === 0) return connections;
- const installRows = await db
- .select()
- .from(toolConnectionInstalls)
- .where(eq(toolConnectionInstalls.companyId, companyId))
- .orderBy(
- asc(toolConnectionInstalls.targetType),
- asc(toolConnectionInstalls.targetId),
+ } else if (input.grantKind === "user") {
+ if (
+ !personalGrant ||
+ personalGrant.status !== "active" ||
+ personalGrant.credentialSecretRefs.length === 0
+ ) {
+ throw conflict(
+ "Your connected identity is missing. Connect this app again before choosing Just me.",
+ );
+ }
+ if (
+ connection.credentialPolicy === "shared" &&
+ connection.credentialSecretRefs.length > 0
+ ) {
+ throw conflict("This connection already uses a company identity");
+ }
+ [connection] = await db
+ .update(toolConnections)
+ .set({
+ credentialPolicy: "per_user",
+ credentialRefs: connection.credentialRefs.filter(
+ (ref) => ref.name !== "oauth.access_token",
+ ),
+ credentialSecretRefs: connection.credentialSecretRefs.filter(
+ (ref) =>
+ ref.configPath !== "oauth.access_token" &&
+ ref.configPath !== "oauth.refresh_token",
+ ),
+ status: "active",
+ enabled: true,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(toolConnections.id, connection.id),
+ eq(toolConnections.companyId, companyId),
+ ),
+ )
+ .returning();
+ await syncCredentialBindings(
+ connection,
+ personalGrant.credentialSecretRefs,
+ );
+ } else if (
+ connection.credentialPolicy !== "shared" ||
+ connection.credentialSecretRefs.length === 0
+ ) {
+ if (
+ !personalGrant ||
+ personalGrant.status !== "active" ||
+ personalGrant.credentialSecretRefs.length === 0
+ ) {
+ throw conflict(
+ "Your connected identity is missing. Connect this app again before sharing it.",
);
- const installsByConnection = new Map<string, ToolConnectionInstall[]>();
- for (const row of installRows) {
- const installs = installsByConnection.get(row.connectionId) ?? [];
- installs.push(toConnectionInstall(row));
- installsByConnection.set(row.connectionId, installs);
}
- for (const connection of connections)
- connection.installs = installsByConnection.get(connection.id) ?? [];
- // Enrich with "last used" = most recent tool-call event per connection so the
- // prosumer Apps list can surface a staleness signal without an N+1 fan-out.
- const lastUsedRows = await db
+
+ const personalSecretIds = personalGrant.credentialSecretRefs.map(
+ (ref) => ref.secretId,
+ );
+ const personalSecretRows = await db
.select({
- connectionId: toolCallEvents.connectionId,
- lastUsedAt: max(toolCallEvents.createdAt),
+ id: companySecrets.id,
+ scope: companySecrets.scope,
+ ownerUserId: companySecrets.ownerUserId,
+ userSecretDefinitionId: companySecrets.userSecretDefinitionId,
})
- .from(toolCallEvents)
+ .from(companySecrets)
.where(
and(
- eq(toolCallEvents.companyId, companyId),
- inArray(
- toolCallEvents.connectionId,
- connections.map((connection) => connection.id),
- ),
+ eq(companySecrets.companyId, companyId),
+ inArray(companySecrets.id, personalSecretIds),
+ ),
+ );
+ const personalSecretById = new Map(
+ personalSecretRows.map((row) => [row.id, row]),
+ );
+ const promotedRefs: ToolCredentialSecretRef[] = [];
+ try {
+ for (const ref of personalGrant.credentialSecretRefs) {
+ const secretRow = personalSecretById.get(ref.secretId);
+ if (
+ !secretRow ||
+ secretRow.scope !== "user" ||
+ secretRow.ownerUserId !== actorUserId ||
+ !secretRow.userSecretDefinitionId
+ ) {
+ throw forbidden(
+ "Only your own connected identity can be shared with the company",
+ );
+ }
+ if (
+ ref.configPath !== "oauth.access_token" &&
+ ref.configPath !== "oauth.refresh_token" &&
+ ref.configPath !== "oauth.client_secret"
+ ) {
+ throw badRequest(
+ "The connected identity contains an unsupported OAuth credential",
+ );
+ }
+ const resolved = await secrets.resolveUserSecretValue(
+ companyId,
+ {
+ definitionId: secretRow.userSecretDefinitionId,
+ responsibleUserId: actorUserId,
+ version: ref.versionSelector ?? "latest",
+ },
+ {
+ consumerType: "tool_connection",
+ consumerId: connection.id,
+ responsibleUserId: actorUserId,
+ actorType: "user",
+ actorId: actorUserId,
+ },
+ );
+ if (!resolved)
+ throw unprocessable("The connected identity could not be read");
+ const promoted = await createOrRotateOAuthSecret({
+ companyId,
+ connection,
+ configPath: ref.configPath,
+ label: ref.label ?? "OAuth credential",
+ value: resolved.value,
+ actor,
+ existingRefs: promotedRefs,
+ });
+ promotedRefs.push({ ...ref, ...promoted });
+ }
+
+ const accessRef = promotedRefs.find(
+ (ref) => ref.configPath === "oauth.access_token",
+ );
+ if (!accessRef)
+ throw unprocessable(
+ "The connected identity is missing its OAuth access token",
+ );
+ const connectionCredentialSecretRefs = [
+ ...connection.credentialSecretRefs.filter(
+ (ref) =>
+ ref.configPath !== "oauth.access_token" &&
+ ref.configPath !== "oauth.refresh_token",
+ ),
+ ...promotedRefs,
+ ];
+ const nowAt = new Date();
+ await db.transaction(async (tx) => {
+ await tx.select({ id: connectionGrants.id }).from(connectionGrants)
+ .where(and(eq(connectionGrants.companyId, companyId), eq(connectionGrants.connectionId, connection.id),
+ or(eq(connectionGrants.id, personalGrant.id), and(eq(connectionGrants.kind, "organization"), eq(connectionGrants.isDefault, true)))))
+ .orderBy(connectionGrants.id).for("update");
+ await tx.select({ id: toolApplications.id }).from(toolApplications)
+ .where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, companyId)))
+ .for("update");
+ await tx.select({ id: toolConnections.id }).from(toolConnections)
+ .where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId)))
+ .for("update");
+ const [existingOrganizationGrant] = await tx
+ .select()
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.companyId, companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "organization"),
+ eq(connectionGrants.isDefault, true),
+ ),
+ )
+ .limit(1);
+ let organizationGrantId: string;
+ if (existingOrganizationGrant) {
+ organizationGrantId = existingOrganizationGrant.id;
+ await tx
+ .update(connectionGrants)
+ .set({
+ providerTenant: personalGrant.providerTenant,
+ credentialSecretRefs: connectionCredentialSecretRefs,
+ status: "active",
+ revokedAt: null,
+ revokedByAgentId: null,
+ revokedByUserId: null,
+ updatedAt: nowAt,
+ })
+ .where(eq(connectionGrants.id, existingOrganizationGrant.id));
+ } else {
+ const [createdOrganizationGrant] = await tx
+ .insert(connectionGrants)
+ .values({
+ companyId,
+ connectionId: connection.id,
+ kind: "organization",
+ subjectUserId: null,
+ providerTenant: personalGrant.providerTenant,
+ credentialSecretRefs: connectionCredentialSecretRefs,
+ status: "active",
+ isDefault: true,
+ createdByUserId: actorUserId,
+ })
+ .returning({ id: connectionGrants.id });
+ organizationGrantId = createdOrganizationGrant.id;
+ }
+ // Empty audience rows are the canonical "everyone in the company".
+ await tx
+ .delete(connectionGrantMembers)
+ .where(
+ and(
+ eq(connectionGrantMembers.companyId, companyId),
+ eq(connectionGrantMembers.grantId, organizationGrantId),
+ ),
+ );
+ await tx
+ .delete(connectionGrantDelegations)
+ .where(
+ and(
+ eq(connectionGrantDelegations.companyId, companyId),
+ eq(connectionGrantDelegations.grantId, personalGrant.id),
+ ),
+ );
+ await tx
+ .update(connectionGrants)
+ .set({
+ credentialSecretRefs: [],
+ status: "revoked",
+ revokedAt: nowAt,
+ revokedByUserId: actorUserId,
+ updatedAt: nowAt,
+ })
+ .where(eq(connectionGrants.id, personalGrant.id));
+ [connection] = await tx
+ .update(toolConnections)
+ .set({
+ credentialPolicy: "shared",
+ credentialSecretRefs: connectionCredentialSecretRefs,
+ credentialRefs: [
+ {
+ name: "oauth.access_token",
+ secretId: accessRef.secretId,
+ version: "latest",
+ placement: "header",
+ key: "Authorization",
+ prefix: "Bearer ",
+ },
+ ],
+ status: "active",
+ enabled: true,
+ updatedAt: nowAt,
+ })
+ .where(
+ and(
+ eq(toolConnections.id, connection.id),
+ eq(toolConnections.companyId, companyId),
+ ),
+ )
+ .returning();
+ });
+ } catch (error) {
+ await Promise.all(
+ promotedRefs.map((ref) =>
+ secrets.remove(ref.secretId).catch(() => undefined),
),
+ );
+ throw error;
+ }
+ await syncCredentialBindings(connection);
+ // The source values are no longer referenced by either grant or
+ // connection. Removing them makes the promotion a move, not a copy.
+ for (const secretId of personalSecretIds) await secrets.remove(secretId);
+ }
+
+ // Both identity branches above commit their own lifecycle write (draft ->
+ // active) before `finishGalleryAppConnection` re-reads the row, so that
+ // step alone would never observe this transition. This is the OAuth
+ // access-finalization step of the same gallery setup flow (Apps and inline
+ // task cards both reach it), hence `gallery`.
+ emitConnectionUpdated(connection, preFinalizeLifecycle, "gallery");
+ const catalog = await db
+ .select()
+ .from(toolCatalogEntries)
+ .where(
+ and(
+ eq(toolCatalogEntries.companyId, companyId),
+ eq(toolCatalogEntries.connectionId, connection.id),
+ eq(toolCatalogEntries.status, "active"),
+ ),
+ );
+ const sourceTemplateKey =
+ typeof connection.config.sourceTemplateKey === "string"
+ ? connection.config.sourceTemplateKey
+ : null;
+ const galleryEntry = sourceTemplateKey
+ ? getConnectableAppDefinition(sourceTemplateKey)
+ : null;
+ const defaults = galleryEntry
+ ? recommendedDefaultsForApp(
+ galleryEntry,
+ connectionMethodForConnection(galleryEntry, connection).key,
)
- .groupBy(toolCallEvents.connectionId);
- const lastUsedByConnection = new Map(
- lastUsedRows.map((row) => [row.connectionId, row.lastUsedAt]),
+ : { askFirstRiskLevels: [] };
+ const askFirstRiskLevels = new Set(
+ Array.isArray(defaults.askFirstRiskLevels)
+ ? defaults.askFirstRiskLevels.filter(
+ (value): value is string => typeof value === "string",
+ )
+ : [],
+ );
+ const finished = await finishGalleryAppConnection(
+ companyId,
+ connection.id,
+ {
+ enabledCatalogEntryIds: catalog.map((entry) => entry.id),
+ askFirstCatalogEntryIds: catalog
+ .filter((entry) => askFirstRiskLevels.has(entry.riskLevel))
+ .map((entry) => entry.id),
+ access: requestingAgentId
+ ? { agentIds: [requestingAgentId] }
+ : "all_agents",
+ preserveExistingAccess: Boolean(requestingAgentId),
+ },
+ actor,
+ );
+ await db
+ .insert(toolConnectionInstalls)
+ .values({
+ companyId,
+ connectionId: connection.id,
+ targetType: requestingAgentId ? "agent" : "company",
+ targetId: requestingAgentId ?? companyId,
+ createdByUserId: actorUserId,
+ })
+ .onConflictDoNothing();
+ return finished;
+ }
+
+ async function preflightGalleryAppMetadata(
+ galleryKey: string,
+ methodKey?: string | null,
+ ): Promise<ToolAppMetadataPreflightResult> {
+ const app = getConnectableAppDefinition(galleryKey);
+ if (!app || app.availability?.available === false)
+ throw notFound("App not found");
+ const method = connectionMethodFor(app, methodKey);
+ await assertExperimentalConnectorSetupEnabled(app.slug);
+ if (method.transport !== "mcp_remote" || !method.defaults?.serverUrl) {
+ throw unprocessable(
+ "This app method does not use a hosted remote MCP endpoint",
);
- for (const connection of connections) {
- connection.lastUsedAt = lastUsedByConnection.get(connection.id) ?? null;
- }
- await annotateAiGrantHealth(connections);
- await annotateGitHubAuthorization(connections, viewerUserId);
- await annotateSavedOAuthClientSecret(connections, viewerUserId);
- return connections;
+ }
+
+ const serverUrl = await assertRemoteHttpUrlAllowed(
+ method.defaults.serverUrl,
+ );
+ return preflightConnectionMetadata(app, method, method.defaults, serverUrl, () => options.now?.() ?? new Date());
+ }
+
+ return {
+ /** Identity-only verification: no bot installation/repository access required. */
+ verifyPersonalGitHubIdentity: async (companyId: string, connectionId: string, userId: string) => {
+ const [connection] = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, companyId), eq(toolConnections.id, connectionId), eq(toolConnections.enabled, true)));
+ if (!connection || (connection.config.sourceTemplateKey !== "github" && connection.transportConfig?.sourceTemplateKey !== "github")) throw notFound("GitHub connection not found");
+ const [ownGrant] = await db.select().from(connectionGrants).where(and(eq(connectionGrants.companyId, companyId), eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.kind, "user"), eq(connectionGrants.subjectUserId, userId), eq(connectionGrants.status, "active")));
+ if (!ownGrant) throw forbidden("Connect your own GitHub account first. Shared and agent connections cannot prove your identity.");
+ const actor = { actorType: "user" as const, actorId: userId };
+ const grant = await refreshOAuthGrantCredentials({ companyId, connectionId, grantId: ownGrant.id, actor });
+ const accessRef = grant.credentialSecretRefs.find(ref => ref.configPath === "oauth.access_token");
+ if (!accessRef) throw unprocessable("Reconnect your personal GitHub connection");
+ const { value } = await resolveOAuthGrantSecret(connection, grant, accessRef, actor, undefined);
+ const identity = await githubBotRequest<{ id?: number; login?: string; avatar_url?: string }>(fetch, value, "/user");
+ if (!Number.isSafeInteger(identity.id) || !identity.id || !identity.login || !/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}$/.test(identity.login)) throw unprocessable("GitHub returned an invalid account identity");
+ const [current] = await db.select({ id: connectionGrants.id }).from(connectionGrants).where(and(eq(connectionGrants.id, grant.id), eq(connectionGrants.companyId, companyId), eq(connectionGrants.subjectUserId, userId), eq(connectionGrants.status, "active")));
+ if (!current) throw forbidden("Your GitHub connection was revoked. Connect it again.");
+ return { githubUserId: String(identity.id), login: identity.login, avatarUrl: identity.avatar_url ?? null, connectionId, grantId: grant.id };
+ },
+ preflightGalleryAppMetadata,
+ approvedStdioTemplates: async (
+ companyId: string,
+ ): Promise<ToolStdioCommandTemplate[]> => {
+ const adminTemplates = await db
+ .select()
+ .from(toolStdioCommandTemplates)
+ .where(eq(toolStdioCommandTemplates.companyId, companyId))
+ .orderBy(asc(toolStdioCommandTemplates.templateKey));
+ return [
+ ...Object.keys(APPROVED_STDIO_TEMPLATES)
+ .sort()
+ .map((templateId) => builtInStdioTemplate(templateId)!),
+ ...adminTemplates.map(toStdioCommandTemplate),
+ ];
},
- createConnection: async (
+ createStdioCommandTemplate: async (
companyId: string,
- input: CreateToolConnection,
+ input: CreateToolStdioCommandTemplate,
actor?: ActorInfo,
- ): Promise<ToolConnection> => {
- let applicationId = input.applicationId;
- let applicationNamespace = input.applicationName ?? input.name;
- const transport = input.transport;
- if (!transport) throw badRequest("Tool connection transport is required");
- const config = normalizeGoogleSheetsConnectionConfig(
- input.config ?? input.transportConfig ?? {},
- );
- await assertConnectorConnectionSetupEnabled({ config, applicationId, companyId });
- // Validate company-scoped references before touching a caller-supplied
- // network endpoint. Besides failing fast, this keeps cross-company
- // authorization errors from being masked by DNS or SSRF validation.
- await assertSecretRefs(companyId, [
- ...(input.credentialRefs ?? []),
- ...(input.credentialSecretRefs ?? []),
- ]);
- if (transport === "mcp_remote")
- await assertRemoteConnectionEndpointsAllowed(config);
- if (transport === "local_stdio") await stdioTemplateId(companyId, config);
- assertLocalStdioCanBeEnabled(transport, input.enabled ?? false, config);
- await assertGoogleSheetsSpreadsheetOwnership(companyId, config);
- if (applicationId) {
- const app = await assertApplication(companyId, applicationId);
- applicationNamespace = app.applicationKey ?? app.name;
- await assertConnectorConnectionSetupEnabled({ config }, applicationNamespace);
- if (
- (transport === "mcp_remote" && app.type !== "mcp_http") ||
- (transport === "local_stdio" && app.type !== "mcp_stdio")
- ) {
- throw unprocessable(
- "Connection transport must match application type",
- );
- }
- } else {
- const [app] = await db
- .insert(toolApplications)
- .values({
- companyId,
- applicationKey: normalizeKey(input.applicationName ?? input.name),
- name: input.applicationName ?? input.name,
- type: isBrowserUseConnection({ transport, config }) || isDaytonaConnection({ transport, config }) ? "rest_api" : transport === "mcp_remote" ? "mcp_http" : "mcp_stdio",
- status: "active",
- metadata: {},
- })
- .returning();
- applicationId = app.id;
+ ): Promise<ToolStdioCommandTemplate> => {
+ if (builtInStdioTemplate(input.templateId)) {
+ throw conflict(
+ "A built-in stdio template already uses this templateId",
+ );
}
- const connectionId = randomUUID();
- const binding = actorBinding(actor);
+ const existing = await getAdminStdioTemplate(companyId, input.templateId);
+ if (existing)
+ throw conflict("A stdio command template already uses this templateId");
+ const tools = input.tools
+ .map((tool) => normalizeToolDescriptor(tool))
+ .filter((tool): tool is McpToolDescriptor => Boolean(tool));
const [row] = await db
- .insert(toolConnections)
+ .insert(toolStdioCommandTemplates)
.values({
- id: connectionId,
companyId,
- applicationId,
+ templateKey: input.templateId,
name: input.name,
- uid: connectionUid(applicationNamespace, input.name, connectionId),
- connectionKind: input.connectionKind ?? "managed",
- ownership: input.ownership ?? "customer",
- transport,
- authKind: input.authKind ?? "none",
- credentialPolicy:
- input.credentialPolicy ??
- (input.authKind === "oauth" ? "per_user" : "shared"),
- status: input.status ?? "draft",
- enabled: input.enabled ?? false,
- agentInstructions: input.agentInstructions !== undefined ? input.agentInstructions : defaultConnectionAgentInstructions(
- typeof config.sourceTemplateKey === "string" ? getConnectableAppDefinition(config.sourceTemplateKey)?.agentInstructions : null,
- ),
- config,
- transportConfig: isGoogleSheetsConnectionConfig(config)
- ? config
- : (input.transportConfig ?? config),
- credentialRefs: input.credentialRefs ?? [],
- credentialSecretRefs: input.credentialSecretRefs ?? [],
+ description: input.description ?? null,
+ status: "active",
+ command: input.command,
+ args: input.args,
+ envKeys: input.envKeys,
+ tools,
createdByAgentId:
- binding.actorType === "agent" ? binding.actorId : null,
+ actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
createdByUserId:
- binding.actorType === "user" ? binding.actorId : null,
- })
- .returning();
- await ensureDefaultOrganizationGrant(row);
- await syncCredentialBindings(row);
- await ensureRuntimeSlot(row);
- emitConnectionCreated(row, "api");
- return toConnection(row);
- },
-
- getConnection: async (
- connectionId: string,
- companyId?: string,
- viewerUserId?: string,
- ): Promise<ToolConnection> => {
- const connection = toConnection(
- await getConnectionRow(connectionId, companyId),
- );
- connection.installs = await listConnectionInstalls(
- connection.id,
- connection.companyId,
- );
- await annotateAiGrantHealth([connection]);
- await annotateGitHubAuthorization([connection], viewerUserId);
- await annotateSavedOAuthClientSecret([connection], viewerUserId);
- return connection;
+ actor?.actorType === "user" ? (actor.actorId ?? null) : null,
+ })
+ .returning();
+ return toStdioCommandTemplate(row);
},
- listConnectionGrants: async (idOrUid: string, companyId?: string) => {
- const connection = await getConnectionRow(idOrUid, companyId);
- const grants = await db
- .select()
- .from(connectionGrants)
+ disableStdioCommandTemplate: async (
+ companyId: string,
+ templateId: string,
+ ): Promise<ToolStdioCommandTemplate> => {
+ if (builtInStdioTemplate(templateId))
+ throw unprocessable("Built-in stdio templates cannot be disabled");
+ const existing = await getAdminStdioTemplate(companyId, templateId);
+ if (!existing) throw notFound("Stdio command template not found");
+ if (existing.status === "disabled")
+ return toStdioCommandTemplate(existing);
+ const at = now();
+ const [row] = await db
+ .update(toolStdioCommandTemplates)
+ .set({ status: "disabled", disabledAt: at, updatedAt: at })
.where(
and(
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
+ eq(toolStdioCommandTemplates.companyId, companyId),
+ eq(toolStdioCommandTemplates.templateKey, templateId),
),
)
- .orderBy(
- desc(connectionGrants.isDefault),
- desc(connectionGrants.updatedAt),
- );
- const grantIds = grants.map((grant) => grant.id);
- const [members, delegations] =
- grantIds.length === 0
- ? [[], []]
- : await Promise.all([
- db
- .select()
- .from(connectionGrantMembers)
- .where(
- and(
- eq(connectionGrantMembers.companyId, connection.companyId),
- inArray(connectionGrantMembers.grantId, grantIds),
- ),
- ),
- db
- .select()
- .from(connectionGrantDelegations)
- .where(
- and(
- eq(
- connectionGrantDelegations.companyId,
- connection.companyId,
- ),
- inArray(connectionGrantDelegations.grantId, grantIds),
- ),
- ),
- ]);
- return {
- connection: { id: connection.id, uid: connection.uid },
- grants: grants.map((grant) => ({
- ...toConnectionGrant(grant),
- members: members.filter((member) => member.grantId === grant.id),
- delegations: delegations.filter(
- (delegation) => delegation.grantId === grant.id,
- ),
- })),
- };
+ .returning();
+ return toStdioCommandTemplate(row);
},
- /**
- * Company members eligible to appear in an organization grant's audience.
- * The audience editor needs display names, and the client must not have to
- * cross-reference a second endpoint to render "12 selected members".
- */
- listConnectionAudienceMembers: async (companyId: string) => {
- const rows = await db
- .select({
- userId: companyMemberships.principalId,
- name: authUsers.name,
- email: authUsers.email,
- })
- .from(companyMemberships)
- .leftJoin(authUsers, eq(authUsers.id, companyMemberships.principalId))
- .where(
- and(
- eq(companyMemberships.companyId, companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.status, "active"),
- ),
- );
- return rows
- .map((row) => ({
- userId: row.userId,
- name: row.name ?? null,
- email: row.email ?? null,
- }))
- .sort((a, b) =>
- (a.name ?? a.email ?? a.userId).localeCompare(
- b.name ?? b.email ?? b.userId,
- ),
+ async setupComposioApp(connectionId: string, toolkit: string, input: ComposioAppSetupInput, actor: ActorInfo): Promise<ComposioAppSetupResult> {
+ if (!findComposioCatalogApp(toolkit)) throw notFound("This Composio app is not in the catalog");
+ const { connection, manage } = await openComposioGateway(connectionId, actor);
+ let result = composioAppSetupResult(await manage([{ name: toolkit, action: "list" }]), toolkit);
+ if (input.action === "start" && result.status !== "connected") {
+ result = composioAppSetupResult(await manage([{ name: toolkit, action: "add" }]), toolkit);
+ if (result.status === "not_connected") throw unprocessable("Composio did not return a sign-in link for this app. Manage it in Composio to check its setup requirements.");
+ }
+ if (input.action === "complete") {
+ if (result.status !== "connected") throw conflict("Finish connecting this app in Composio, then check again");
+ const currentConnection = await getConnectionRow(connectionId);
+ if (currentConnection.status !== "active" || !currentConnection.enabled) {
+ throw conflict("The gateway is no longer active. Restore it before connecting this app.");
+ }
+ }
+ await audit({ companyId: connection.companyId, connectionId, action: "tool_connection.upstream_app_setup", outcome: "success", actor,
+ details: { toolkit, action: input.action, status: result.status } });
+ return result;
+ },
+
+ listAggregatorApps: async (connectionId: string, actor: ActorInfo) => aggregatorAppsResponse(await getConnectionRow(connectionId), actor),
+ syncAggregatorApps,
+ refreshAggregatorApps: async (connectionId: string, requested: string[], actor: ActorInfo) => {
+ const connection = await getConnectionRow(connectionId);
+ if (aggregatorProvider(connection) === "composio" && requested.length) {
+ const { manage } = await openComposioGateway(connectionId, actor);
+ if (requested.some(toolkit => !findComposioCatalogApp(toolkit))) throw notFound("This Composio app is not in the catalog");
+ await manage(requested.map(name => ({ name, action: "list" })));
+ return aggregatorAppsResponse(connection, actor);
+ }
+ return syncAggregatorApps(connectionId, true, actor);
+ },
+ configureArcadeDiscovery,
+ syncComposioApps: startComposioAppSync,
+
+ async listComposioApps(connectionId: string, actor: ActorInfo) {
+ const connection = await getConnectionRow(connectionId);
+ if (actor.actorType !== "user" || !actor.actorId) throw forbidden("Board access required");
+ if (connection.config.sourceTemplateKey !== "composio") throw notFound("Composio gateway not found");
+ return composioAppsResponse(connection, actor);
+ },
+
+ async refreshComposioApps(connectionId: string, requested: string[], actor: ActorInfo) {
+ if (requested.some(toolkit => !findComposioCatalogApp(toolkit))) throw notFound("This Composio app is not in the catalog");
+ const { connection, manage } = await openComposioGateway(connectionId, actor);
+ const existing = await cachedComposioApps(connection, actor);
+ // Migrate observations from the original direct setup flow on the first visit.
+ const history = await db.select({ details: toolAccessAuditEvents.details }).from(toolAccessAuditEvents).where(and(
+ eq(toolAccessAuditEvents.companyId, connection.companyId), eq(toolAccessAuditEvents.connectionId, connectionId),
+ eq(toolAccessAuditEvents.actorId, actor.actorId!), eq(toolAccessAuditEvents.action, "tool_connection.upstream_app_setup"),
+ )).orderBy(desc(toolAccessAuditEvents.createdAt)).limit(128);
+ const known = [...existing.filter(app => app.accounts.length > 0).map(app => app.toolkit),
+ ...history.map(row => row.details.toolkit).filter((toolkit): toolkit is string => typeof toolkit === "string" && Boolean(findComposioCatalogApp(toolkit)))];
+ const toolkits = [...new Set([...requested, ...known])];
+ for (let start = 0; start < toolkits.length; start += 32) {
+ await manage(toolkits.slice(start, start + 32).map(name => ({ name, action: "list" })));
+ }
+ return composioAppsResponse(connection, actor);
+ },
+
+ async manageComposioAppAccount(connectionId: string, toolkit: string, input: ComposioAppAccountInput, actor: ActorInfo) {
+ if (!findComposioCatalogApp(toolkit)) throw notFound("This Composio app is not in the catalog");
+ const { connection, manage } = await openComposioGateway(connectionId, actor);
+ if (input.action !== "add") {
+ const before = composioAppAccounts(await manage([{ name: toolkit, action: "list" }]), toolkit);
+ if (!before?.some(account => account.id === input.accountId)) throw notFound("This account is no longer available in the selected Composio app");
+ }
+ const details = { toolkit, ...(input.action !== "add" ? { accountId: input.accountId } : {}) };
+ await logActivity(db, { companyId: connection.companyId, actorType: "user", actorId: actor.actorId!,
+ action: `tool_connection.upstream_account_${input.action}_requested`, entityType: "tool_connection", entityId: connectionId, details });
+ let payload: unknown;
+ try {
+ payload = await manage([{ name: toolkit, action: input.action,
+ ...(input.action !== "add" ? { account_id: input.accountId } : {}), ...(input.action === "rename" ? { alias: input.alias } : {}) }]);
+ } catch (error) {
+ await audit({ companyId: connection.companyId, connectionId, actor, action: `tool_connection.upstream_account_${input.action}`,
+ outcome: "failure", reasonCode: "provider_unconfirmed", details });
+ throw error;
+ }
+ const result = composioAppSetupResult(payload, toolkit); // Reject provider errors before reporting success.
+ if (input.action === "add" && !result.authorizationUrl) throw unprocessable("Composio did not return a sign-in link. Check the app in Composio.");
+ if (input.action !== "add") {
+ const after = composioAppAccounts(await manage([{ name: toolkit, action: "list" }]), toolkit);
+ if (!after || (input.action === "remove" ? after.some(account => account.id === input.accountId)
+ : !after.some(account => account.id === input.accountId && account.alias === input.alias))) {
+ throw conflict("Composio has not confirmed this change. Refresh the accounts before trying again.");
+ }
+ }
+ await logActivity(db, { companyId: connection.companyId, actorType: "user", actorId: actor.actorId!,
+ action: `tool_connection.upstream_account_${input.action}`, entityType: "tool_connection", entityId: connectionId,
+ details: { toolkit, ...(input.action !== "add" ? { accountId: input.accountId } : {}) } });
+ return { ...result, apps: await cachedComposioApps(connection, actor) };
+ },
+
+ connectGalleryApp,
+
+ finishGalleryAppConnection,
+
+ reconnectGalleryApp,
+
+ storeConnectorOAuthSecret: createOrRotateOAuthSecret,
+ resolveConnectorOAuthGrantSecret: resolveOAuthGrantSecret,
+ startOAuth,
+
+ startAuthorizationForAgent: async (input: {
+ companyId: string;
+ connectionId: string;
+ agentId: string;
+ runId: string;
+ subjectUserId: string;
+ scopes?: string[];
+ returnTo?: string;
+ redirectUri: string;
+ }) => {
+ const runContext = await loadBrokerRunContext(input);
+ const connection = await getConnectionRow(
+ input.connectionId,
+ input.companyId,
+ );
+ if (
+ !runContext.responsibleUserId ||
+ runContext.responsibleUserId !== input.subjectUserId
+ ) {
+ throw new HttpError(
+ 403,
+ "The agent run cannot start authorization for the requested user",
+ {
+ code: "subject_not_permitted",
+ connection: { uid: connection.uid },
+ subject: { type: "user", userId: input.subjectUserId },
+ },
);
+ }
+ return startOAuth(input.companyId, connection.id, {
+ redirectUri: input.redirectUri,
+ actor: { actorType: "agent", actorId: input.agentId },
+ subjectUserId: input.subjectUserId,
+ scopes: input.scopes,
+ returnTo: input.returnTo,
+ issueId: runContext.issueId ?? undefined,
+ });
+ },
+
+ peekOAuthState,
+
+ completePaperclipCloudConnectorCallback,
+
+ completeVercelConnectCallback,
+
+ completeOAuthCallback,
+ refreshOAuthGrantCredentials,
+ finalizeOAuthAccess,
+
+ listExamples: async (companyId: string): Promise<ToolExampleSummary[]> => {
+ return Promise.all(
+ TOOL_EXAMPLES.map(async (definition) => {
+ const rows = await exampleRows(companyId, definition);
+ return exampleSummary(definition, rows);
+ }),
+ );
},
- /**
- * Replace an organization grant's audience atomically (PAP-17835).
- *
- * An empty `memberUserIds` persists as zero rows, which the resolver already
- * treats as "every organization member". Replacement is delete-then-insert
- * inside one transaction so a partially-applied audience can never widen or
- * narrow access, and every member id is checked against active company
- * membership first so an audience cannot name an outsider. Existing audience
- * members are locked too: membership cleanup deliberately retains a sole
- * inactive audience row, and a concurrent empty replacement must not erase
- * that fail-closed marker after cleanup wins. Once cleanup has retained that
- * marker, callers must restore the member or replace it with an active named
- * audience before widening access to the whole company.
- */
- replaceConnectionGrantMembers: async (
- idOrUid: string,
- grantId: string,
- memberUserIds: string[],
+ installExample: async (
+ companyId: string,
+ exampleId: string,
actor?: ActorInfo,
- ) => {
- const connection = await getConnectionRow(idOrUid);
- const [grant] = await db
- .select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.id, grantId),
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
- ),
- )
- .limit(1);
- if (!grant) throw notFound("Connection grant not found");
- if (grant.kind !== "organization") {
- throw badRequest(
- "Only an organization identity has an audience; a personal identity belongs to its owner",
- );
- }
- const requested = [
- ...new Set(memberUserIds.map((id) => id.trim()).filter(Boolean)),
- ];
- const binding = actorBinding(actor);
- const members = await db.transaction(async (tx) => {
- // Serialize replacements before taking the current audience snapshot.
- // Otherwise a second replacement could read the old rows, wait behind
- // an in-flight replacement, and then miss locking a newly-added member.
- await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${"paperclip.connection_grant_audience:" + grant.id}, 0))`);
- const existingAudience = await tx
- .select()
- .from(connectionGrantMembers)
- .where(
- and(
- eq(connectionGrantMembers.companyId, connection.companyId),
- eq(connectionGrantMembers.grantId, grant.id),
- eq(connectionGrantMembers.subjectType, "user"),
- ),
- );
- const existingUserIds = [
- ...new Set(existingAudience.map((row) => row.subjectId)),
- ];
- const membershipUserIds = [
- ...new Set([...existingUserIds, ...requested]),
- ];
- if (membershipUserIds.length > 0) {
- // Membership suspension/archive/removal takes the same row lock before
- // sweeping grant audiences. Lock both the old and new audience so an
- // empty replacement also serializes with cleanup of its existing sole
- // member. Whichever transaction wins is then authoritative.
- const memberships = await tx
- .select({
- principalId: companyMemberships.principalId,
- status: companyMemberships.status,
- })
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, connection.companyId),
- eq(companyMemberships.principalType, "user"),
- inArray(companyMemberships.principalId, membershipUserIds),
- ),
- )
- .orderBy(asc(companyMemberships.id))
- .for("update");
- const active = new Set(
- memberships
- .filter((row) => row.status === "active")
- .map((row) => row.principalId),
- );
- const unknown = requested.filter((id) => !active.has(id));
- if (unknown.length > 0) {
- throw unprocessable(
- "Every audience member must be an active member of this company",
- {
- code: "audience_member_not_in_company",
- unknownUserIds: unknown,
- },
- );
- }
- const inactiveExisting = existingUserIds.filter(
- (id) => !active.has(id),
- );
- if (requested.length === 0 && inactiveExisting.length > 0) {
- throw conflict(
- "Replace inactive audience members before widening access to the whole company",
- {
- code: "audience_widening_blocked",
- inactiveUserIds: inactiveExisting,
- },
- );
- }
- }
- await tx
- .select({ id: connectionGrants.id })
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.id, grant.id),
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
- ),
- )
- .for("update");
- const existingUserSet = new Set(existingUserIds);
- if (requested.length === existingUserSet.size && requested.every(id => existingUserSet.has(id))) return existingAudience;
- await tx
- .delete(connectionGrantMembers)
+ ): Promise<ToolExampleInstallResult> => {
+ const definition = findExample(exampleId);
+ const blocker = localStdioInstallBlocker();
+ if (blocker) throw unprocessable(blocker);
+ assertLocalStdioCanBeEnabled("local_stdio", true);
+ await stdioTemplateId(companyId, { templateId: definition.templateId });
+ const before = await exampleRows(companyId, definition);
+ const application = await upsertExampleApplication(
+ companyId,
+ definition,
+ before.application,
+ );
+ const connection = await upsertExampleConnection(
+ companyId,
+ definition,
+ application.row.id,
+ before.connection,
+ );
+ const refresh = await refreshCatalog(connection.row.id, actor);
+ let catalog = refresh.catalog;
+ const safeReadEntryIds = catalog
+ .filter((entry) => entry.riskLevel === "read")
+ .map((entry) => entry.id);
+ if (safeReadEntryIds.length > 0) {
+ const reviewedAt = new Date();
+ await db
+ .update(toolCatalogEntries)
+ .set({
+ status: "active",
+ reviewedAt,
+ reviewedByAgentId:
+ actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
+ reviewedByUserId:
+ actor?.actorType === "user" ? (actor.actorId ?? null) : null,
+ quarantinedAt: null,
+ quarantineReason: null,
+ updatedAt: reviewedAt,
+ })
.where(
and(
- eq(connectionGrantMembers.companyId, connection.companyId),
- eq(connectionGrantMembers.grantId, grant.id),
+ eq(toolCatalogEntries.companyId, companyId),
+ inArray(toolCatalogEntries.id, safeReadEntryIds),
),
);
- const inserted =
- requested.length === 0
- ? []
- : await tx
- .insert(connectionGrantMembers)
- .values(
- requested.map((subjectId) => ({
- companyId: connection.companyId,
- grantId: grant.id,
- subjectType: "user" as const,
- subjectId,
- })),
- )
- .returning();
- await tx
- .update(connectionGrants)
- .set({ updatedAt: new Date() })
- .where(eq(connectionGrants.id, grant.id));
- return inserted;
+ catalog = catalog.map((entry) =>
+ safeReadEntryIds.includes(entry.id)
+ ? {
+ ...entry,
+ status: "active",
+ reviewedAt,
+ quarantinedAt: null,
+ quarantineReason: null,
+ updatedAt: reviewedAt,
+ }
+ : entry,
+ );
+ }
+ const profile = await upsertExampleProfile(
+ companyId,
+ definition,
+ before.profile,
+ );
+ const profileEntries = await syncExampleProfileEntries(
+ companyId,
+ profile.row.id,
+ catalog,
+ );
+ const profileBinding = await upsertExampleProfileBinding(
+ companyId,
+ profile.row.id,
+ before.profileBinding,
+ actor,
+ );
+ const after = await exampleRows(companyId, definition);
+ return {
+ example: exampleSummary(definition, after),
+ created:
+ application.created ||
+ connection.created ||
+ profile.created ||
+ !before.profileBinding,
+ application: toApplication(application.row),
+ connection: refresh.connection,
+ profile: toProfile(profile.row),
+ profileEntries,
+ profileBinding,
+ catalog,
+ };
+ },
+
+ smokeExample: async (
+ companyId: string,
+ exampleId: string,
+ actor?: ActorInfo,
+ ): Promise<ToolExampleSmokeResult> => {
+ const definition = findExample(exampleId);
+ const rows = await exampleRows(companyId, definition);
+ if (!rows.connection || !rows.profile || !rows.profileBinding) {
+ throw conflict("Install this tool example before running smoke checks");
+ }
+ const catalog =
+ rows.catalog.length > 0
+ ? rows.catalog.map(toCatalogEntry)
+ : (await refreshCatalog(rows.connection.id, actor)).catalog;
+ const readEntry = catalog.find(
+ (entry) => entry.riskLevel === "read" && entry.status === "active",
+ );
+ const deniedEntry = catalog.find(
+ (entry) =>
+ entry.riskLevel === "write" || entry.riskLevel === "destructive",
+ );
+ if (!readEntry || !deniedEntry) {
+ throw unprocessable(
+ "Example smoke requires at least one read tool and one denied write/destructive tool",
+ );
+ }
+ const smokeActor = await exampleSmokeActor(companyId, actor);
+ const connection = toConnection(rows.connection);
+ const allowCheck = await runSmokeDecisionCheck({
+ companyId,
+ actor: smokeActor,
+ connection,
+ catalogEntry: readEntry,
+ expectedDecision: "allow",
+ name: "allow_read_tool",
});
- await db.insert(toolAccessAuditEvents).values({
- companyId: connection.companyId,
- connectionId: connection.id,
- actorType: binding.actorType ?? "system",
- actorId: binding.actorId,
- action: "connection_grant.audience_replaced",
- outcome: "success",
- reasonCode: "audience_replaced",
+ const denyCheck = await runSmokeDecisionCheck({
+ companyId,
+ actor: smokeActor,
+ connection,
+ catalogEntry: deniedEntry,
+ expectedDecision: "deny",
+ name: "deny_write_tool",
+ });
+ const auditCheck: ToolExampleSmokeCheck = {
+ name: "audit_written",
+ ok: Boolean(
+ allowCheck.auditEventId &&
+ allowCheck.toolCallEventId &&
+ denyCheck.auditEventId &&
+ denyCheck.toolCallEventId,
+ ),
details: {
- grantId: grant.id,
- memberCount: members.length,
- memberUserIds: requested,
+ auditEventIds: [allowCheck.auditEventId, denyCheck.auditEventId],
+ toolCallEventIds: [
+ allowCheck.toolCallEventId,
+ denyCheck.toolCallEventId,
+ ],
},
- });
- return { ...toConnectionGrant(grant), members };
+ };
+ const checks = [allowCheck, denyCheck, auditCheck];
+ return {
+ exampleId: definition.id,
+ ok: checks.every((check) => check.ok),
+ actor: smokeActor,
+ connection,
+ profile: toProfile(rows.profile),
+ checks,
+ };
},
- createConnectionGrantDelegation: async (
- idOrUid: string,
- grantId: string,
- agentId: string,
- ownerUserId: string,
- ) => {
- const connection = await getConnectionRow(idOrUid);
- if (connection.connectionPurpose === "ai") {
- throw badRequest("AI credentials use the connection's human access settings, not agent delegation");
- }
- return db.transaction(async (tx) => {
- // Membership removal/suspension takes this same row lock before sweeping
- // personal grants. Whichever operation wins is therefore authoritative:
- // removal deletes a delegation committed first, while creation that runs
- // second observes the inactive membership and fails closed.
- const [membership] = await tx
- .select({ id: companyMemberships.id })
- .from(companyMemberships)
+ listApplications: async (companyId: string): Promise<ToolApplication[]> => {
+ const rows = await db
+ .select()
+ .from(toolApplications)
+ .where(eq(toolApplications.companyId, companyId))
+ .orderBy(desc(toolApplications.updatedAt));
+ return rows.map(toApplication);
+ },
+
+ createApplication: async (
+ companyId: string,
+ input: CreateToolApplication,
+ ): Promise<ToolApplication> => {
+ await assertOptionalPlugin(input.pluginId);
+ await assertOptionalAgent(
+ companyId,
+ input.ownerAgentId,
+ "Tool application owner agent",
+ );
+ const [row] = await db
+ .insert(toolApplications)
+ .values({
+ companyId,
+ applicationKey: input.applicationKey ?? normalizeKey(input.name),
+ name: input.name,
+ description: input.description ?? null,
+ type: input.type,
+ status: input.status ?? "active",
+ pluginId: input.pluginId ?? null,
+ ownerAgentId: input.ownerAgentId ?? null,
+ ownerUserId: input.ownerUserId ?? null,
+ metadata: input.metadata ?? {},
+ })
+ .returning();
+ return toApplication(row);
+ },
+
+ getApplication: async (
+ applicationId: string,
+ companyId?: string,
+ ): Promise<ToolApplication> => {
+ const where = companyId
+ ? and(
+ eq(toolApplications.id, applicationId),
+ eq(toolApplications.companyId, companyId),
+ )
+ : eq(toolApplications.id, applicationId);
+ const [row] = await db.select().from(toolApplications).where(where);
+ if (!row) throw notFound("Tool application not found");
+ return toApplication(row);
+ },
+
+ updateApplication: async (
+ applicationId: string,
+ input: UpdateToolApplication,
+ ): Promise<ToolApplication> => {
+ const [existing] = await db
+ .select()
+ .from(toolApplications)
+ .where(eq(toolApplications.id, applicationId));
+ if (!existing) throw notFound("Tool application not found");
+ await assertOptionalPlugin(input.pluginId);
+ await assertOptionalAgent(
+ existing.companyId,
+ input.ownerAgentId,
+ "Tool application owner agent",
+ );
+ if (input.name && input.name !== existing.name) {
+ const [duplicate] = await db
+ .select({ id: toolApplications.id })
+ .from(toolApplications)
.where(
and(
- eq(companyMemberships.companyId, connection.companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, ownerUserId),
- eq(companyMemberships.status, "active"),
+ eq(toolApplications.companyId, existing.companyId),
+ eq(toolApplications.name, input.name),
+ ne(toolApplications.id, applicationId),
),
)
- .for("update")
.limit(1);
- if (!membership) {
- throw forbidden(
- "Only an active company member can delegate their personal grant",
+ if (duplicate) {
+ throw conflict("A tool access record with that name already exists", {
+ code: "tool_access_name_conflict",
+ });
+ }
+ }
+ const [row] = await db
+ .update(toolApplications)
+ .set({
+ name: input.name ?? existing.name,
+ description: input.description ?? existing.description,
+ status: input.status ?? existing.status,
+ pluginId: input.pluginId ?? existing.pluginId,
+ ownerAgentId: input.ownerAgentId ?? existing.ownerAgentId,
+ ownerUserId: input.ownerUserId ?? existing.ownerUserId,
+ metadata: input.metadata ?? existing.metadata,
+ updatedAt: new Date(),
+ })
+ .where(eq(toolApplications.id, applicationId))
+ .returning();
+ return toApplication(row);
+ },
+
+ deleteApplication: async (
+ applicationId: string,
+ ): Promise<ToolApplication> => {
+ const [existing] = await db
+ .select()
+ .from(toolApplications)
+ .where(eq(toolApplications.id, applicationId));
+ if (!existing) throw notFound("Tool application not found");
+ // Guard: never orphan connections. The caller must remove the connections
+ // or archive the application instead — there is no force-cascade in v1.
+ const linkedConnections = await db
+ .select({ id: toolConnections.id })
+ .from(toolConnections)
+ .where(eq(toolConnections.applicationId, applicationId));
+ if (linkedConnections.length > 0) {
+ throw conflict(
+ "This application still has connections. Remove its connections or archive the application instead of deleting it.",
+ { connectionCount: linkedConnections.length },
+ );
+ }
+ // The pre-check above gives a friendly 409 in the common case, but it cannot close the
+ // race where a connection is created in the gap before this delete runs. The FK is now
+ // ON DELETE RESTRICT, so such a delete fails closed with a foreign_key_violation instead
+ // of silently cascading the new connection away. Translate that into the same 409 so the
+ // endpoint keeps its contract instead of surfacing a 500.
+ let row: typeof toolApplications.$inferSelect | undefined;
+ try {
+ [row] = await db
+ .delete(toolApplications)
+ .where(eq(toolApplications.id, applicationId))
+ .returning();
+ } catch (error) {
+ if (isToolConnectionForeignKeyViolation(error)) {
+ throw conflict(
+ "This application still has connections. Remove its connections or archive the application instead of deleting it.",
);
}
+ throw error;
+ }
+ if (!row) throw notFound("Tool application not found");
+ return toApplication(row);
+ },
+
+ // Repository discovery uses credential audiences, not connection-management
+ // visibility. An administrator cannot browse another user's private repos.
+ listProjectRepositories: async (companyId: string, userId: string | null, localTrusted = false) =>
+ toolAccessService(db).listGitHubRepositories(companyId, userId, localTrusted),
+
+ // Return identifiers, never credentials, so each attempted read can recheck its grant.
+ githubReadConnectionIds: async (companyId: string, userId: string | null, localTrusted = false): Promise<string[]> => {
+ const connections = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, companyId), eq(toolConnections.enabled, true))).orderBy(desc(toolConnections.updatedAt));
+ const ids: string[] = [];
+ for (const connection of connections) {
+ if (connection.status !== "active" || asRecord(connection.config).sourceTemplateKey !== "github") continue;
+ try {
+ await gitHubReadGrantAccess(db, companyId, connection.id, userId, localTrusted);
+ ids.push(connection.id);
+ } catch (error) {
+ // Only ineligible grants are skipped; database/service failures must surface.
+ if (!(error instanceof Error && "status" in error && error.status === 403)) throw error;
+ }
+ }
+ return ids;
+ },
+
+ githubReadGrantIds: async (companyId: string, connectionId: string, userId: string | null, localTrusted = false): Promise<Array<string | null>> => {
+ const { allowed, legacyShared } = await gitHubReadGrantAccess(db, companyId, connectionId, userId, localTrusted);
+ return legacyShared ? [null] : allowed.map(grant => grant.id);
+ },
+
+ // Server-side reads share the same grant audience and credential lifecycle as discovery.
+ githubReadHeaders: async (companyId: string, connectionId: string, userId: string | null, localTrusted = false, forceRefresh = false, grantId?: string | null): Promise<Record<string, string>> => {
+ const { connection, allowed, legacyShared } = await gitHubReadGrantAccess(db, companyId, connectionId, userId, localTrusted);
+ const actor: ActorInfo = { actorType: "user", actorId: userId ?? "board" };
+ if (legacyShared && !grantId) return resolveCredentialHeaders(connection, actor);
+ let grant = grantId ? allowed.find(candidate => candidate.id === grantId) : allowed.length === 1 ? allowed[0] : undefined;
+ if (!grant) throw forbidden("Choose an active GitHub authorization you can use.");
+ if (asRecord(asRecord(connection.config).oauth).connectorProfile === "github.code") {
+ grant = await refreshOAuthGrantCredentials({ companyId, connectionId, grantId: grant.id, actor, forceRefresh });
+ }
+ const ref = grant.credentialSecretRefs.find(ref => ref.configPath === "oauth.access_token" || /authorization|token|api_key/i.test(ref.configPath));
+ if (!ref) throw unprocessable("Reconnect GitHub to read repository files.");
+ const secret = await resolveOAuthGrantSecret(connection, grant, ref, actor, undefined);
+ return { Authorization: `Bearer ${secret.value}` };
+ },
- const [grant] = await tx
+ listGitHubRepositories: async (
+ companyId: string,
+ userId: string | null,
+ localTrusted = false,
+ ) => measureRunPhase("connectors.github.catalog", async () => {
+ const [connections, grants, members, memberships] = await Promise.all([
+ measureRunPhase("connectors.github.connections", () => db
.select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.id, grantId),
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "user"),
- eq(connectionGrants.subjectUserId, ownerUserId),
- eq(connectionGrants.status, "active"),
- ),
- )
- .for("update")
- .limit(1);
- if (!grant)
- throw forbidden(
- "Only the active personal grant owner can create a delegation",
- );
- await tx.select({ id: toolConnections.id }).from(toolConnections)
- .where(eq(toolConnections.id, connection.id)).for("key share");
- const [targetAgent] = await tx
- .select({ id: agents.id })
- .from(agents)
+ .from(toolConnections)
.where(
and(
- eq(agents.id, agentId),
- eq(agents.companyId, connection.companyId),
+ eq(toolConnections.companyId, companyId),
+ eq(toolConnections.enabled, true),
),
- )
- .for("no key update")
- .limit(1);
- if (!targetAgent) throw notFound("Agent not found");
- const [existing] = await tx
+ )),
+ measureRunPhase("connectors.github.grants", () => db
.select()
- .from(connectionGrantDelegations)
- .where(
- and(
- eq(connectionGrantDelegations.grantId, grant.id),
- eq(connectionGrantDelegations.agentId, agentId),
- ),
- )
- .limit(1);
- if (existing) return existing;
- const [delegation] = await tx
- .insert(connectionGrantDelegations)
- .values({
- companyId: connection.companyId,
- grantId: grant.id,
- agentId,
- createdByUserId: ownerUserId,
- })
- .returning();
- await tx.insert(toolAccessAuditEvents).values({
- companyId: connection.companyId,
- connectionId: connection.id,
+ .from(connectionGrants)
+ .where(eq(connectionGrants.companyId, companyId))),
+ measureRunPhase("connectors.github.grant_members", () => db
+ .select()
+ .from(connectionGrantMembers)
+ .where(eq(connectionGrantMembers.companyId, companyId))),
+ userId
+ ? measureRunPhase("connectors.github.membership", () => db
+ .select()
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, userId),
+ eq(companyMemberships.status, "active"),
+ ),
+ ))
+ : Promise.resolve([]),
+ ]);
+ const repositories = new Map<
+ string,
+ import("@paperclipai/shared").ProjectRepository
+ >();
+ const usableConnections: Array<{ id: string; name: string }> = [];
+ let connectionCount = 0;
+ let failedConnectionCount = 0;
+ for (const connection of connections) {
+ if (
+ connection.status !== "active" ||
+ asRecord(connection.config).sourceTemplateKey !== "github"
+ )
+ continue;
+ const connectionGrants = grants.filter(
+ (grant) => grant.connectionId === connection.id,
+ );
+ const availableGrants = connectionGrants.filter(
+ (grant) =>
+ !(
+ grant.kind === "organization" &&
+ ["per_user", "per_agent"].includes(connection.credentialPolicy)
+ ) &&
+ canBrowseProjectRepositoryGrant({
+ grant,
+ userId,
+ activeMember: localTrusted || memberships.length > 0,
+ audience: members
+ .filter((member) => member.grantId === grant.id)
+ .map((member) => member.subjectId),
+ }),
+ );
+ // Legacy shared PAT connections predate grants. Never fall back when a
+ // grant exists but is revoked, private, or outside the caller's audience.
+ const legacyShared =
+ connectionGrants.length === 0 &&
+ connection.credentialPolicy === "shared" &&
+ (localTrusted || (!!userId && memberships.length > 0));
+ if (!availableGrants.length && !legacyShared) continue;
+ connectionCount += 1;
+ usableConnections.push({ id: connection.id, name: connection.name });
+ const actor: ActorInfo = {
actorType: "user",
- actorId: ownerUserId,
- action: "connection_grant.delegated",
- outcome: "success",
- reasonCode: "delegation_created",
- details: { grantId: grant.id, delegationId: delegation!.id, agentId },
- });
- return delegation!;
- });
- },
+ actorId: userId ?? "board",
+ };
+ let failed = false;
+ for (const initialGrant of legacyShared ? [null] : availableGrants) {
+ try {
+ let rows: Array<{
+ id: string;
+ fullName: string;
+ private?: boolean;
+ }>;
+ if (
+ initialGrant &&
+ asRecord(asRecord(connection.config).oauth).connectorProfile ===
+ "github.code"
+ ) {
+ const grant = await refreshManagedGitHubGrantAccess(
+ connection,
+ initialGrant,
+ actor,
+ );
+ rows = grant.providerTenant?.github?.repositories ?? [];
+ } else {
+ const headers = await measureRunPhase("connectors.github.credentials", () => initialGrant
+ ? (async () => {
+ const ref = initialGrant.credentialSecretRefs.find(
+ (ref) =>
+ ref.configPath === "oauth.access_token" ||
+ /authorization|token|api_key/i.test(ref.configPath),
+ );
+ if (!ref)
+ throw unprocessable(
+ "Reconnect GitHub to load repositories",
+ );
+ const secret = await resolveOAuthGrantSecret(
+ connection,
+ initialGrant,
+ ref,
+ actor,
+ undefined,
+ );
+ return { Authorization: `Bearer ${secret.value}` };
+ })()
+ : resolveCredentialHeaders(connection, actor));
+ rows = await measureRunPhase("connectors.github.repositories", () => loadGitHubTokenRepositories(headers));
+ }
+ for (const row of rows) {
+ mergeProjectRepository(repositories, row, connection.name, connection.id);
+ }
+ } catch {
+ // Credential/provider errors may contain secrets. Only expose an
+ // aggregate failure; successful connections remain usable.
+ failed = true;
+ }
+ }
+ if (failed) failedConnectionCount += 1;
+ }
+ return {
+ repositories: [...repositories.values()].sort((a, b) =>
+ a.fullName.localeCompare(b.fullName),
+ ),
+ connections: usableConnections,
+ connectionCount,
+ failedConnectionCount,
+ };
+ }),
- revokeConnectionGrantDelegation: async (
- idOrUid: string,
- grantId: string,
- delegationId: string,
- actor?: ActorInfo,
- ) => {
- const connection = await getConnectionRow(idOrUid);
- const delegation = await db.transaction(async tx => {
- const [grant] = await tx.select({ id: connectionGrants.id }).from(connectionGrants)
- .where(and(eq(connectionGrants.id, grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id)))
- .for("update");
- if (!grant) return undefined;
- const [target] = await tx.select({ agentId: connectionGrantDelegations.agentId }).from(connectionGrantDelegations)
- .where(and(eq(connectionGrantDelegations.id, delegationId), eq(connectionGrantDelegations.companyId, connection.companyId), eq(connectionGrantDelegations.grantId, grantId)));
- if (!target) return undefined;
- await tx.select({ id: agents.id }).from(agents)
- .where(and(eq(agents.companyId, connection.companyId), eq(agents.id, target.agentId))).for("no key update");
- const [removed] = await tx
- .delete(connectionGrantDelegations)
- .where(
- and(
- eq(connectionGrantDelegations.id, delegationId),
- eq(connectionGrantDelegations.companyId, connection.companyId),
- eq(connectionGrantDelegations.grantId, grantId),
+ listConnections: async (
+ companyId: string,
+ viewerUserId?: string,
+ ): Promise<ToolConnection[]> => {
+ const rows = await db
+ .select()
+ .from(toolConnections)
+ .where(eq(toolConnections.companyId, companyId))
+ .orderBy(desc(toolConnections.updatedAt));
+ const connections = rows.map(toConnection);
+ if (connections.length === 0) return connections;
+ const installRows = await db
+ .select()
+ .from(toolConnectionInstalls)
+ .where(eq(toolConnectionInstalls.companyId, companyId))
+ .orderBy(
+ asc(toolConnectionInstalls.targetType),
+ asc(toolConnectionInstalls.targetId),
+ );
+ const installsByConnection = new Map<string, ToolConnectionInstall[]>();
+ for (const row of installRows) {
+ const installs = installsByConnection.get(row.connectionId) ?? [];
+ installs.push(toConnectionInstall(row));
+ installsByConnection.set(row.connectionId, installs);
+ }
+ for (const connection of connections)
+ connection.installs = installsByConnection.get(connection.id) ?? [];
+ // Enrich with "last used" = most recent tool-call event per connection so the
+ // prosumer Apps list can surface a staleness signal without an N+1 fan-out.
+ const lastUsedRows = await db
+ .select({
+ connectionId: toolCallEvents.connectionId,
+ lastUsedAt: max(toolCallEvents.createdAt),
+ })
+ .from(toolCallEvents)
+ .where(
+ and(
+ eq(toolCallEvents.companyId, companyId),
+ inArray(
+ toolCallEvents.connectionId,
+ connections.map((connection) => connection.id),
),
- )
- .returning();
- return removed;
- });
- if (!delegation) throw notFound("Connection grant delegation not found");
- const binding = actorBinding(actor);
- await db.insert(toolAccessAuditEvents).values({
- companyId: connection.companyId,
- connectionId: connection.id,
- actorType: binding.actorType ?? "system",
- actorId: binding.actorId,
- action: "connection_grant.delegation_revoked",
- outcome: "success",
- reasonCode: "delegation_revoked",
- details: { grantId, delegationId, agentId: delegation.agentId },
- });
- return delegation;
+ ),
+ )
+ .groupBy(toolCallEvents.connectionId);
+ const lastUsedByConnection = new Map(
+ lastUsedRows.map((row) => [row.connectionId, row.lastUsedAt]),
+ );
+ for (const connection of connections) {
+ connection.lastUsedAt = lastUsedByConnection.get(connection.id) ?? null;
+ }
+ await annotateAiGrantHealth(connections);
+ await annotateGitHubAuthorization(connections, viewerUserId);
+ await annotateSavedOAuthClientSecret(connections, viewerUserId);
+ return connections;
},
- addConnectionInstallation: async (
- idOrUid: string,
- input: {
- providerTenant?: { name?: string; externalId?: string };
- credentialSecretRefs?: typeof connectionGrants.$inferInsert.credentialSecretRefs;
- isDefault?: boolean;
- },
+ createConnection: async (
+ companyId: string,
+ input: CreateToolConnection,
actor?: ActorInfo,
- ) => {
- const connection = await getConnectionRow(idOrUid);
- await assertSecretRefs(
- connection.companyId,
- input.credentialSecretRefs ?? [],
+ ): Promise<ToolConnection> => {
+ let applicationId = input.applicationId;
+ let applicationNamespace = input.applicationName ?? input.name;
+ const transport = input.transport;
+ if (!transport) throw badRequest("Tool connection transport is required");
+ const config = normalizeGoogleSheetsConnectionConfig(
+ input.config ?? input.transportConfig ?? {},
);
- if (input.isDefault) {
- await db
- .update(connectionGrants)
- .set({ isDefault: false, updatedAt: new Date() })
- .where(
- and(
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "organization"),
- ),
+ await assertConnectorConnectionSetupEnabled({ config, applicationId, companyId });
+ // Validate company-scoped references before touching a caller-supplied
+ // network endpoint. Besides failing fast, this keeps cross-company
+ // authorization errors from being masked by DNS or SSRF validation.
+ await assertSecretRefs(companyId, [
+ ...(input.credentialRefs ?? []),
+ ...(input.credentialSecretRefs ?? []),
+ ]);
+ if (transport === "mcp_remote")
+ await assertRemoteConnectionEndpointsAllowed(config);
+ if (transport === "local_stdio") await stdioTemplateId(companyId, config);
+ assertLocalStdioCanBeEnabled(transport, input.enabled ?? false, config);
+ await assertGoogleSheetsSpreadsheetOwnership(companyId, config);
+ if (applicationId) {
+ const app = await assertApplication(companyId, applicationId);
+ applicationNamespace = app.applicationKey ?? app.name;
+ await assertConnectorConnectionSetupEnabled({ config }, applicationNamespace);
+ if (
+ (transport === "mcp_remote" && app.type !== "mcp_http") ||
+ (transport === "local_stdio" && app.type !== "mcp_stdio")
+ ) {
+ throw unprocessable(
+ "Connection transport must match application type",
);
+ }
+ } else {
+ const [app] = await db
+ .insert(toolApplications)
+ .values({
+ companyId,
+ applicationKey: normalizeKey(input.applicationName ?? input.name),
+ name: input.applicationName ?? input.name,
+ type: isBrowserUseConnection({ transport, config }) || isDaytonaConnection({ transport, config }) ? "rest_api" : transport === "mcp_remote" ? "mcp_http" : "mcp_stdio",
+ status: "active",
+ metadata: {},
+ })
+ .returning();
+ applicationId = app.id;
}
+ const connectionId = randomUUID();
const binding = actorBinding(actor);
- const [grant] = await db
- .insert(connectionGrants)
+ const [row] = await db
+ .insert(toolConnections)
.values({
- companyId: connection.companyId,
- connectionId: connection.id,
- kind: "organization",
- providerTenant: input.providerTenant,
+ id: connectionId,
+ companyId,
+ applicationId,
+ name: input.name,
+ uid: connectionUid(applicationNamespace, input.name, connectionId),
+ connectionKind: input.connectionKind ?? "managed",
+ ownership: input.ownership ?? "customer",
+ transport,
+ authKind: input.authKind ?? "none",
+ credentialPolicy:
+ input.credentialPolicy ??
+ (input.authKind === "oauth" ? "per_user" : "shared"),
+ status: input.status ?? "draft",
+ enabled: input.enabled ?? false,
+ agentInstructions: input.agentInstructions !== undefined ? input.agentInstructions : defaultConnectionAgentInstructions(
+ typeof config.sourceTemplateKey === "string" ? getConnectableAppDefinition(config.sourceTemplateKey)?.agentInstructions : null,
+ ),
+ config,
+ transportConfig: isGoogleSheetsConnectionConfig(config)
+ ? config
+ : (input.transportConfig ?? config),
+ credentialRefs: input.credentialRefs ?? [],
credentialSecretRefs: input.credentialSecretRefs ?? [],
- status: "active",
- isDefault: input.isDefault ?? false,
createdByAgentId:
binding.actorType === "agent" ? binding.actorId : null,
createdByUserId:
binding.actorType === "user" ? binding.actorId : null,
})
.returning();
- if (!grant) throw new Error("Failed to create connection installation");
- await db.insert(toolAccessAuditEvents).values({
- companyId: connection.companyId,
- connectionId: connection.id,
- actorType: binding.actorType ?? "system",
- actorId: binding.actorId,
- action: "connection_grant.created",
- outcome: "success",
- reasonCode: "grant_created",
- details: {
- grantId: grant.id,
- kind: grant.kind,
- isDefault: grant.isDefault,
- },
- });
- return toConnectionGrant(grant);
+ await ensureDefaultOrganizationGrant(row);
+ await syncCredentialBindings(row);
+ await ensureRuntimeSlot(row);
+ emitConnectionCreated(row, "api");
+ return toConnection(row);
+ },
+
+ getConnection: async (
+ connectionId: string,
+ companyId?: string,
+ viewerUserId?: string,
+ ): Promise<ToolConnection> => {
+ const connection = toConnection(
+ await getConnectionRow(connectionId, companyId),
+ );
+ connection.installs = await listConnectionInstalls(
+ connection.id,
+ connection.companyId,
+ );
+ await annotateAiGrantHealth([connection]);
+ await annotateGitHubAuthorization([connection], viewerUserId);
+ await annotateSavedOAuthClientSecret([connection], viewerUserId);
+ return connection;
+ },
+
+ listConnectionGrants: async (idOrUid: string, companyId?: string) => {
+ const connection = await getConnectionRow(idOrUid, companyId);
+ const grants = await db
+ .select()
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ ),
+ )
+ .orderBy(
+ desc(connectionGrants.isDefault),
+ desc(connectionGrants.updatedAt),
+ );
+ const grantIds = grants.map((grant) => grant.id);
+ const [members, delegations] =
+ grantIds.length === 0
+ ? [[], []]
+ : await Promise.all([
+ db
+ .select()
+ .from(connectionGrantMembers)
+ .where(
+ and(
+ eq(connectionGrantMembers.companyId, connection.companyId),
+ inArray(connectionGrantMembers.grantId, grantIds),
+ ),
+ ),
+ db
+ .select()
+ .from(connectionGrantDelegations)
+ .where(
+ and(
+ eq(
+ connectionGrantDelegations.companyId,
+ connection.companyId,
+ ),
+ inArray(connectionGrantDelegations.grantId, grantIds),
+ ),
+ ),
+ ]);
+ return {
+ connection: { id: connection.id, uid: connection.uid },
+ grants: grants.map((grant) => ({
+ ...toConnectionGrant(grant),
+ members: members.filter((member) => member.grantId === grant.id),
+ delegations: delegations.filter(
+ (delegation) => delegation.grantId === grant.id,
+ ),
+ })),
+ };
+ },
+
+ /**
+ * Company members eligible to appear in an organization grant's audience.
+ * The audience editor needs display names, and the client must not have to
+ * cross-reference a second endpoint to render "12 selected members".
+ */
+ listConnectionAudienceMembers: async (companyId: string) => {
+ const rows = await db
+ .select({
+ userId: companyMemberships.principalId,
+ name: authUsers.name,
+ email: authUsers.email,
+ })
+ .from(companyMemberships)
+ .leftJoin(authUsers, eq(authUsers.id, companyMemberships.principalId))
+ .where(
+ and(
+ eq(companyMemberships.companyId, companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.status, "active"),
+ ),
+ );
+ return rows
+ .map((row) => ({
+ userId: row.userId,
+ name: row.name ?? null,
+ email: row.email ?? null,
+ }))
+ .sort((a, b) =>
+ (a.name ?? a.email ?? a.userId).localeCompare(
+ b.name ?? b.email ?? b.userId,
+ ),
+ );
},
- revokeConnectionGrant: async (
+ /**
+ * Replace an organization grant's audience atomically (PAP-17835).
+ *
+ * An empty `memberUserIds` persists as zero rows, which the resolver already
+ * treats as "every organization member". Replacement is delete-then-insert
+ * inside one transaction so a partially-applied audience can never widen or
+ * narrow access, and every member id is checked against active company
+ * membership first so an audience cannot name an outsider. Existing audience
+ * members are locked too: membership cleanup deliberately retains a sole
+ * inactive audience row, and a concurrent empty replacement must not erase
+ * that fail-closed marker after cleanup wins. Once cleanup has retained that
+ * marker, callers must restore the member or replace it with an active named
+ * audience before widening access to the whole company.
+ */
+ replaceConnectionGrantMembers: async (
idOrUid: string,
grantId: string,
+ memberUserIds: string[],
actor?: ActorInfo,
) => {
const connection = await getConnectionRow(idOrUid);
- const binding = actorBinding(actor);
- const [currentGrant] = await db
+ const [grant] = await db
.select()
.from(connectionGrants)
.where(
@@ -15864,1610 +14561,1261 @@ export function toolAccessService(
eq(connectionGrants.id, grantId),
eq(connectionGrants.companyId, connection.companyId),
eq(connectionGrants.connectionId, connection.id),
- ),
- )
- .limit(1);
- if (!currentGrant) throw notFound("Connection grant not found");
- let providerRevocation = "not_applicable";
- if (
- connection.credentialSource === "vercel_connect" &&
- connection.externalCredential
- ) {
- const request = vercelTokenRequest({
- credential: connection.externalCredential,
- grant: currentGrant,
- connectionId: connection.id,
- companyId: connection.companyId,
- resources: vercelConnectResourcesFor(connection),
- });
- vercelConnect?.evict(request);
- if (currentGrant.externalCredential?.subjectType === "app") {
- providerRevocation = "manage_in_vercel";
- } else if (currentGrant.externalCredential?.subjectType === "user") {
- try {
- if (!vercelConnect) throw new Error("Vercel Connect unavailable");
- await vercelConnect.revoke(request);
- providerRevocation = "success";
- } catch {
- providerRevocation = "failed";
- }
- }
- } else if (
- isPaperclipCloudConnectorStrategy(oauthConfig(connection).strategy)
- ) {
- // Google revocation is client-wide for a user. The managed Workspace
- // profiles intentionally share one Paperclip-owned client, so revoking
- // one token here could invalidate unrelated Gmail, Drive, and Calendar
- // grants. A per-profile removal is therefore local-only. A future
- // provider-level disconnect must warn that it removes every profile.
- providerRevocation = "local_only_shared_client";
- }
- const grant = await db.transaction(async (tx) => {
- const [lockedGrant] = await tx.select({ id: connectionGrants.id }).from(connectionGrants)
- .where(and(eq(connectionGrants.id, grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id)))
- .for("update");
- if (!lockedGrant) throw notFound("Connection grant not found");
- await tx.select({ id: agents.id }).from(agents)
- .where(and(eq(agents.companyId, connection.companyId), notInArray(agents.status, ["pending_approval", "terminated"])))
- .orderBy(agents.id).for("no key update");
- const removedDelegations = await tx
- .delete(connectionGrantDelegations)
- .where(
- and(
- eq(connectionGrantDelegations.companyId, connection.companyId),
- eq(connectionGrantDelegations.grantId, grantId),
- ),
- )
- .returning();
- const [updated] = await tx
- .update(connectionGrants)
- .set({
- status: "revoked",
- isDefault: false,
- revokedAt: new Date(),
- revokedByAgentId:
- binding.actorType === "agent" ? binding.actorId : null,
- revokedByUserId:
- binding.actorType === "user" ? binding.actorId : null,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(connectionGrants.id, grantId),
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
- ),
- )
- .returning();
- if (!updated) throw notFound("Connection grant not found");
- if (removedDelegations.length > 0) {
- await tx.insert(toolAccessAuditEvents).values(
- removedDelegations.map((delegation) => ({
- companyId: connection.companyId,
- connectionId: connection.id,
- actorType: binding.actorType ?? "system",
- actorId: binding.actorId,
- action: "connection_grant.delegation_revoked",
- outcome: "success",
- reasonCode: "grant_revoked",
- details: {
- grantId,
- delegationId: delegation.id,
- agentId: delegation.agentId,
- },
- })),
- );
- }
- return updated;
- });
- if (!grant) throw notFound("Connection grant not found");
- await db.insert(toolAccessAuditEvents).values({
- companyId: connection.companyId,
- connectionId: connection.id,
- actorType: binding.actorType ?? "system",
- actorId: binding.actorId,
- action: "connection_grant.revoked",
- outcome: "success",
- reasonCode: "grant_revoked",
- details: { grantId: grant.id, kind: grant.kind, providerRevocation },
- });
- return toConnectionGrant(grant);
- },
-
- getConnectionUsage: async (
- idOrUid: string,
- range: "7d" | "30d",
- companyId?: string,
- ) => {
- const connection = await getConnectionRow(idOrUid, companyId);
- const days = range === "30d" ? 30 : 7;
- const start = new Date();
- start.setUTCHours(0, 0, 0, 0);
- start.setUTCDate(start.getUTCDate() - days + 1);
- const [issuances, invocations] = await Promise.all([
- db
- .select({
- createdAt: connectionTokenIssuances.createdAt,
- outcome: connectionTokenIssuances.outcome,
- path: connectionTokenIssuances.path,
- })
- .from(connectionTokenIssuances)
- .where(
- and(
- eq(connectionTokenIssuances.companyId, connection.companyId),
- eq(connectionTokenIssuances.connectionId, connection.id),
- gte(connectionTokenIssuances.createdAt, start),
- ),
- ),
- db
- .select({
- createdAt: toolInvocations.createdAt,
- riskLevel: toolInvocations.riskLevel,
- })
- .from(toolInvocations)
- .where(
- and(
- eq(toolInvocations.companyId, connection.companyId),
- eq(toolInvocations.connectionId, connection.id),
- gte(toolInvocations.createdAt, start),
- ),
- ),
- ]);
- const buckets = Array.from({ length: days }, (_, offset) => {
- const date = new Date(start);
- date.setUTCDate(start.getUTCDate() + offset);
- return {
- date: date.toISOString().slice(0, 10),
- issuances: {
- total: 0,
- byOutcome: {} as Record<string, number>,
- byPath: {} as Record<string, number>,
- },
- invocations: { total: 0, byRiskLevel: {} as Record<string, number> },
- deliveries: { received: 0, forwarded: 0 },
- };
- });
- const byDate = new Map(buckets.map((bucket) => [bucket.date, bucket]));
- for (const row of issuances) {
- const bucket = byDate.get(row.createdAt.toISOString().slice(0, 10));
- if (!bucket) continue;
- bucket.issuances.total += 1;
- bucket.issuances.byOutcome[row.outcome] =
- (bucket.issuances.byOutcome[row.outcome] ?? 0) + 1;
- bucket.issuances.byPath[row.path] =
- (bucket.issuances.byPath[row.path] ?? 0) + 1;
- }
- for (const row of invocations) {
- const bucket = byDate.get(row.createdAt.toISOString().slice(0, 10));
- if (!bucket) continue;
- const riskLevel = row.riskLevel ?? "unknown";
- bucket.invocations.total += 1;
- bucket.invocations.byRiskLevel[riskLevel] =
- (bucket.invocations.byRiskLevel[riskLevel] ?? 0) + 1;
- }
- return {
- connection: { id: connection.id, uid: connection.uid },
- range,
- buckets,
- };
- },
-
- listConnectionInstalls,
-
- putConnectionInstalls: async (
- connectionId: string,
- input: PutToolConnectionInstalls,
- actor?: ActorInfo,
- ): Promise<ToolConnectionInstallSnapshot> => {
- const connection = await getConnectionRow(connectionId);
- const requested = new Map(
- input.installs.map((install) => [
- `${install.targetType}:${install.targetId}`,
- install,
- ]),
- );
- for (const install of requested.values()) {
- if (install.targetType === "company") {
- if (install.targetId !== connection.companyId)
- throw unprocessable(
- "Company installs must target the connection company",
- );
- } else {
- await assertOptionalAgent(
- connection.companyId,
- install.targetId,
- "Tool connection install agent",
- );
- }
+ ),
+ )
+ .limit(1);
+ if (!grant) throw notFound("Connection grant not found");
+ if (grant.kind !== "organization") {
+ throw badRequest(
+ "Only an organization identity has an audience; a personal identity belongs to its owner",
+ );
}
- const markMcpAccessConfigured = connection.transport === "mcp_remote"
- && connection.config.mcpAgentAccessConfigured !== true;
- const accessExtensions: Array<{
- targetType: "company" | "agent";
- targetId: string;
- profileId: string;
- }> = [];
- await db.transaction(async (tx) => {
- await lockToolConnectionRuntimeInputs(tx, connection.companyId, connection.id);
- if (markMcpAccessConfigured) {
- // Preserve an explicit zero-agent selection through OAuth. Merge the
- // marker in SQL so concurrent credential/config changes are retained.
- await tx.update(toolConnections).set({
- config: sql`${toolConnections.config} || '{"mcpAgentAccessConfigured":true}'::jsonb`,
- transportConfig: sql`${toolConnections.transportConfig} || '{"mcpAgentAccessConfigured":true}'::jsonb`,
- updatedAt: now(),
- }).where(and(
- eq(toolConnections.companyId, connection.companyId),
- eq(toolConnections.id, connection.id),
- ));
- }
- const existing = await tx
+ const requested = [
+ ...new Set(memberUserIds.map((id) => id.trim()).filter(Boolean)),
+ ];
+ const binding = actorBinding(actor);
+ const members = await db.transaction(async (tx) => {
+ // Serialize replacements before taking the current audience snapshot.
+ // Otherwise a second replacement could read the old rows, wait behind
+ // an in-flight replacement, and then miss locking a newly-added member.
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${"paperclip.connection_grant_audience:" + grant.id}, 0))`);
+ const existingAudience = await tx
.select()
- .from(toolConnectionInstalls)
+ .from(connectionGrantMembers)
.where(
and(
- eq(toolConnectionInstalls.companyId, connection.companyId),
- eq(toolConnectionInstalls.connectionId, connection.id),
+ eq(connectionGrantMembers.companyId, connection.companyId),
+ eq(connectionGrantMembers.grantId, grant.id),
+ eq(connectionGrantMembers.subjectType, "user"),
),
);
- const existingKeys = new Set(
- existing.map(
- (install) => `${install.targetType}:${install.targetId}`,
- ),
- );
- const bindings = await tx.select({ targetType: toolProfileBindings.targetType, targetId: toolProfileBindings.targetId })
- .from(toolProfileBindings).innerJoin(toolProfiles, eq(toolProfiles.id, toolProfileBindings.profileId))
- .where(and(eq(toolProfileBindings.companyId, connection.companyId), eq(toolProfiles.companyId, connection.companyId), eq(toolProfiles.profileKey, `app:${connection.id}`)));
- await lockToolAssignmentAgents(tx, connection.companyId, [...existing, ...requested.values(), ...bindings]);
- const removals = existing.filter(
- (install) =>
- !requested.has(`${install.targetType}:${install.targetId}`),
- );
- const removeIds = removals.map((install) => install.id);
- if (removeIds.length > 0) {
- await tx
- .delete(toolConnectionInstalls)
- .where(inArray(toolConnectionInstalls.id, removeIds));
- // Uninstalling must also drop the binding this path created. Installing
- // writes both an install row and a profile binding, so deleting only the
- // install row leaves a binding that no surface can see or remove. The
- // install row is the reach gate (`mintConnectionTokenForAgent` fails with
- // `installation_required`, and the heartbeat only hands over installed
- // connections), so a stale binding grants no reach on its own — but it
- // still makes `finishApp`, which rebuilds `access` from the bindings,
- // read a target the operator already removed.
- //
- // Only bindings tagged `source: "tool_connection_install"` are removed.
- // A binding the operator authored through the access model carries a
- // different source and must survive an uninstall.
- const [installProfile] = await tx
- .select({ id: toolProfiles.id })
- .from(toolProfiles)
+ const existingUserIds = [
+ ...new Set(existingAudience.map((row) => row.subjectId)),
+ ];
+ const membershipUserIds = [
+ ...new Set([...existingUserIds, ...requested]),
+ ];
+ if (membershipUserIds.length > 0) {
+ // Membership suspension/archive/removal takes the same row lock before
+ // sweeping grant audiences. Lock both the old and new audience so an
+ // empty replacement also serializes with cleanup of its existing sole
+ // member. Whichever transaction wins is then authoritative.
+ const memberships = await tx
+ .select({
+ principalId: companyMemberships.principalId,
+ status: companyMemberships.status,
+ })
+ .from(companyMemberships)
.where(
and(
- eq(toolProfiles.companyId, connection.companyId),
- eq(toolProfiles.profileKey, `app:${connection.id}`),
+ eq(companyMemberships.companyId, connection.companyId),
+ eq(companyMemberships.principalType, "user"),
+ inArray(companyMemberships.principalId, membershipUserIds),
),
)
- .limit(1);
- if (installProfile) {
- for (const install of removals) {
- await tx
- .delete(toolProfileBindings)
- .where(
- and(
- eq(toolProfileBindings.companyId, connection.companyId),
- eq(toolProfileBindings.profileId, installProfile.id),
- eq(toolProfileBindings.targetType, install.targetType),
- eq(toolProfileBindings.targetId, install.targetId),
- sql`${toolProfileBindings.metadata}->>'source' = 'tool_connection_install'`,
- ),
- );
- }
+ .orderBy(asc(companyMemberships.id))
+ .for("update");
+ const active = new Set(
+ memberships
+ .filter((row) => row.status === "active")
+ .map((row) => row.principalId),
+ );
+ const unknown = requested.filter((id) => !active.has(id));
+ if (unknown.length > 0) {
+ throw unprocessable(
+ "Every audience member must be an active member of this company",
+ {
+ code: "audience_member_not_in_company",
+ unknownUserIds: unknown,
+ },
+ );
}
- }
- const additions = [...requested.entries()]
- .filter(([key]) => !existingKeys.has(key))
- .map(([, install]) => install);
- if (additions.length > 0) {
- await tx.insert(toolConnectionInstalls).values(
- additions.map((install) => ({
- companyId: connection.companyId,
- connectionId: connection.id,
- targetType: install.targetType,
- targetId: install.targetId,
- createdByAgentId:
- actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
- createdByUserId:
- actor?.actorType === "user" ? (actor.actorId ?? null) : null,
- })),
+ const inactiveExisting = existingUserIds.filter(
+ (id) => !active.has(id),
);
- }
- if (requested.size > 0 && connection.connectionPurpose !== "ai") {
- const profile = await appProfileForConnection(tx, connection);
- for (const install of requested.values()) {
- const [binding] = await tx
- .insert(toolProfileBindings)
- .values({
- companyId: connection.companyId,
- profileId: profile.id,
- targetType: install.targetType,
- targetId: install.targetId,
- priority: 100,
- metadata: {
- source: "tool_connection_install",
- connectionId: connection.id,
- },
- createdByAgentId:
- actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
- createdByUserId:
- actor?.actorType === "user" ? (actor.actorId ?? null) : null,
- })
- .onConflictDoNothing()
- .returning({ id: toolProfileBindings.id });
- if (binding)
- accessExtensions.push({
- targetType: install.targetType,
- targetId: install.targetId,
- profileId: profile.id,
- });
+ if (requested.length === 0 && inactiveExisting.length > 0) {
+ throw conflict(
+ "Replace inactive audience members before widening access to the whole company",
+ {
+ code: "audience_widening_blocked",
+ inactiveUserIds: inactiveExisting,
+ },
+ );
}
}
- if (markMcpAccessConfigured || removeIds.length > 0 || additions.length > 0) {
- const binding = actorBinding(actor);
- await tx.insert(toolAccessAuditEvents).values({
- companyId: connection.companyId,
- connectionId: connection.id,
- actorType: binding.actorType ?? "system",
- actorId: binding.actorId,
- action: "connection_installs.changed",
- outcome: "success",
- reasonCode: "installs_changed",
- details: {
- ...(markMcpAccessConfigured ? { mcpAgentAccessConfigured: true } : {}),
- added: additions.map((install) => ({
- targetType: install.targetType,
- targetId: install.targetId,
- })),
- removed: existing
- .filter((install) => removeIds.includes(install.id))
- .map((install) => ({
- targetType: install.targetType,
- targetId: install.targetId,
- })),
- },
- });
- }
- });
- for (const extension of accessExtensions) {
- await logActivity(db, {
- companyId: connection.companyId,
- actorType: actor?.actorType ?? "system",
- actorId: actor?.actorId ?? "system",
- action: "tool_connection.install_access_extended",
- entityType: "tool_connection",
- entityId: connection.id,
- details: extension,
- });
- }
- return {
+ await tx
+ .select({ id: connectionGrants.id })
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.id, grant.id),
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ ),
+ )
+ .for("update");
+ const existingUserSet = new Set(existingUserIds);
+ if (requested.length === existingUserSet.size && requested.every(id => existingUserSet.has(id))) return existingAudience;
+ await tx
+ .delete(connectionGrantMembers)
+ .where(
+ and(
+ eq(connectionGrantMembers.companyId, connection.companyId),
+ eq(connectionGrantMembers.grantId, grant.id),
+ ),
+ );
+ const inserted =
+ requested.length === 0
+ ? []
+ : await tx
+ .insert(connectionGrantMembers)
+ .values(
+ requested.map((subjectId) => ({
+ companyId: connection.companyId,
+ grantId: grant.id,
+ subjectType: "user" as const,
+ subjectId,
+ })),
+ )
+ .returning();
+ await tx
+ .update(connectionGrants)
+ .set({ updatedAt: new Date() })
+ .where(eq(connectionGrants.id, grant.id));
+ return inserted;
+ });
+ await db.insert(toolAccessAuditEvents).values({
+ companyId: connection.companyId,
connectionId: connection.id,
- installs: await listConnectionInstalls(
- connection.id,
- connection.companyId,
- ),
- };
+ actorType: binding.actorType ?? "system",
+ actorId: binding.actorId,
+ action: "connection_grant.audience_replaced",
+ outcome: "success",
+ reasonCode: "audience_replaced",
+ details: {
+ grantId: grant.id,
+ memberCount: members.length,
+ memberUserIds: requested,
+ },
+ });
+ return { ...toConnectionGrant(grant), members };
},
- updateConnection: async (
- connectionId: string,
- input: UpdateToolConnection,
- ): Promise<ToolConnection> => {
- const existing = await getConnectionRow(connectionId);
- if (existing.connectionPurpose === "ai" && (input.config || input.transportConfig || input.credentialRefs || input.credentialSecretRefs || (input.credentialPolicy && input.credentialPolicy !== existing.credentialPolicy))) throw badRequest("Use AI account reconnect to change credentials. Provider, sign-in method, and ownership cannot be changed.");
- const config = normalizeGoogleSheetsConnectionConfig(
- input.config ?? input.transportConfig ?? existing.config,
- );
- if (input.config?.methodConfig !== undefined && typeof config.sourceTemplateKey === "string") {
- const app = getConnectableAppDefinition(config.sourceTemplateKey);
- if (app) normalizeConnectionMethodConfig(connectionMethodForConnection(app, { ...existing, config }), asRecord(config.methodConfig));
+ createConnectionGrantDelegation: async (
+ idOrUid: string,
+ grantId: string,
+ agentId: string,
+ ownerUserId: string,
+ ) => {
+ const connection = await getConnectionRow(idOrUid);
+ if (connection.connectionPurpose === "ai") {
+ throw badRequest("AI credentials use the connection's human access settings, not agent delegation");
}
- if (existing.transport === "mcp_remote")
- await assertRemoteConnectionEndpointsAllowed(config);
- if (existing.transport === "local_stdio")
- await stdioTemplateId(existing.companyId, config);
- assertLocalStdioCanBeEnabled(
- existing.transport,
- input.enabled ?? existing.enabled,
- config,
- );
- await assertGoogleSheetsSpreadsheetOwnership(existing.companyId, config, {
- excludeConnectionId: existing.id,
- });
- await assertSecretRefs(existing.companyId, [
- ...(input.credentialRefs ?? existing.credentialRefs),
- ...(input.credentialSecretRefs ?? existing.credentialSecretRefs),
- ]);
- const write = (database: Db) => database
- .update(toolConnections)
- .set({
- name: input.name ?? existing.name,
- status: input.status ?? existing.status,
- enabled: input.enabled ?? existing.enabled,
- ...(input.agentInstructions !== undefined ? { agentInstructions: input.agentInstructions } : {}),
- config,
- transportConfig: isGoogleSheetsConnectionConfig(config)
- ? config
- : (input.transportConfig ?? config),
- credentialRefs: input.credentialRefs ?? existing.credentialRefs,
- credentialSecretRefs:
- input.credentialSecretRefs ?? existing.credentialSecretRefs,
- credentialPolicy: input.credentialPolicy ?? existing.credentialPolicy,
- updatedAt: new Date(),
- })
- .where(eq(toolConnections.id, connectionId))
- .returning();
- const [row] = existing.transport === "chat_sdk"
- ? await db.transaction(async tx => {
- await notifyChatEndpointWork(tx, existing.id);
- const rows = await write(tx as unknown as Db);
- // Credential resolution must never observe the binding rebuild's
- // delete/insert gap after a configuration wake.
- await syncCredentialBindings(rows[0]!, [], tx);
- return rows;
+ return db.transaction(async (tx) => {
+ // Membership removal/suspension takes this same row lock before sweeping
+ // personal grants. Whichever operation wins is therefore authoritative:
+ // removal deletes a delegation committed first, while creation that runs
+ // second observes the inactive membership and fails closed.
+ const [membership] = await tx
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, connection.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, ownerUserId),
+ eq(companyMemberships.status, "active"),
+ ),
+ )
+ .for("update")
+ .limit(1);
+ if (!membership) {
+ throw forbidden(
+ "Only an active company member can delegate their personal grant",
+ );
+ }
+
+ const [grant] = await tx
+ .select()
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.id, grantId),
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "user"),
+ eq(connectionGrants.subjectUserId, ownerUserId),
+ eq(connectionGrants.status, "active"),
+ ),
+ )
+ .for("update")
+ .limit(1);
+ if (!grant)
+ throw forbidden(
+ "Only the active personal grant owner can create a delegation",
+ );
+ await tx.select({ id: toolConnections.id }).from(toolConnections)
+ .where(eq(toolConnections.id, connection.id)).for("key share");
+ const [targetAgent] = await tx
+ .select({ id: agents.id })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.id, agentId),
+ eq(agents.companyId, connection.companyId),
+ ),
+ )
+ .for("no key update")
+ .limit(1);
+ if (!targetAgent) throw notFound("Agent not found");
+ const [existing] = await tx
+ .select()
+ .from(connectionGrantDelegations)
+ .where(
+ and(
+ eq(connectionGrantDelegations.grantId, grant.id),
+ eq(connectionGrantDelegations.agentId, agentId),
+ ),
+ )
+ .limit(1);
+ if (existing) return existing;
+ const [delegation] = await tx
+ .insert(connectionGrantDelegations)
+ .values({
+ companyId: connection.companyId,
+ grantId: grant.id,
+ agentId,
+ createdByUserId: ownerUserId,
})
- : await write(db);
- if (existing.transport !== "chat_sdk") await syncCredentialBindings(row);
- await ensureRuntimeSlot(row);
- emitConnectionUpdated(row, existing, "api");
- return toConnection(row);
+ .returning();
+ await tx.insert(toolAccessAuditEvents).values({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ actorType: "user",
+ actorId: ownerUserId,
+ action: "connection_grant.delegated",
+ outcome: "success",
+ reasonCode: "delegation_created",
+ details: { grantId: grant.id, delegationId: delegation!.id, agentId },
+ });
+ return delegation!;
+ });
},
- archiveConnection: removeConnection,
-
- checkHealth: checkConnectionHealth,
-
- refreshCatalog,
-
- configureRailwaySsh: async (connectionId: string, companyId: string, input: ConfigureRailwaySsh, actor: ActorInfo): Promise<RailwaySshSetup | null> => {
- const knownHosts = input.action === "enable" ? validateRailwayKnownHosts(input.knownHosts) : "";
- const setup = await db.transaction(async (tx) => {
- const [grant] = await tx.select().from(connectionGrants).where(and(eq(connectionGrants.id, input.grantId), eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.companyId, companyId))).for("update");
- const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, companyId))).for("update");
- if (!connection || !isRailwayConnection(connection) || (connection.status !== "active" && input.action !== "remove")) throw unprocessable("Connect Railway before configuring container access.");
- if (!grant || (grant.status !== "active" && input.action !== "remove")) throw unprocessable("Select an active Railway authorization.");
- if (grant.kind === "user" && (actor.actorType !== "user" || actor.actorId !== grant.subjectUserId)) throw forbidden("Only this authorization's owner can configure its SSH key.");
- const existing = asRecord(connection.config.railwaySsh);
- if (existing.grantId && existing.grantId !== grant.id) throw conflict("Remove the existing container key before choosing another authorization.");
- const currentRef = grant.credentialSecretRefs.find((ref) => ref.configPath === RAILWAY_SSH_SECRET_PATH);
- let next: RailwaySshSetup | null = null;
- let refs = grant.credentialSecretRefs;
- if (input.action === "remove") {
- if (currentRef) await secretService(tx).remove(currentRef.secretId);
- refs = refs.filter((ref) => ref.configPath !== RAILWAY_SSH_SECRET_PATH);
- } else if (input.action === "prepare") {
- if (currentRef && typeof existing.publicKey === "string") return existing as unknown as RailwaySshSetup;
- const key = await generateRailwaySshKey();
- const ref = await createOrRotateOAuthSecret({ companyId, connection, configPath: RAILWAY_SSH_SECRET_PATH, label: "Railway container SSH key", value: key.privateKey, existingRefs: [], ownerUserId: grant.kind === "user" ? grant.subjectUserId ?? undefined : undefined, actor }, { dbClient: tx, secretClient: secretService(tx) });
- refs = [...refs.filter((ref) => ref.configPath !== RAILWAY_SSH_SECRET_PATH), ref];
- next = { grantId: grant.id, publicKey: key.publicKey, knownHosts: "", enabled: false };
- } else {
- if (!currentRef || typeof existing.publicKey !== "string") throw unprocessable("Generate and register a container key first.");
- next = { grantId: grant.id, publicKey: existing.publicKey, knownHosts, enabled: true };
- }
- await tx.update(connectionGrants).set({ credentialSecretRefs: refs, updatedAt: now() }).where(and(eq(connectionGrants.id, grant.id), eq(connectionGrants.companyId, companyId)));
- const config = { ...connection.config, railwaySsh: next };
- const [updated] = await tx.update(toolConnections).set({ config, transportConfig: config, updatedAt: now() }).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, companyId))).returning();
- await syncCredentialBindings(updated, [], tx);
- return next;
+ revokeConnectionGrantDelegation: async (
+ idOrUid: string,
+ grantId: string,
+ delegationId: string,
+ actor?: ActorInfo,
+ ) => {
+ const connection = await getConnectionRow(idOrUid);
+ const delegation = await db.transaction(async tx => {
+ const [grant] = await tx.select({ id: connectionGrants.id }).from(connectionGrants)
+ .where(and(eq(connectionGrants.id, grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id)))
+ .for("update");
+ if (!grant) return undefined;
+ const [target] = await tx.select({ agentId: connectionGrantDelegations.agentId }).from(connectionGrantDelegations)
+ .where(and(eq(connectionGrantDelegations.id, delegationId), eq(connectionGrantDelegations.companyId, connection.companyId), eq(connectionGrantDelegations.grantId, grantId)));
+ if (!target) return undefined;
+ await tx.select({ id: agents.id }).from(agents)
+ .where(and(eq(agents.companyId, connection.companyId), eq(agents.id, target.agentId))).for("no key update");
+ const [removed] = await tx
+ .delete(connectionGrantDelegations)
+ .where(
+ and(
+ eq(connectionGrantDelegations.id, delegationId),
+ eq(connectionGrantDelegations.companyId, connection.companyId),
+ eq(connectionGrantDelegations.grantId, grantId),
+ ),
+ )
+ .returning();
+ return removed;
+ });
+ if (!delegation) throw notFound("Connection grant delegation not found");
+ const binding = actorBinding(actor);
+ await db.insert(toolAccessAuditEvents).values({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ actorType: binding.actorType ?? "system",
+ actorId: binding.actorId,
+ action: "connection_grant.delegation_revoked",
+ outcome: "success",
+ reasonCode: "delegation_revoked",
+ details: { grantId, delegationId, agentId: delegation.agentId },
});
- await audit({ companyId, connectionId, action: "tool_connection.railway_ssh_updated", outcome: "success", actor, details: { action: input.action, grantId: input.grantId, enabled: setup?.enabled ?? false } });
- return setup;
+ return delegation;
},
- listAppsNeedingAttention,
-
- sweepConnectionHealth,
-
- sweepGitHubConnectionContinuity,
-
- listCatalog: async (
- connectionId: string,
- companyId?: string,
+ addConnectionInstallation: async (
+ idOrUid: string,
+ input: {
+ providerTenant?: { name?: string; externalId?: string };
+ credentialSecretRefs?: typeof connectionGrants.$inferInsert.credentialSecretRefs;
+ isDefault?: boolean;
+ },
actor?: ActorInfo,
- ): Promise<ToolCatalogEntry[]> => {
- const connection = await getConnectionRow(connectionId, companyId);
- let rows = await db
- .select()
- .from(toolCatalogEntries)
- .where(eq(toolCatalogEntries.connectionId, connection.id))
- .orderBy(desc(toolCatalogEntries.updatedAt));
- // Native provider catalogs change with the deployed code. Upgrade saved
- // Daytona connections too; their first small catalog must not survive
- // merely because REST discovery has no remote MCP cache timer.
- const nativeDaytona = isDaytonaConnection(connection);
- const rowsByName = new Map(rows.map((row) => [row.toolName, row]));
- const daytonaCatalogChanged = nativeDaytona && connection.status === "active" && (
- rows.some((row) => row.status !== "removed" && !isDaytonaToolName(row.toolName))
- || DAYTONA_TOOLS.some((tool) => {
- const existing = rowsByName.get(tool.name);
- return !existing || existing.versionHash !== descriptorHash(tool, daytonaRisk(tool.name));
- })
+ ) => {
+ const connection = await getConnectionRow(idOrUid);
+ await assertSecretRefs(
+ connection.companyId,
+ input.credentialSecretRefs ?? [],
);
- const cacheExpired = daytonaCatalogChanged || (
- connection.transport === "mcp_remote" &&
- connection.status !== "archived" &&
- (rows.length === 0 ||
- !connection.lastCatalogRefreshAt ||
- connection.lastCatalogRefreshAt.getTime() <=
- now().getTime() - catalogCacheTtlMs));
- if (cacheExpired) {
- try {
- await singleFlight(catalogRefreshFlights, connection.id, () =>
- refreshCatalog(connection.id, nativeDaytona && actor ? actor : {
- actorType: "system",
- actorId: "tool_catalog_cache",
- }),
+ if (input.isDefault) {
+ await db
+ .update(connectionGrants)
+ .set({ isDefault: false, updatedAt: new Date() })
+ .where(
+ and(
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "organization"),
+ ),
);
- rows = await db
- .select()
- .from(toolCatalogEntries)
- .where(eq(toolCatalogEntries.connectionId, connection.id))
- .orderBy(desc(toolCatalogEntries.updatedAt));
- } catch (error) {
- // A stale catalog remains useful when the remote server is temporarily
- // unavailable. Empty caches still fail so callers never mistake “no
- // actions discovered” for a successful lookup.
- if (rows.length === 0) throw error;
- }
}
- // Even failed discovery must not keep retired native tools visible.
- // Their database rows remain available to historical invocation records.
- return rows
- .filter((row) => !nativeDaytona || (row.status !== "removed" && isDaytonaToolName(row.toolName)))
- .map((row) => toCatalogEntryForConnection(row, connection));
- },
-
- /** Recent tool-call events for one connection — drives App detail · Recent activity. */
- listConnectionActivity: async (
- connectionId: string,
- companyId?: string,
- limit = 20,
- ): Promise<ToolConnectionActivityResponse> => {
- const connection = await getConnectionRow(connectionId, companyId);
- const safeLimit = Math.max(1, Math.min(100, Math.floor(limit)));
- const rows = await db
- .select()
- .from(toolCallEvents)
- .where(
- and(
- eq(toolCallEvents.companyId, connection.companyId),
- eq(toolCallEvents.connectionId, connection.id),
- ),
- )
- .orderBy(desc(toolCallEvents.createdAt))
- .limit(safeLimit);
- const events = rows.map(toToolCallEvent);
-
- const issueIds = [
- ...new Set(rows.map((row) => row.issueId).filter(Boolean)),
- ] as string[];
- const issueRows = issueIds.length
- ? await db
- .select({
- id: issues.id,
- identifier: issues.identifier,
- title: issues.title,
- })
- .from(issues)
- .where(
- and(
- eq(issues.companyId, connection.companyId),
- inArray(issues.id, issueIds),
- ),
- )
- : [];
- const issueMap = Object.fromEntries(
- issueRows.map((issue) => [
- issue.id,
- {
- identifier: issue.identifier ?? issue.id,
- title: issue.title,
- },
- ]),
- );
-
- const actionRequestIds = [
- ...new Set(rows.map((row) => row.actionRequestId).filter(Boolean)),
- ] as string[];
- const requestRows = actionRequestIds.length
- ? await db
- .select({
- id: toolActionRequests.id,
- status: toolActionRequests.status,
- resolvedByAgentId: toolActionRequests.resolvedByAgentId,
- resolvedByUserId: toolActionRequests.resolvedByUserId,
- })
- .from(toolActionRequests)
- .where(
- and(
- eq(toolActionRequests.companyId, connection.companyId),
- inArray(toolActionRequests.id, actionRequestIds),
- ),
- )
- : [];
-
- const resolverAgentIds = [
- ...new Set(
- requestRows.map((row) => row.resolvedByAgentId).filter(Boolean),
- ),
- ] as string[];
- const resolverUserIds = [
- ...new Set(
- requestRows.map((row) => row.resolvedByUserId).filter(Boolean),
- ),
- ] as string[];
- const resolverAgents = resolverAgentIds.length
- ? await db
- .select({ id: agents.id, name: agents.name })
- .from(agents)
- .where(
- and(
- eq(agents.companyId, connection.companyId),
- inArray(agents.id, resolverAgentIds),
- ),
- )
- : [];
- const resolverUsers = resolverUserIds.length
- ? await db
- .select({
- id: authUsers.id,
- name: authUsers.name,
- email: authUsers.email,
- })
- .from(authUsers)
- .where(inArray(authUsers.id, resolverUserIds))
- : [];
- const resolverAgentNames = new Map(
- resolverAgents.map((agent) => [agent.id, agent.name]),
- );
- const resolverUserNames = new Map(
- resolverUsers.map((user) => [
- user.id,
- user.name?.trim() || user.email?.trim() || user.id,
- ]),
- );
- const actionRequestMap = Object.fromEntries(
- requestRows.map((request) => [
- request.id,
- {
- status: request.status,
- resolverDisplayName: request.resolvedByAgentId
- ? (resolverAgentNames.get(request.resolvedByAgentId) ??
- request.resolvedByAgentId)
- : request.resolvedByUserId
- ? (resolverUserNames.get(request.resolvedByUserId) ??
- userFallbackName(request.resolvedByUserId))
- : null,
- resolvedByAgentId: request.resolvedByAgentId,
- resolvedByUserId: request.resolvedByUserId,
- },
- ]),
- );
-
- const lifecycleEvents = await listConnectionLifecycleEvents(db, {
+ const binding = actorBinding(actor);
+ const [grant] = await db
+ .insert(connectionGrants)
+ .values({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ kind: "organization",
+ providerTenant: input.providerTenant,
+ credentialSecretRefs: input.credentialSecretRefs ?? [],
+ status: "active",
+ isDefault: input.isDefault ?? false,
+ createdByAgentId:
+ binding.actorType === "agent" ? binding.actorId : null,
+ createdByUserId:
+ binding.actorType === "user" ? binding.actorId : null,
+ })
+ .returning();
+ if (!grant) throw new Error("Failed to create connection installation");
+ await db.insert(toolAccessAuditEvents).values({
companyId: connection.companyId,
- connectionIds: [connection.id],
- limit: safeLimit,
- });
-
- return {
connectionId: connection.id,
- events,
- lifecycleEvents,
- issues: issueMap,
- actionRequests: actionRequestMap,
- };
+ actorType: binding.actorType ?? "system",
+ actorId: binding.actorId,
+ action: "connection_grant.created",
+ outcome: "success",
+ reasonCode: "grant_created",
+ details: {
+ grantId: grant.id,
+ kind: grant.kind,
+ isDefault: grant.isDefault,
+ },
+ });
+ return toConnectionGrant(grant);
},
- /**
- * List "Ask first" action requests for the review queue, enriched with the
- * connection/app context the prosumer card renders. Defaults to pending.
- */
- listActionRequests: async (
- companyId: string,
- status: ToolActionRequestStatus = "pending",
- ): Promise<ToolActionRequestListItem[]> => {
- const requests = await db
+ revokeConnectionGrant: async (
+ idOrUid: string,
+ grantId: string,
+ actor?: ActorInfo,
+ ) => {
+ const connection = await getConnectionRow(idOrUid);
+ const binding = actorBinding(actor);
+ const [currentGrant] = await db
.select()
- .from(toolActionRequests)
+ .from(connectionGrants)
.where(
and(
- eq(toolActionRequests.companyId, companyId),
- eq(toolActionRequests.status, status),
+ eq(connectionGrants.id, grantId),
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
),
)
- .orderBy(desc(toolActionRequests.createdAt));
- if (requests.length === 0) return [];
+ .limit(1);
+ if (!currentGrant) throw notFound("Connection grant not found");
+ let providerRevocation = "not_applicable";
+ if (
+ connection.credentialSource === "vercel_connect" &&
+ connection.externalCredential
+ ) {
+ const request = vercelTokenRequest({
+ credential: connection.externalCredential,
+ grant: currentGrant,
+ connectionId: connection.id,
+ companyId: connection.companyId,
+ resources: vercelConnectResourcesFor(connection),
+ });
+ vercelConnect?.evict(request);
+ if (currentGrant.externalCredential?.subjectType === "app") {
+ providerRevocation = "manage_in_vercel";
+ } else if (currentGrant.externalCredential?.subjectType === "user") {
+ try {
+ if (!vercelConnect) throw new Error("Vercel Connect unavailable");
+ await vercelConnect.revoke(request);
+ providerRevocation = "success";
+ } catch {
+ providerRevocation = "failed";
+ }
+ }
+ } else if (
+ isPaperclipCloudConnectorStrategy(oauthConfig(connection).strategy)
+ ) {
+ // Google revocation is client-wide for a user. The managed Workspace
+ // profiles intentionally share one Paperclip-owned client, so revoking
+ // one token here could invalidate unrelated Gmail, Drive, and Calendar
+ // grants. A per-profile removal is therefore local-only. A future
+ // provider-level disconnect must warn that it removes every profile.
+ providerRevocation = "local_only_shared_client";
+ }
+ const grant = await db.transaction(async (tx) => {
+ const [lockedGrant] = await tx.select({ id: connectionGrants.id }).from(connectionGrants)
+ .where(and(eq(connectionGrants.id, grantId), eq(connectionGrants.companyId, connection.companyId), eq(connectionGrants.connectionId, connection.id)))
+ .for("update");
+ if (!lockedGrant) throw notFound("Connection grant not found");
+ await tx.select({ id: agents.id }).from(agents)
+ .where(and(eq(agents.companyId, connection.companyId), notInArray(agents.status, ["pending_approval", "terminated"])))
+ .orderBy(agents.id).for("no key update");
+ const removedDelegations = await tx
+ .delete(connectionGrantDelegations)
+ .where(
+ and(
+ eq(connectionGrantDelegations.companyId, connection.companyId),
+ eq(connectionGrantDelegations.grantId, grantId),
+ ),
+ )
+ .returning();
+ const [updated] = await tx
+ .update(connectionGrants)
+ .set({
+ status: "revoked",
+ isDefault: false,
+ revokedAt: new Date(),
+ revokedByAgentId:
+ binding.actorType === "agent" ? binding.actorId : null,
+ revokedByUserId:
+ binding.actorType === "user" ? binding.actorId : null,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(connectionGrants.id, grantId),
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ ),
+ )
+ .returning();
+ if (!updated) throw notFound("Connection grant not found");
+ if (removedDelegations.length > 0) {
+ await tx.insert(toolAccessAuditEvents).values(
+ removedDelegations.map((delegation) => ({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ actorType: binding.actorType ?? "system",
+ actorId: binding.actorId,
+ action: "connection_grant.delegation_revoked",
+ outcome: "success",
+ reasonCode: "grant_revoked",
+ details: {
+ grantId,
+ delegationId: delegation.id,
+ agentId: delegation.agentId,
+ },
+ })),
+ );
+ }
+ return updated;
+ });
+ if (!grant) throw notFound("Connection grant not found");
+ await db.insert(toolAccessAuditEvents).values({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ actorType: binding.actorType ?? "system",
+ actorId: binding.actorId,
+ action: "connection_grant.revoked",
+ outcome: "success",
+ reasonCode: "grant_revoked",
+ details: { grantId: grant.id, kind: grant.kind, providerRevocation },
+ });
+ return toConnectionGrant(grant);
+ },
- const invocationIds = [
- ...new Set(requests.map((request) => request.invocationId)),
- ];
- const invocations = await db
- .select()
- .from(toolInvocations)
- .where(
- and(
- eq(toolInvocations.companyId, companyId),
- inArray(toolInvocations.id, invocationIds),
+ getConnectionUsage: async (
+ idOrUid: string,
+ range: "7d" | "30d",
+ companyId?: string,
+ ) => {
+ const connection = await getConnectionRow(idOrUid, companyId);
+ const days = range === "30d" ? 30 : 7;
+ const start = new Date();
+ start.setUTCHours(0, 0, 0, 0);
+ start.setUTCDate(start.getUTCDate() - days + 1);
+ const [issuances, invocations] = await Promise.all([
+ db
+ .select({
+ createdAt: connectionTokenIssuances.createdAt,
+ outcome: connectionTokenIssuances.outcome,
+ path: connectionTokenIssuances.path,
+ })
+ .from(connectionTokenIssuances)
+ .where(
+ and(
+ eq(connectionTokenIssuances.companyId, connection.companyId),
+ eq(connectionTokenIssuances.connectionId, connection.id),
+ gte(connectionTokenIssuances.createdAt, start),
+ ),
),
- );
- const invocationById = new Map(
- invocations.map((invocation) => [invocation.id, invocation]),
- );
- let visibleRequests = requests;
- if (status === "pending") {
- // A pending request that the creator has not signed yet is still being
- // set up. The gateway creates the row (signedArguments = null) and signs
- // it in a second step, so a review-queue read can observe the row inside
- // that window. Hide such a request from the queue, but do not cancel it —
- // cancelling here races the two-step create and makes the later approve
- // fail with action_not_pending. Only cancel a request that carries a
- // signature we cannot verify (secret rotation or tampering), or an
- // unsigned row whose creator has exceeded the signing grace period.
- const unsignedRequestIds = new Set<string>();
- const invalidRequestIds: string[] = [];
- for (const request of requests) {
- const invocation = invocationById.get(request.invocationId);
- if (!invocation) {
- invalidRequestIds.push(request.id);
- continue;
- }
- if (request.signedArguments === null) {
- if (
- Date.now() - request.createdAt.getTime() >=
- TOOL_ACTION_REQUEST_SIGNING_GRACE_MS
- ) {
- invalidRequestIds.push(request.id);
- } else {
- unsignedRequestIds.add(request.id);
- }
- continue;
- }
- let readable = false;
- try {
- readable = Boolean(
- readSignedToolArgumentsPayload({
- signedArguments: request.signedArguments,
- invocationId: invocation.id,
- toolName: invocation.toolName,
- }),
+ db
+ .select({
+ createdAt: toolInvocations.createdAt,
+ riskLevel: toolInvocations.riskLevel,
+ })
+ .from(toolInvocations)
+ .where(
+ and(
+ eq(toolInvocations.companyId, connection.companyId),
+ eq(toolInvocations.connectionId, connection.id),
+ gte(toolInvocations.createdAt, start),
+ ),
+ ),
+ ]);
+ const buckets = Array.from({ length: days }, (_, offset) => {
+ const date = new Date(start);
+ date.setUTCDate(start.getUTCDate() + offset);
+ return {
+ date: date.toISOString().slice(0, 10),
+ issuances: {
+ total: 0,
+ byOutcome: {} as Record<string, number>,
+ byPath: {} as Record<string, number>,
+ },
+ invocations: { total: 0, byRiskLevel: {} as Record<string, number> },
+ deliveries: { received: 0, forwarded: 0 },
+ };
+ });
+ const byDate = new Map(buckets.map((bucket) => [bucket.date, bucket]));
+ for (const row of issuances) {
+ const bucket = byDate.get(row.createdAt.toISOString().slice(0, 10));
+ if (!bucket) continue;
+ bucket.issuances.total += 1;
+ bucket.issuances.byOutcome[row.outcome] =
+ (bucket.issuances.byOutcome[row.outcome] ?? 0) + 1;
+ bucket.issuances.byPath[row.path] =
+ (bucket.issuances.byPath[row.path] ?? 0) + 1;
+ }
+ for (const row of invocations) {
+ const bucket = byDate.get(row.createdAt.toISOString().slice(0, 10));
+ if (!bucket) continue;
+ const riskLevel = row.riskLevel ?? "unknown";
+ bucket.invocations.total += 1;
+ bucket.invocations.byRiskLevel[riskLevel] =
+ (bucket.invocations.byRiskLevel[riskLevel] ?? 0) + 1;
+ }
+ return {
+ connection: { id: connection.id, uid: connection.uid },
+ range,
+ buckets,
+ };
+ },
+
+ listConnectionInstalls,
+
+ putConnectionInstalls: async (
+ connectionId: string,
+ input: PutToolConnectionInstalls,
+ actor?: ActorInfo,
+ ): Promise<ToolConnectionInstallSnapshot> => {
+ const connection = await getConnectionRow(connectionId);
+ const requested = new Map(
+ input.installs.map((install) => [
+ `${install.targetType}:${install.targetId}`,
+ install,
+ ]),
+ );
+ for (const install of requested.values()) {
+ if (install.targetType === "company") {
+ if (install.targetId !== connection.companyId)
+ throw unprocessable(
+ "Company installs must target the connection company",
);
- } catch {
- readable = false;
- }
- if (!readable) invalidRequestIds.push(request.id);
+ } else {
+ await assertOptionalAgent(
+ connection.companyId,
+ install.targetId,
+ "Tool connection install agent",
+ );
}
- if (invalidRequestIds.length > 0) {
- await db
- .update(toolActionRequests)
- .set({
- status: "cancelled",
- resolvedAt: new Date(),
- updatedAt: new Date(),
- })
+ }
+ const markMcpAccessConfigured = connection.transport === "mcp_remote"
+ && connection.config.mcpAgentAccessConfigured !== true;
+ const accessExtensions: Array<{
+ targetType: "company" | "agent";
+ targetId: string;
+ profileId: string;
+ }> = [];
+ await db.transaction(async (tx) => {
+ await lockToolConnectionRuntimeInputs(tx, connection.companyId, connection.id);
+ if (markMcpAccessConfigured) {
+ // Preserve an explicit zero-agent selection through OAuth. Merge the
+ // marker in SQL so concurrent credential/config changes are retained.
+ await tx.update(toolConnections).set({
+ config: sql`${toolConnections.config} || '{"mcpAgentAccessConfigured":true}'::jsonb`,
+ transportConfig: sql`${toolConnections.transportConfig} || '{"mcpAgentAccessConfigured":true}'::jsonb`,
+ updatedAt: now(),
+ }).where(and(
+ eq(toolConnections.companyId, connection.companyId),
+ eq(toolConnections.id, connection.id),
+ ));
+ }
+ const existing = await tx
+ .select()
+ .from(toolConnectionInstalls)
+ .where(
+ and(
+ eq(toolConnectionInstalls.companyId, connection.companyId),
+ eq(toolConnectionInstalls.connectionId, connection.id),
+ ),
+ );
+ const existingKeys = new Set(
+ existing.map(
+ (install) => `${install.targetType}:${install.targetId}`,
+ ),
+ );
+ const bindings = await tx.select({ targetType: toolProfileBindings.targetType, targetId: toolProfileBindings.targetId })
+ .from(toolProfileBindings).innerJoin(toolProfiles, eq(toolProfiles.id, toolProfileBindings.profileId))
+ .where(and(eq(toolProfileBindings.companyId, connection.companyId), eq(toolProfiles.companyId, connection.companyId), eq(toolProfiles.profileKey, `app:${connection.id}`)));
+ await lockToolAssignmentAgents(tx, connection.companyId, [...existing, ...requested.values(), ...bindings]);
+ const removals = existing.filter(
+ (install) =>
+ !requested.has(`${install.targetType}:${install.targetId}`),
+ );
+ const removeIds = removals.map((install) => install.id);
+ if (removeIds.length > 0) {
+ await tx
+ .delete(toolConnectionInstalls)
+ .where(inArray(toolConnectionInstalls.id, removeIds));
+ // Uninstalling must also drop the binding this path created. Installing
+ // writes both an install row and a profile binding, so deleting only the
+ // install row leaves a binding that no surface can see or remove. The
+ // install row is the reach gate (`mintConnectionTokenForAgent` fails with
+ // `installation_required`, and the heartbeat only hands over installed
+ // connections), so a stale binding grants no reach on its own — but it
+ // still makes `finishApp`, which rebuilds `access` from the bindings,
+ // read a target the operator already removed.
+ //
+ // Only bindings tagged `source: "tool_connection_install"` are removed.
+ // A binding the operator authored through the access model carries a
+ // different source and must survive an uninstall.
+ const [installProfile] = await tx
+ .select({ id: toolProfiles.id })
+ .from(toolProfiles)
.where(
and(
- eq(toolActionRequests.companyId, companyId),
- eq(toolActionRequests.status, "pending"),
- inArray(toolActionRequests.id, invalidRequestIds),
+ eq(toolProfiles.companyId, connection.companyId),
+ eq(toolProfiles.profileKey, `app:${connection.id}`),
),
- );
+ )
+ .limit(1);
+ if (installProfile) {
+ for (const install of removals) {
+ await tx
+ .delete(toolProfileBindings)
+ .where(
+ and(
+ eq(toolProfileBindings.companyId, connection.companyId),
+ eq(toolProfileBindings.profileId, installProfile.id),
+ eq(toolProfileBindings.targetType, install.targetType),
+ eq(toolProfileBindings.targetId, install.targetId),
+ sql`${toolProfileBindings.metadata}->>'source' = 'tool_connection_install'`,
+ ),
+ );
+ }
+ }
}
- const hiddenIds = new Set([
- ...invalidRequestIds,
- ...unsignedRequestIds,
- ]);
- if (hiddenIds.size > 0) {
- visibleRequests = requests.filter(
- (request) => !hiddenIds.has(request.id),
+ const additions = [...requested.entries()]
+ .filter(([key]) => !existingKeys.has(key))
+ .map(([, install]) => install);
+ if (additions.length > 0) {
+ await tx.insert(toolConnectionInstalls).values(
+ additions.map((install) => ({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ targetType: install.targetType,
+ targetId: install.targetId,
+ createdByAgentId:
+ actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
+ createdByUserId:
+ actor?.actorType === "user" ? (actor.actorId ?? null) : null,
+ })),
);
}
- }
- if (visibleRequests.length === 0) return [];
-
- const visibleInvocations = visibleRequests
- .map((request) => invocationById.get(request.invocationId))
- .filter(
- (invocation): invocation is typeof toolInvocations.$inferSelect =>
- Boolean(invocation),
- );
- const connectionIds = [
- ...new Set(
- visibleInvocations
- .map((invocation) => invocation.connectionId)
- .filter(Boolean),
- ),
- ] as string[];
- const connections = connectionIds.length
- ? await db
- .select()
- .from(toolConnections)
- .where(inArray(toolConnections.id, connectionIds))
- : [];
- const connectionById = new Map(
- connections.map((connection) => [connection.id, connection]),
- );
-
- const applicationIds = [
- ...new Set(
- connections
- .map((connection) => connection.applicationId)
- .filter(Boolean),
- ),
- ] as string[];
- const applications = applicationIds.length
- ? await db
- .select()
- .from(toolApplications)
- .where(inArray(toolApplications.id, applicationIds))
- : [];
- const applicationById = new Map(
- applications.map((application) => [application.id, application]),
- );
-
- const catalogEntryIds = [
- ...new Set(
- visibleInvocations
- .map((invocation) => invocation.catalogEntryId)
- .filter(Boolean),
- ),
- ] as string[];
- const catalogEntries = catalogEntryIds.length
- ? await db
- .select()
- .from(toolCatalogEntries)
- .where(inArray(toolCatalogEntries.id, catalogEntryIds))
- : [];
- const catalogById = new Map(
- catalogEntries.map((entry) => [entry.id, entry]),
- );
-
- return visibleRequests.map((request) => {
- const invocation = invocationById.get(request.invocationId);
- const connection = invocation?.connectionId
- ? connectionById.get(invocation.connectionId)
- : undefined;
- const application = connection?.applicationId
- ? applicationById.get(connection.applicationId)
- : undefined;
- const catalogEntry = invocation?.catalogEntryId
- ? catalogById.get(invocation.catalogEntryId)
- : undefined;
- return {
- request: toToolActionRequest(request),
- toolName: invocation?.toolName ?? catalogEntry?.toolName ?? "",
- toolTitle: catalogEntry?.title ?? null,
- connectionId: connection?.id ?? invocation?.connectionId ?? null,
- connectionName: connection?.name ?? null,
- applicationName: application?.name ?? null,
- riskLevel: catalogEntry?.riskLevel ?? null,
- requestedByAgentId: request.requestedByAgentId ?? null,
- };
- });
- },
- ...profileService,
- ...profileResolver,
-
- mintConnectionTokenForAgent: async (input: {
- connectionId: string;
- companyId: string;
- agentId: string;
- runId: string;
- body: ConnectionTokenRequest;
- }): Promise<ConnectionTokenResponse> => {
- const runContext = await loadBrokerRunContext({
- companyId: input.companyId,
- agentId: input.agentId,
- runId: input.runId,
+ if (requested.size > 0 && connection.connectionPurpose !== "ai") {
+ const profile = await appProfileForConnection(tx, connection);
+ for (const install of requested.values()) {
+ const [binding] = await tx
+ .insert(toolProfileBindings)
+ .values({
+ companyId: connection.companyId,
+ profileId: profile.id,
+ targetType: install.targetType,
+ targetId: install.targetId,
+ priority: 100,
+ metadata: {
+ source: "tool_connection_install",
+ connectionId: connection.id,
+ },
+ createdByAgentId:
+ actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
+ createdByUserId:
+ actor?.actorType === "user" ? (actor.actorId ?? null) : null,
+ })
+ .onConflictDoNothing()
+ .returning({ id: toolProfileBindings.id });
+ if (binding)
+ accessExtensions.push({
+ targetType: install.targetType,
+ targetId: install.targetId,
+ profileId: profile.id,
+ });
+ }
+ }
+ if (markMcpAccessConfigured || removeIds.length > 0 || additions.length > 0) {
+ const binding = actorBinding(actor);
+ await tx.insert(toolAccessAuditEvents).values({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ actorType: binding.actorType ?? "system",
+ actorId: binding.actorId,
+ action: "connection_installs.changed",
+ outcome: "success",
+ reasonCode: "installs_changed",
+ details: {
+ ...(markMcpAccessConfigured ? { mcpAgentAccessConfigured: true } : {}),
+ added: additions.map((install) => ({
+ targetType: install.targetType,
+ targetId: install.targetId,
+ })),
+ removed: existing
+ .filter((install) => removeIds.includes(install.id))
+ .map((install) => ({
+ targetType: install.targetType,
+ targetId: install.targetId,
+ })),
+ },
+ });
+ }
});
- const connection = await getConnectionRow(
- input.connectionId,
- input.companyId,
- );
- if (isDaytonaConnection(connection)) throw forbidden("Daytona credentials stay in the governed tool gateway and cannot be exported.");
- if (isBrowserUseConnection(connection)) throw forbidden("Browser Use credentials stay in the governed tool gateway and cannot be exported.");
- if (connection.connectionPurpose === "ai") throw unprocessable("AI credentials are available only through the runtime resolver");
- const application = await getConnectionApplication(connection);
- const brokerEnabled = connectionTokenBrokerEnabled(connection);
- const path = brokerEnabled
- ? inferConnectionTokenPath(connection, application)
- : "static";
- const requestedScope = normalizeConnectionTokenScopes(input.body.scope);
- const parentScopes = parentScopesForConnection(connection);
- const fallbackScopes = defaultScopesForConnection(connection);
- const issuedScope =
- requestedScope.length > 0
- ? requestedScope
- : fallbackScopes.length > 0
- ? fallbackScopes
- : parentScopes;
- const ttlSeconds = requestedTtlSeconds(input.body, connection);
- const attribution = {
- agentId: input.agentId,
- runId: input.runId,
- issueId: runContext.issueId,
- projectId: runContext.projectId,
- responsibleUserId: runContext.responsibleUserId,
- };
-
- const recordFailure = async (
- outcome: ConnectionTokenIssuanceOutcome,
- errorCode: string,
- details: Record<string, unknown> = {},
- ) => {
- await recordConnectionTokenIssuance({
- companyId: connection.companyId,
- applicationId: connection.applicationId,
- connectionId: connection.id,
- agentId: input.agentId,
- runId: input.runId,
- issueId: runContext.issueId,
- projectId: runContext.projectId,
- responsibleUserId: runContext.responsibleUserId,
- path,
- requestedScope,
- issuedScope,
- ttlSeconds: outcome === "use_env_lease" ? null : ttlSeconds,
- expiresAt: null,
- tokenHash: null,
- outcome,
- errorCode,
- metadata: details,
- });
- await auditConnectionTokenIssuance({
+ for (const extension of accessExtensions) {
+ await logActivity(db, {
companyId: connection.companyId,
- connectionId: connection.id,
- agentId: input.agentId,
- runId: input.runId,
- path,
- outcome,
- reasonCode: errorCode,
- details,
- });
- };
-
- const fail = async (
- status: number,
- message: string,
- outcome: ConnectionTokenIssuanceOutcome,
- errorCode: string,
- details: Record<string, unknown> = {},
- ): Promise<never> => {
- await recordFailure(outcome, errorCode, details);
- throw new HttpError(status, message, {
- code: errorCode,
- path,
- ...details,
+ actorType: actor?.actorType ?? "system",
+ actorId: actor?.actorId ?? "system",
+ action: "tool_connection.install_access_extended",
+ entityType: "tool_connection",
+ entityId: connection.id,
+ details: extension,
});
+ }
+ return {
+ connectionId: connection.id,
+ installs: await listConnectionInstalls(
+ connection.id,
+ connection.companyId,
+ ),
};
+ },
- const [install] = await db
- .select({ id: toolConnectionInstalls.id })
- .from(toolConnectionInstalls)
- .where(
- and(
- eq(toolConnectionInstalls.companyId, connection.companyId),
- eq(toolConnectionInstalls.connectionId, connection.id),
- sql`((${toolConnectionInstalls.targetType} = 'company' and ${toolConnectionInstalls.targetId} = ${connection.companyId}) or (${toolConnectionInstalls.targetType} = 'agent' and ${toolConnectionInstalls.targetId} = ${input.agentId}))`,
- ),
- )
- .limit(1);
- if (!install) {
- await fail(
- 403,
- `Connection ${connection.name} must be installed for this agent before it can mint a token`,
- "denied",
- "installation_required",
- {
- connection: {
- id: connection.id,
- uid: connection.uid,
- name: connection.name,
- },
- agentId: input.agentId,
- remediation: {
- action: "install_connection",
- targetType: "agent",
- targetId: input.agentId,
- },
- },
- );
+ updateConnection: async (
+ connectionId: string,
+ input: UpdateToolConnection,
+ ): Promise<ToolConnection> => {
+ const existing = await getConnectionRow(connectionId);
+ if (existing.connectionPurpose === "ai" && (input.config || input.transportConfig || input.credentialRefs || input.credentialSecretRefs || (input.credentialPolicy && input.credentialPolicy !== existing.credentialPolicy))) throw badRequest("Use AI account reconnect to change credentials. Provider, sign-in method, and ownership cannot be changed.");
+ const config = normalizeGoogleSheetsConnectionConfig(
+ input.config ?? input.transportConfig ?? existing.config,
+ );
+ if (input.config?.methodConfig !== undefined && typeof config.sourceTemplateKey === "string") {
+ const app = getConnectableAppDefinition(config.sourceTemplateKey);
+ if (app) normalizeConnectionMethodConfig(connectionMethodForConnection(app, { ...existing, config }), asRecord(config.methodConfig));
}
+ if (existing.transport === "mcp_remote")
+ await assertRemoteConnectionEndpointsAllowed(config);
+ if (existing.transport === "local_stdio")
+ await stdioTemplateId(existing.companyId, config);
+ assertLocalStdioCanBeEnabled(
+ existing.transport,
+ input.enabled ?? existing.enabled,
+ config,
+ );
+ await assertGoogleSheetsSpreadsheetOwnership(existing.companyId, config, {
+ excludeConnectionId: existing.id,
+ });
+ await assertSecretRefs(existing.companyId, [
+ ...(input.credentialRefs ?? existing.credentialRefs),
+ ...(input.credentialSecretRefs ?? existing.credentialSecretRefs),
+ ]);
+ const write = (database: Db) => database
+ .update(toolConnections)
+ .set({
+ name: input.name ?? existing.name,
+ status: input.status ?? existing.status,
+ enabled: input.enabled ?? existing.enabled,
+ ...(input.agentInstructions !== undefined ? { agentInstructions: input.agentInstructions } : {}),
+ config,
+ transportConfig: isGoogleSheetsConnectionConfig(config)
+ ? config
+ : (input.transportConfig ?? config),
+ credentialRefs: input.credentialRefs ?? existing.credentialRefs,
+ credentialSecretRefs:
+ input.credentialSecretRefs ?? existing.credentialSecretRefs,
+ credentialPolicy: input.credentialPolicy ?? existing.credentialPolicy,
+ updatedAt: new Date(),
+ })
+ .where(eq(toolConnections.id, connectionId))
+ .returning();
+ const [row] = existing.transport === "chat_sdk"
+ ? await db.transaction(async tx => {
+ await notifyChatEndpointWork(tx, existing.id);
+ const rows = await write(tx as unknown as Db);
+ // Credential resolution must never observe the binding rebuild's
+ // delete/insert gap after a configuration wake.
+ await syncCredentialBindings(rows[0]!, [], tx);
+ return rows;
+ })
+ : await write(db);
+ if (existing.transport !== "chat_sdk") await syncCredentialBindings(row);
+ await ensureRuntimeSlot(row);
+ emitConnectionUpdated(row, existing, "api");
+ return toConnection(row);
+ },
- if (
- runContext.run.activeIdentityContextId &&
- (connection.config.sourceTemplateKey === "github" ||
- connection.transportConfig?.sourceTemplateKey === "github")
- ) {
- await fail(
- 409,
- "Use managed git, gh, or GitHub tools for this run",
- "denied",
- "managed_github_invocation_required",
- );
- }
- const requestedSubject = input.body.subject;
- if (
- requestedSubject?.type === "user" &&
- requestedSubject.userId !== runContext.responsibleUserId
- ) {
- await fail(
- 403,
- "The agent run cannot act as the requested user",
- "denied",
- "subject_not_permitted",
- {
- connection: { uid: connection.uid },
- subject: requestedSubject,
- },
- );
- }
+ archiveConnection: removeConnection,
- const actingUserId = runContext.responsibleUserId;
- const autonomous =
- runContext.run.invocationSource === "automation" ||
- runContext.run.invocationSource === "timer";
- let subject: { type: "app" } | { type: "user"; userId: string } =
- connection.credentialPolicy === "shared" ||
- connection.credentialPolicy === "per_agent" ||
- !actingUserId
- ? { type: "app" as const }
- : { type: "user" as const, userId: actingUserId };
- let grant: typeof connectionGrants.$inferSelect | undefined;
- if (connection.credentialPolicy === "per_agent") {
- [grant] = await db
- .select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "agent"),
- eq(connectionGrants.subjectAgentId, input.agentId),
- ),
- )
- .limit(1);
- if (!grant) {
- await fail(
- 409,
- "This agent's dedicated authorization is required",
- "denied",
- "agent_authorization_required",
- {
- connection: { uid: connection.uid },
- agentId: input.agentId,
- remediation: {
- action: "start_agent_authorization",
- agentId: input.agentId,
- },
- },
- );
- }
- } else if (connection.credentialPolicy !== "shared" && actingUserId) {
- // Installation targets express the grant owner's consent to agent use;
- // the control-plane-resolved responsible user selects whose grant is in
- // force. A separate standing delegation is required only when no such
- // responsible user exists for unattended work.
- const [membership] = await db
- .select({ id: companyMemberships.id })
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, connection.companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, actingUserId),
- eq(companyMemberships.status, "active"),
- ),
- )
- .limit(1);
- if (!membership) {
- await fail(
- 403,
- "The personal grant owner is not an active company member",
- "denied",
- "grant_owner_membership_inactive",
- {
- connection: {
- id: connection.id,
- uid: connection.uid,
- name: connection.name,
- },
- subject: { type: "user", userId: actingUserId },
- remediation: { action: "restore_membership_or_reconnect" },
- },
- );
- }
- [grant] = await db
- .select()
- .from(connectionGrants)
- .where(
- and(
- eq(connectionGrants.companyId, connection.companyId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "user"),
- eq(connectionGrants.subjectUserId, actingUserId),
- ),
- )
- .limit(1);
- } else if (connection.credentialPolicy === "per_user" && autonomous) {
- const delegated = await db
- .select({ grant: connectionGrants })
- .from(connectionGrantDelegations)
- .innerJoin(
- connectionGrants,
- and(
- eq(connectionGrants.id, connectionGrantDelegations.grantId),
- eq(
- connectionGrants.companyId,
- connectionGrantDelegations.companyId,
- ),
- ),
- )
- .where(
- and(
- eq(connectionGrantDelegations.companyId, connection.companyId),
- eq(connectionGrantDelegations.agentId, input.agentId),
- eq(connectionGrants.connectionId, connection.id),
- eq(connectionGrants.kind, "user"),
- ),
- )
- .limit(2);
- if (delegated.length > 1) {
- await fail(
- 409,
- "More than one delegated personal authorization matches this run",
- "denied",
- "subject_not_permitted",
- {
- connection: { uid: connection.uid },
- agentId: input.agentId,
- },
- );
- }
- grant = delegated[0]?.grant;
- if (grant?.subjectUserId)
- subject = { type: "user", userId: grant.subjectUserId };
- }
- if (!grant && connection.credentialPolicy === "per_user") {
- await fail(
- 409,
- "User authorization is required",
- "denied",
- "user_authorization_required",
- {
- connection: { uid: connection.uid },
- subject: actingUserId
- ? { type: "user", userId: actingUserId }
- : { type: "app" },
- remediation: { action: "start_authorization" },
- },
- );
- }
- if (!grant) {
- grant = await ensureDefaultOrganizationGrant(connection);
- }
+ checkHealth: checkConnectionHealth,
- if (
- grant.kind === "user" &&
- grant.subjectUserId &&
- grant.subjectUserId !== actingUserId
- ) {
- const [membership] = await db
- .select({ id: companyMemberships.id })
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, connection.companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, grant.subjectUserId),
- eq(companyMemberships.status, "active"),
- ),
- )
- .limit(1);
- if (!membership) {
- await fail(
- 403,
- "The delegated personal grant owner is not an active company member",
- "denied",
- "grant_owner_membership_inactive",
- {
- connection: {
- id: connection.id,
- uid: connection.uid,
- name: connection.name,
- },
- subject,
- remediation: { action: "restore_membership_or_reconnect" },
- },
- );
+ refreshCatalog,
+
+ configureRailwaySsh: async (connectionId: string, companyId: string, input: ConfigureRailwaySsh, actor: ActorInfo): Promise<RailwaySshSetup | null> => {
+ const knownHosts = input.action === "enable" ? validateRailwayKnownHosts(input.knownHosts) : "";
+ const setup = await db.transaction(async (tx) => {
+ const [grant] = await tx.select().from(connectionGrants).where(and(eq(connectionGrants.id, input.grantId), eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.companyId, companyId))).for("update");
+ const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, companyId))).for("update");
+ if (!connection || !isRailwayConnection(connection) || (connection.status !== "active" && input.action !== "remove")) throw unprocessable("Connect Railway before configuring container access.");
+ if (!grant || (grant.status !== "active" && input.action !== "remove")) throw unprocessable("Select an active Railway authorization.");
+ if (grant.kind === "user" && (actor.actorType !== "user" || actor.actorId !== grant.subjectUserId)) throw forbidden("Only this authorization's owner can configure its SSH key.");
+ const existing = asRecord(connection.config.railwaySsh);
+ if (existing.grantId && existing.grantId !== grant.id) throw conflict("Remove the existing container key before choosing another authorization.");
+ const currentRef = grant.credentialSecretRefs.find((ref) => ref.configPath === RAILWAY_SSH_SECRET_PATH);
+ let next: RailwaySshSetup | null = null;
+ let refs = grant.credentialSecretRefs;
+ if (input.action === "remove") {
+ if (currentRef) await secretService(tx).remove(currentRef.secretId);
+ refs = refs.filter((ref) => ref.configPath !== RAILWAY_SSH_SECRET_PATH);
+ } else if (input.action === "prepare") {
+ if (currentRef && typeof existing.publicKey === "string") return existing as unknown as RailwaySshSetup;
+ const key = await generateRailwaySshKey();
+ const ref = await createOrRotateOAuthSecret({ companyId, connection, configPath: RAILWAY_SSH_SECRET_PATH, label: "Railway container SSH key", value: key.privateKey, existingRefs: [], ownerUserId: grant.kind === "user" ? grant.subjectUserId ?? undefined : undefined, actor }, { dbClient: tx, secretClient: secretService(tx) });
+ refs = [...refs.filter((ref) => ref.configPath !== RAILWAY_SSH_SECRET_PATH), ref];
+ next = { grantId: grant.id, publicKey: key.publicKey, knownHosts: "", enabled: false };
+ } else {
+ if (!currentRef || typeof existing.publicKey !== "string") throw unprocessable("Generate and register a container key first.");
+ next = { grantId: grant.id, publicKey: existing.publicKey, knownHosts, enabled: true };
}
- }
+ await tx.update(connectionGrants).set({ credentialSecretRefs: refs, updatedAt: now() }).where(and(eq(connectionGrants.id, grant.id), eq(connectionGrants.companyId, companyId)));
+ const config = { ...connection.config, railwaySsh: next };
+ const [updated] = await tx.update(toolConnections).set({ config, transportConfig: config, updatedAt: now() }).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, companyId))).returning();
+ await syncCredentialBindings(updated, [], tx);
+ return next;
+ });
+ await audit({ companyId, connectionId, action: "tool_connection.railway_ssh_updated", outcome: "success", actor, details: { action: input.action, grantId: input.grantId, enabled: setup?.enabled ?? false } });
+ return setup;
+ },
- if (grant.kind === "organization") {
- const activeAudienceMember = actingUserId
- ? await db
- .select({ id: companyMemberships.id })
- .from(companyMemberships)
- .where(
- and(
- eq(companyMemberships.companyId, connection.companyId),
- eq(companyMemberships.principalType, "user"),
- eq(companyMemberships.principalId, actingUserId),
- eq(companyMemberships.status, "active"),
- ),
- )
- .limit(1)
- .then((rows) => rows[0] ?? null)
- : null;
- const audience = await db
- .select({ subjectId: connectionGrantMembers.subjectId })
- .from(connectionGrantMembers)
- .where(
- and(
- eq(connectionGrantMembers.companyId, connection.companyId),
- eq(connectionGrantMembers.grantId, grant.id),
- eq(connectionGrantMembers.subjectType, "user"),
- ),
- );
- if (
- (actingUserId !== null && !activeAudienceMember) ||
- (audience.length > 0 &&
- (!actingUserId ||
- !audience.some((member) => member.subjectId === actingUserId)))
- ) {
- await fail(
- 403,
- "The acting user is not in this grant's audience",
- "denied",
- "grant_audience_denied",
- {
- connection: { uid: connection.uid },
- subject,
- grantId: grant.id,
- },
+ listAppsNeedingAttention,
+
+ sweepConnectionHealth,
+
+ sweepGitHubConnectionContinuity,
+
+ listCatalog: async (
+ connectionId: string,
+ companyId?: string,
+ actor?: ActorInfo,
+ ): Promise<ToolCatalogEntry[]> => {
+ const connection = await getConnectionRow(connectionId, companyId);
+ let rows = await db
+ .select()
+ .from(toolCatalogEntries)
+ .where(eq(toolCatalogEntries.connectionId, connection.id))
+ .orderBy(desc(toolCatalogEntries.updatedAt));
+ // Native provider catalogs change with the deployed code. Upgrade saved
+ // Daytona connections too; their first small catalog must not survive
+ // merely because REST discovery has no remote MCP cache timer.
+ const nativeDaytona = isDaytonaConnection(connection);
+ const rowsByName = new Map(rows.map((row) => [row.toolName, row]));
+ const daytonaCatalogChanged = nativeDaytona && connection.status === "active" && (
+ rows.some((row) => row.status !== "removed" && !isDaytonaToolName(row.toolName))
+ || DAYTONA_TOOLS.some((tool) => {
+ const existing = rowsByName.get(tool.name);
+ return !existing || existing.versionHash !== descriptorHash(tool, daytonaRisk(tool.name));
+ })
+ );
+ const cacheExpired = daytonaCatalogChanged || (
+ connection.transport === "mcp_remote" &&
+ connection.status !== "archived" &&
+ (rows.length === 0 ||
+ !connection.lastCatalogRefreshAt ||
+ connection.lastCatalogRefreshAt.getTime() <=
+ now().getTime() - catalogCacheTtlMs));
+ if (cacheExpired) {
+ try {
+ await singleFlight(catalogRefreshFlights, connection.id, () =>
+ refreshCatalog(connection.id, nativeDaytona && actor ? actor : {
+ actorType: "system",
+ actorId: "tool_catalog_cache",
+ }),
);
+ rows = await db
+ .select()
+ .from(toolCatalogEntries)
+ .where(eq(toolCatalogEntries.connectionId, connection.id))
+ .orderBy(desc(toolCatalogEntries.updatedAt));
+ } catch (error) {
+ // A stale catalog remains useful when the remote server is temporarily
+ // unavailable. Empty caches still fail so callers never mistake “no
+ // actions discovered” for a successful lookup.
+ if (rows.length === 0) throw error;
}
}
+ // Even failed discovery must not keep retired native tools visible.
+ // Their database rows remain available to historical invocation records.
+ return rows
+ .filter((row) => !nativeDaytona || (row.status !== "removed" && isDaytonaToolName(row.toolName)))
+ .map((row) => toCatalogEntryForConnection(row, connection));
+ },
+
+ /** Recent tool-call events for one connection — drives App detail · Recent activity. */
+ listConnectionActivity: async (
+ connectionId: string,
+ companyId?: string,
+ limit = 20,
+ ): Promise<ToolConnectionActivityResponse> => {
+ const connection = await getConnectionRow(connectionId, companyId);
+ const safeLimit = Math.max(1, Math.min(100, Math.floor(limit)));
+ const rows = await db
+ .select()
+ .from(toolCallEvents)
+ .where(
+ and(
+ eq(toolCallEvents.companyId, connection.companyId),
+ eq(toolCallEvents.connectionId, connection.id),
+ ),
+ )
+ .orderBy(desc(toolCallEvents.createdAt))
+ .limit(safeLimit);
+ const events = rows.map(toToolCallEvent);
- if (grant.status !== "active") {
- const code =
- grant.status === "needs_reauthorization"
- ? "needs_reauthorization"
- : "grant_revoked";
- await fail(
- 409,
- "The selected connection grant is not active",
- "denied",
- code,
+ const issueIds = [
+ ...new Set(rows.map((row) => row.issueId).filter(Boolean)),
+ ] as string[];
+ const issueRows = issueIds.length
+ ? await db
+ .select({
+ id: issues.id,
+ identifier: issues.identifier,
+ title: issues.title,
+ })
+ .from(issues)
+ .where(
+ and(
+ eq(issues.companyId, connection.companyId),
+ inArray(issues.id, issueIds),
+ ),
+ )
+ : [];
+ const issueMap = Object.fromEntries(
+ issueRows.map((issue) => [
+ issue.id,
{
- connection: { uid: connection.uid },
- subject,
- grantId: grant.id,
- remediation: { action: "reauthorize" },
+ identifier: issue.identifier ?? issue.id,
+ title: issue.title,
},
- );
- }
- const requestedScopeSelectors = new Set(requestedScope);
- const matchingScopedRefs = grant.credentialSecretRefs.filter(
- (ref) => ref.keyScope && requestedScopeSelectors.has(ref.keyScope),
+ ]),
);
- const selectedCredentialSecretRefs =
- matchingScopedRefs.length > 0
- ? grant.credentialSecretRefs.filter(
- (ref) =>
- !ref.keyScope || requestedScopeSelectors.has(ref.keyScope),
+
+ const actionRequestIds = [
+ ...new Set(rows.map((row) => row.actionRequestId).filter(Boolean)),
+ ] as string[];
+ const requestRows = actionRequestIds.length
+ ? await db
+ .select({
+ id: toolActionRequests.id,
+ status: toolActionRequests.status,
+ resolvedByAgentId: toolActionRequests.resolvedByAgentId,
+ resolvedByUserId: toolActionRequests.resolvedByUserId,
+ })
+ .from(toolActionRequests)
+ .where(
+ and(
+ eq(toolActionRequests.companyId, connection.companyId),
+ inArray(toolActionRequests.id, actionRequestIds),
+ ),
)
- : grant.credentialSecretRefs.filter((ref) => !ref.keyScope);
- const rotateBefore = Date.now() + 14 * 24 * 60 * 60 * 1000;
- const expiringRef = selectedCredentialSecretRefs.find(
- (ref) => ref.expiresAt && Date.parse(ref.expiresAt) <= rotateBefore,
- );
- if (expiringRef && connection.healthStatus !== "degraded") {
- await db
- .update(toolConnections)
- .set({
- healthStatus: "degraded",
- healthMessage: `Rotate ${expiringRef.label ?? expiringRef.configPath} before it expires.`,
- updatedAt: new Date(),
- })
- .where(eq(toolConnections.id, connection.id));
- }
- const credentialConnection = {
- ...connection,
- credentialSecretRefs: selectedCredentialSecretRefs,
- };
+ : [];
- if (!connection.enabled || connection.status !== "active") {
- await fail(
- 409,
- "Connection is not active",
- "denied",
- "connection_not_active",
- {
- connectionStatus: connection.status,
- enabled: connection.enabled,
- },
- );
- }
- if (
- ["failed", "error", "missing_secret"].includes(connection.healthStatus)
- ) {
- await fail(
- 409,
- "Connection credential needs attention",
- "denied",
- "credential_revoked",
- {
- healthStatus: connection.healthStatus,
- healthMessage: connection.healthMessage ?? null,
- },
- );
- }
- if (!brokerEnabled) {
- await fail(
- 403,
- "Connection token broker is not enabled for this connection",
- "denied",
- "broker_not_enabled",
- {
- reason:
- "Connections must explicitly opt in with tokenBroker.enabled before agents can request brokered tokens.",
- },
- );
- }
- try {
- assertScopeSubset({ requestedScope: issuedScope, parentScopes });
- } catch {
- await fail(
- 403,
- "Requested token scope exceeds the connection parent scope",
- "denied",
- "scope_exceeds_parent",
+ const resolverAgentIds = [
+ ...new Set(
+ requestRows.map((row) => row.resolvedByAgentId).filter(Boolean),
+ ),
+ ] as string[];
+ const resolverUserIds = [
+ ...new Set(
+ requestRows.map((row) => row.resolvedByUserId).filter(Boolean),
+ ),
+ ] as string[];
+ const resolverAgents = resolverAgentIds.length
+ ? await db
+ .select({ id: agents.id, name: agents.name })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.companyId, connection.companyId),
+ inArray(agents.id, resolverAgentIds),
+ ),
+ )
+ : [];
+ const resolverUsers = resolverUserIds.length
+ ? await db
+ .select({
+ id: authUsers.id,
+ name: authUsers.name,
+ email: authUsers.email,
+ })
+ .from(authUsers)
+ .where(inArray(authUsers.id, resolverUserIds))
+ : [];
+ const resolverAgentNames = new Map(
+ resolverAgents.map((agent) => [agent.id, agent.name]),
+ );
+ const resolverUserNames = new Map(
+ resolverUsers.map((user) => [
+ user.id,
+ user.name?.trim() || user.email?.trim() || user.id,
+ ]),
+ );
+ const actionRequestMap = Object.fromEntries(
+ requestRows.map((request) => [
+ request.id,
{
- parentScopeCount: parentScopes.length,
+ status: request.status,
+ resolverDisplayName: request.resolvedByAgentId
+ ? (resolverAgentNames.get(request.resolvedByAgentId) ??
+ request.resolvedByAgentId)
+ : request.resolvedByUserId
+ ? (resolverUserNames.get(request.resolvedByUserId) ??
+ userFallbackName(request.resolvedByUserId))
+ : null,
+ resolvedByAgentId: request.resolvedByAgentId,
+ resolvedByUserId: request.resolvedByUserId,
},
- );
- }
+ ]),
+ );
- const hasBrokerGrant = await hasExplicitConnectionTokenMintProfileGrant({
+ const lifecycleEvents = await listConnectionLifecycleEvents(db, {
companyId: connection.companyId,
- agentId: input.agentId,
- issueId: runContext.issueId,
- projectId: runContext.projectId,
- routineId: runContext.routineId,
+ connectionIds: [connection.id],
+ limit: safeLimit,
});
- if (!hasBrokerGrant) {
- await fail(
- 403,
- "Connection token minting requires an explicit broker profile grant",
- "denied",
- "broker_mint_not_granted",
- {
- reason:
- "A connection-level profile grant is not sufficient for connection_token.mint.",
- },
- );
- }
- const decisionInput = {
- companyId: connection.companyId,
- actor: {
- actorType: "agent" as const,
- actorId: input.agentId,
- agentId: input.agentId,
- },
- runContext: {
- heartbeatRunId: input.runId,
- issueId: runContext.issueId,
- projectId: runContext.projectId,
- routineId: runContext.routineId,
- },
- request: {
- applicationId: connection.applicationId,
- connectionId: connection.id,
- providerType: "connection_token_broker",
- applicationKey: application?.applicationKey ?? null,
- upstreamToolName: CONNECTION_TOKEN_MINT_TOOL_NAME,
- riskLevel: "write",
- toolName: CONNECTION_TOKEN_MINT_TOOL_NAME,
- arguments: {
- path,
- scope: issuedScope,
- requestedTtlSeconds: input.body.requestedTtlSeconds ?? null,
- },
- },
- consumeRateLimit: true,
+ return {
+ connectionId: connection.id,
+ events,
+ lifecycleEvents,
+ issues: issueMap,
+ actionRequests: actionRequestMap,
};
- const decision = await policySvc.decide(decisionInput);
- await policySvc.writeAudit(decisionInput, decision);
- if (!decision.allowed) {
- await fail(
- decision.decision === "rate_limited" ? 429 : 403,
- decision.explanation,
- decision.decision === "rate_limited" ? "rate_limited" : "denied",
- decision.reasonCode,
- {
- decision: decision.decision,
- effectiveProfileIds: decision.effectiveProfileIds,
- matchedPolicyIds: decision.matchedPolicyIds,
- rateLimitState: decision.rateLimitState ?? null,
- },
- );
- }
+ },
- try {
- await enforceDefaultConnectionTokenRateLimit({
- connection,
- agentId: input.agentId,
- path,
- });
- } catch (error) {
- if (error instanceof HttpError && error.status === 429) {
- await fail(
- 429,
- error.message,
- "rate_limited",
- "rate_limited",
- asRecord(error.details),
+ /**
+ * List "Ask first" action requests for the review queue, enriched with the
+ * connection/app context the prosumer card renders. Defaults to pending.
+ */
+ listActionRequests: async (
+ companyId: string,
+ status: ToolActionRequestStatus = "pending",
+ ): Promise<ToolActionRequestListItem[]> => {
+ const requests = await db
+ .select()
+ .from(toolActionRequests)
+ .where(
+ and(
+ eq(toolActionRequests.companyId, companyId),
+ eq(toolActionRequests.status, status),
+ ),
+ )
+ .orderBy(desc(toolActionRequests.createdAt));
+ if (requests.length === 0) return [];
+
+ const invocationIds = [
+ ...new Set(requests.map((request) => request.invocationId)),
+ ];
+ const invocations = await db
+ .select()
+ .from(toolInvocations)
+ .where(
+ and(
+ eq(toolInvocations.companyId, companyId),
+ inArray(toolInvocations.id, invocationIds),
+ ),
+ );
+ const invocationById = new Map(
+ invocations.map((invocation) => [invocation.id, invocation]),
+ );
+ let visibleRequests = requests;
+ if (status === "pending") {
+ // A pending request that the creator has not signed yet is still being
+ // set up. The gateway creates the row (signedArguments = null) and signs
+ // it in a second step, so a review-queue read can observe the row inside
+ // that window. Hide such a request from the queue, but do not cancel it —
+ // cancelling here races the two-step create and makes the later approve
+ // fail with action_not_pending. Only cancel a request that carries a
+ // signature we cannot verify (secret rotation or tampering), or an
+ // unsigned row whose creator has exceeded the signing grace period.
+ const unsignedRequestIds = new Set<string>();
+ const invalidRequestIds: string[] = [];
+ for (const request of requests) {
+ const invocation = invocationById.get(request.invocationId);
+ if (!invocation) {
+ invalidRequestIds.push(request.id);
+ continue;
+ }
+ if (request.signedArguments === null) {
+ if (
+ Date.now() - request.createdAt.getTime() >=
+ TOOL_ACTION_REQUEST_SIGNING_GRACE_MS
+ ) {
+ invalidRequestIds.push(request.id);
+ } else {
+ unsignedRequestIds.add(request.id);
+ }
+ continue;
+ }
+ let readable = false;
+ try {
+ readable = Boolean(
+ readSignedToolArgumentsPayload({
+ signedArguments: request.signedArguments,
+ invocationId: invocation.id,
+ toolName: invocation.toolName,
+ }),
+ );
+ } catch {
+ readable = false;
+ }
+ if (!readable) invalidRequestIds.push(request.id);
+ }
+ if (invalidRequestIds.length > 0) {
+ await db
+ .update(toolActionRequests)
+ .set({
+ status: "cancelled",
+ resolvedAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(toolActionRequests.companyId, companyId),
+ eq(toolActionRequests.status, "pending"),
+ inArray(toolActionRequests.id, invalidRequestIds),
+ ),
+ );
+ }
+ const hiddenIds = new Set([
+ ...invalidRequestIds,
+ ...unsignedRequestIds,
+ ]);
+ if (hiddenIds.size > 0) {
+ visibleRequests = requests.filter(
+ (request) => !hiddenIds.has(request.id),
);
}
- throw error;
}
+ if (visibleRequests.length === 0) return [];
- if (path === "static") {
- await recordFailure("use_env_lease", "use_env_lease", {
- reason:
- "Connection uses durable static credentials; broker token delivery is refused.",
- });
- return {
- status: "use_env_lease",
- code: "use_env_lease",
- connectionId: connection.id,
- connection: { id: connection.id, uid: connection.uid },
- grantId: grant.id,
- path: "static",
- message:
- "This connection uses static credentials. Use an audited environment lease projection instead.",
- scope: issuedScope,
- attribution,
- };
- }
- if (path === "oauth_access") {
- await fail(
- 422,
- "OAuth access-token projection is disabled; configure a short-lived exchange mint path instead",
- "denied",
- "oauth_access_projection_disabled",
- {
- reason:
- "The broker must not return stored upstream OAuth bearer tokens directly.",
- },
+ const visibleInvocations = visibleRequests
+ .map((request) => invocationById.get(request.invocationId))
+ .filter(
+ (invocation): invocation is typeof toolInvocations.$inferSelect =>
+ Boolean(invocation),
);
- }
+ const connectionIds = [
+ ...new Set(
+ visibleInvocations
+ .map((invocation) => invocation.connectionId)
+ .filter(Boolean),
+ ),
+ ] as string[];
+ const connections = connectionIds.length
+ ? await db
+ .select()
+ .from(toolConnections)
+ .where(inArray(toolConnections.id, connectionIds))
+ : [];
+ const connectionById = new Map(
+ connections.map((connection) => [connection.id, connection]),
+ );
- const selectedGrant = grant;
- try {
- const mintResult = await db.transaction(async (tx) => {
- await lockAuthorizedBrokerResponsibleMembership(
- {
- companyId: connection.companyId,
- responsibleUserId: runContext.responsibleUserId,
- },
- tx,
- );
- const minted = await mintExchangeConnectionToken(
- {
- connection: credentialConnection,
- application,
- agentId: input.agentId,
- runId: input.runId,
- issueId: runContext.issueId,
- responsibleUserId: runContext.responsibleUserId,
- scope: issuedScope,
- ttlSeconds,
- },
- secretService(tx),
- );
- const expiresAt = minted.expiresAt;
- const mintedScope = "scope" in minted ? minted.scope : issuedScope;
- const effectiveTtlSeconds = Math.max(
- 1,
- Math.min(
- 900,
- Math.ceil((expiresAt.getTime() - now().getTime()) / 1000),
- ),
- );
- const tokenHash = bearerTokenHash(minted.token);
- await recordConnectionTokenIssuance(
- {
- companyId: connection.companyId,
- applicationId: connection.applicationId,
- connectionId: connection.id,
- agentId: input.agentId,
- runId: input.runId,
- issueId: runContext.issueId,
- projectId: runContext.projectId,
- responsibleUserId: runContext.responsibleUserId,
- path,
- requestedScope,
- issuedScope: mintedScope,
- ttlSeconds: effectiveTtlSeconds,
- expiresAt,
- tokenHash,
- outcome: "success",
- metadata: { tokenRef: tokenHash, tokenType: minted.tokenType },
- },
- tx,
- );
- await tx
- .update(connectionGrants)
- .set({ lastUsedAt: new Date(), updatedAt: new Date() })
- .where(eq(connectionGrants.id, selectedGrant.id));
- return {
- minted,
- expiresAt,
- mintedScope,
- effectiveTtlSeconds,
- tokenHash,
- };
- });
- await auditConnectionTokenIssuance({
- companyId: connection.companyId,
- connectionId: connection.id,
- agentId: input.agentId,
- runId: input.runId,
- path,
- outcome: "success",
- details: {
- ttlSeconds: mintResult.effectiveTtlSeconds,
- scopeCount: mintResult.mintedScope.length,
- tokenRef: mintResult.tokenHash,
- },
- });
+ const applicationIds = [
+ ...new Set(
+ connections
+ .map((connection) => connection.applicationId)
+ .filter(Boolean),
+ ),
+ ] as string[];
+ const applications = applicationIds.length
+ ? await db
+ .select()
+ .from(toolApplications)
+ .where(inArray(toolApplications.id, applicationIds))
+ : [];
+ const applicationById = new Map(
+ applications.map((application) => [application.id, application]),
+ );
+
+ const catalogEntryIds = [
+ ...new Set(
+ visibleInvocations
+ .map((invocation) => invocation.catalogEntryId)
+ .filter(Boolean),
+ ),
+ ] as string[];
+ const catalogEntries = catalogEntryIds.length
+ ? await db
+ .select()
+ .from(toolCatalogEntries)
+ .where(inArray(toolCatalogEntries.id, catalogEntryIds))
+ : [];
+ const catalogById = new Map(
+ catalogEntries.map((entry) => [entry.id, entry]),
+ );
+
+ return visibleRequests.map((request) => {
+ const invocation = invocationById.get(request.invocationId);
+ const connection = invocation?.connectionId
+ ? connectionById.get(invocation.connectionId)
+ : undefined;
+ const application = connection?.applicationId
+ ? applicationById.get(connection.applicationId)
+ : undefined;
+ const catalogEntry = invocation?.catalogEntryId
+ ? catalogById.get(invocation.catalogEntryId)
+ : undefined;
return {
- status: "minted",
- connectionId: connection.id,
- connection: { id: connection.id, uid: connection.uid },
- grantId: selectedGrant.id,
- providerTenantId: selectedGrant.providerTenant?.externalId,
- path: "exchange",
- token: mintResult.minted.token,
- tokenType: mintResult.minted.tokenType,
- expiresAt: mintResult.expiresAt.toISOString(),
- ttlSeconds: mintResult.effectiveTtlSeconds,
- scope: mintResult.mintedScope,
- attribution,
+ request: toToolActionRequest(request),
+ toolName: invocation?.toolName ?? catalogEntry?.toolName ?? "",
+ toolTitle: catalogEntry?.title ?? null,
+ connectionId: connection?.id ?? invocation?.connectionId ?? null,
+ connectionName: connection?.name ?? null,
+ applicationName: application?.name ?? null,
+ riskLevel: catalogEntry?.riskLevel ?? null,
+ requestedByAgentId: request.requestedByAgentId ?? null,
};
- } catch (error) {
- const details =
- error instanceof HttpError && asRecord(error.details).code
- ? asRecord(error.details)
- : {};
- const errorCode =
- typeof details.code === "string" ? details.code : "mint_failed";
- const outcome: ConnectionTokenIssuanceOutcome =
- errorCode === "upstream_error" ||
- errorCode === "upstream_token_missing"
- ? "upstream_error"
- : "failure";
- await recordFailure(outcome, errorCode, {
- ...details,
- message: error instanceof Error ? error.message : String(error),
- });
- throw error;
- }
+ });
},
+ ...profileService,
+ ...profileResolver,
+ mintConnectionTokenForAgent,
listRuntimeSlots: async (companyId: string): Promise<ToolRuntimeSlot[]> => {
const rows = await db
diff --git a/server/src/services/tool-access/audit.ts b/server/src/services/tool-access/audit.ts
new file mode 100644
index 0000000000..47458c663c
--- /dev/null
+++ b/server/src/services/tool-access/audit.ts
@@ -0,0 +1,37 @@
+import type { ActorInfo } from "./types.js";
+import type { Db } from "@paperclipai/db";
+import { toolAccessAuditEvents } from "@paperclipai/db";
+import { recordToolRuntimeAuditWriteFailure } from "../tool-runtime-metrics.js";
+
+export function createToolAccessAudit(db: Db) {
+ async function audit(input: {
+ companyId: string;
+ connectionId?: string | null;
+ catalogEntryId?: string | null;
+ action: string;
+ outcome: "success" | "failure";
+ reasonCode?: string | null;
+ details?: Record<string, unknown>;
+ actor?: ActorInfo;
+ }) {
+ try {
+ await db.insert(toolAccessAuditEvents).values({
+ companyId: input.companyId,
+ connectionId: input.connectionId ?? null,
+ catalogEntryId: input.catalogEntryId ?? null,
+ actorType: input.actor?.actorType ?? "system",
+ actorId: input.actor?.actorId ?? null,
+ action: input.action,
+ outcome: input.outcome,
+ reasonCode: input.reasonCode ?? null,
+ details: input.details ?? {},
+ });
+ } catch (error) {
+ await recordToolRuntimeAuditWriteFailure(db, input.companyId);
+ throw error;
+ }
+ }
+ return audit;
+}
+
+export type ToolAccessAudit = ReturnType<typeof createToolAccessAudit>;
diff --git a/server/src/services/tool-access/token-broker/admission.ts b/server/src/services/tool-access/token-broker/admission.ts
new file mode 100644
index 0000000000..5b30a3fd91
--- /dev/null
+++ b/server/src/services/tool-access/token-broker/admission.ts
@@ -0,0 +1,254 @@
+import type { DbTransaction } from "../types.js";
+import { captureRunIdentity } from "../../run-identity.js";
+import { and, eq, gte, inArray, sql } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { connectionTokenIssuances, companyMemberships, heartbeatRuns, toolConnections, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db";
+import type { ConnectionTokenIssuancePath } from "@paperclipai/shared";
+import { forbidden, HttpError } from "../../../errors.js";
+import { narrowestScopeBindings, profileIdsInBindingOrder } from "../../tool-profile-binding-precedence.js";
+
+import { CONNECTION_TOKEN_MINT_TOOL_NAME, tokenBrokerConfig } from "./configuration.js";
+function asRecord(value: unknown): Record<string, unknown> {
+ if (value && typeof value === "object" && !Array.isArray(value))
+ return value as Record<string, unknown>;
+ return {};
+}
+
+const ACTIVE_BROKER_RUN_STATUSES = new Set(["running"]);
+
+export async function lockAuthorizedBrokerResponsibleMembership(
+ input: {
+ companyId: string;
+ responsibleUserId: string;
+ },
+ tx: DbTransaction,
+) {
+ const membership = await tx
+ .select({
+ id: companyMemberships.id,
+ status: companyMemberships.status,
+ membershipRole: companyMemberships.membershipRole,
+ })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, input.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, input.responsibleUserId),
+ ),
+ )
+ .limit(1)
+ .for("update")
+ .then((rows) => rows[0] ?? null);
+ if (
+ !membership ||
+ membership.status !== "active" ||
+ !membership.membershipRole ||
+ membership.membershipRole === "viewer"
+ ) {
+ throw new HttpError(
+ 403,
+ "Responsible user is no longer authorized for company write access",
+ {
+ code: "responsible_user_unauthorized",
+ },
+ );
+ }
+ return membership;
+}
+
+export function createTokenBrokerAdmission(db: Db, now: () => Date) {
+ function runSnapshotString(
+ snapshot: Record<string, unknown>,
+ ...keys: string[]
+ ): string | null {
+ for (const key of keys) {
+ const value = snapshot[key];
+ if (typeof value === "string" && value.trim().length > 0) return value;
+ }
+ return null;
+ }
+
+ async function loadBrokerRunContext(input: {
+ companyId: string;
+ agentId: string;
+ runId: string;
+ }) {
+ const [initialRun] = await db
+ .select()
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, input.runId));
+ const run = initialRun?.activeIdentityContextId
+ ? (await captureRunIdentity(db, input)).run
+ : initialRun;
+ if (
+ !run ||
+ run.companyId !== input.companyId ||
+ run.agentId !== input.agentId
+ ) {
+ throw forbidden(
+ "Agent run context does not match the authenticated actor",
+ );
+ }
+ if (!ACTIVE_BROKER_RUN_STATUSES.has(run.status)) {
+ throw forbidden("Agent run is not active");
+ }
+ const snapshot = asRecord(run.contextSnapshot);
+ const paperclipIssue = asRecord(snapshot.paperclipIssue);
+ const responsibleUserId = run.activeIdentityContextId
+ ? run.responsibleUserId
+ : (runSnapshotString(
+ snapshot,
+ "responsibleUserId",
+ "responsible_user_id",
+ ) ??
+ runSnapshotString(
+ paperclipIssue,
+ "responsibleUserId",
+ "responsible_user_id",
+ ) ??
+ run.responsibleUserId);
+ if (!responsibleUserId) {
+ throw forbidden(
+ "Agent run has no responsible user for delegated connection access",
+ );
+ }
+ const responsibleMembership = await db
+ .select({
+ status: companyMemberships.status,
+ membershipRole: companyMemberships.membershipRole,
+ })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, run.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, responsibleUserId),
+ ),
+ )
+ .then((rows) => rows[0] ?? null);
+ if (
+ !responsibleMembership ||
+ responsibleMembership.status !== "active" ||
+ !responsibleMembership.membershipRole ||
+ responsibleMembership.membershipRole === "viewer"
+ ) {
+ throw forbidden(
+ "Responsible user is no longer authorized for company write access",
+ );
+ }
+ return {
+ run,
+ issueId:
+ runSnapshotString(snapshot, "issueId") ??
+ runSnapshotString(paperclipIssue, "id"),
+ projectId:
+ runSnapshotString(snapshot, "projectId") ??
+ runSnapshotString(paperclipIssue, "projectId"),
+ routineId: runSnapshotString(snapshot, "routineId"),
+ responsibleUserId,
+ };
+ }
+
+ async function enforceDefaultConnectionTokenRateLimit(input: {
+ connection: typeof toolConnections.$inferSelect;
+ agentId: string;
+ path: ConnectionTokenIssuancePath;
+ }) {
+ const broker = tokenBrokerConfig(input.connection);
+ const configured = Number(broker.rateLimitPerHour ?? 30);
+ const limit =
+ Number.isFinite(configured) && configured > 0
+ ? Math.trunc(configured)
+ : 30;
+ const since = new Date(now().getTime() - 60 * 60 * 1000);
+ const [row] = await db
+ .select({ count: sql<number>`count(*)::int` })
+ .from(connectionTokenIssuances)
+ .where(
+ and(
+ eq(connectionTokenIssuances.companyId, input.connection.companyId),
+ eq(connectionTokenIssuances.connectionId, input.connection.id),
+ eq(connectionTokenIssuances.agentId, input.agentId),
+ eq(connectionTokenIssuances.outcome, "success"),
+ gte(connectionTokenIssuances.createdAt, since),
+ ),
+ );
+ const count = Number(row?.count ?? 0);
+ if (count >= limit) {
+ throw new HttpError(429, "Connection token mint rate limit exceeded", {
+ code: "rate_limited",
+ path: input.path,
+ limit,
+ windowSeconds: 3600,
+ });
+ }
+ }
+
+ async function hasExplicitConnectionTokenMintProfileGrant(input: {
+ companyId: string;
+ agentId: string;
+ issueId: string | null;
+ projectId: string | null;
+ routineId: string | null;
+ }) {
+ const bindings = await db
+ .select()
+ .from(toolProfileBindings)
+ .where(eq(toolProfileBindings.companyId, input.companyId));
+ const matchingBindings = bindings.filter((binding) => {
+ if (binding.targetType === "company")
+ return binding.targetId === input.companyId;
+ if (binding.targetType === "agent")
+ return binding.targetId === input.agentId;
+ if (binding.targetType === "issue")
+ return Boolean(input.issueId && binding.targetId === input.issueId);
+ if (binding.targetType === "project")
+ return Boolean(input.projectId && binding.targetId === input.projectId);
+ if (binding.targetType === "routine")
+ return Boolean(input.routineId && binding.targetId === input.routineId);
+ return false;
+ });
+ const profileIds = profileIdsInBindingOrder(
+ narrowestScopeBindings(matchingBindings),
+ );
+ if (profileIds.length === 0) return false;
+ const profiles = await db
+ .select()
+ .from(toolProfiles)
+ .where(
+ and(
+ eq(toolProfiles.companyId, input.companyId),
+ inArray(toolProfiles.id, profileIds),
+ ),
+ );
+ const activeProfileIds = profiles
+ .filter((profile) => profile.status === "active")
+ .map((profile) => profile.id);
+ if (activeProfileIds.length === 0) return false;
+ const entries = await db
+ .select()
+ .from(toolProfileEntries)
+ .where(
+ and(
+ eq(toolProfileEntries.companyId, input.companyId),
+ inArray(toolProfileEntries.profileId, activeProfileIds),
+ ),
+ );
+ return activeProfileIds.some((profileId) => {
+ const profileEntries = entries.filter(
+ (entry) => entry.profileId === profileId,
+ );
+ const exactBrokerEntries = profileEntries.filter(
+ (entry) =>
+ entry.selectorType === "tool_name" &&
+ entry.toolName === CONNECTION_TOKEN_MINT_TOOL_NAME &&
+ Object.keys(asRecord(entry.conditions)).length === 0,
+ );
+ if (exactBrokerEntries.some((entry) => entry.effect === "exclude"))
+ return false;
+ return exactBrokerEntries.some((entry) => entry.effect === "include");
+ });
+ }
+ return { loadBrokerRunContext, enforceDefaultConnectionTokenRateLimit, hasExplicitConnectionTokenMintProfileGrant };
+}
diff --git a/server/src/services/tool-access/token-broker/configuration.ts b/server/src/services/tool-access/token-broker/configuration.ts
new file mode 100644
index 0000000000..2a6658cea6
--- /dev/null
+++ b/server/src/services/tool-access/token-broker/configuration.ts
@@ -0,0 +1,237 @@
+import { createHash } from "node:crypto";
+
+import { toolApplications, toolConnections } from "@paperclipai/db";
+import type { ConnectionTokenIssuancePath, ConnectionTokenRequest } from "@paperclipai/shared";
+import { forbidden, unprocessable } from "../../../errors.js";
+
+function asRecord(value: unknown): Record<string, unknown> {
+ if (value && typeof value === "object" && !Array.isArray(value))
+ return value as Record<string, unknown>;
+ return {};
+}
+
+export function readConfigString(
+ record: Record<string, unknown>,
+ key: string,
+): string | null {
+ const value = record[key];
+ return typeof value === "string" && value.trim().length > 0
+ ? value.trim()
+ : null;
+}
+
+export function readConfigStringArray(value: unknown): string[] {
+ if (Array.isArray(value)) {
+ return value
+ .filter((item): item is string => typeof item === "string")
+ .map((item) => item.trim())
+ .filter(Boolean);
+ }
+ if (typeof value === "string")
+ return value
+ .split(/\s+/)
+ .map((item) => item.trim())
+ .filter(Boolean);
+ return [];
+}
+
+export function normalizeConnectionTokenScopes(
+ scope: ConnectionTokenRequest["scope"],
+): string[] {
+ if (Array.isArray(scope))
+ return [...new Set(scope.map((item) => item.trim()).filter(Boolean))];
+ if (typeof scope === "string")
+ return [
+ ...new Set(
+ scope
+ .split(/\s+/)
+ .map((item) => item.trim())
+ .filter(Boolean),
+ ),
+ ];
+ return [];
+}
+
+export function tokenBrokerConfigFromConnectionConfig(
+ config: Record<string, unknown>,
+): Record<string, unknown> {
+ const broker = asRecord(config.tokenBroker);
+ if (Object.keys(broker).length > 0) return broker;
+ return asRecord(config.broker);
+}
+
+export function tokenBrokerConfig(
+ connection: typeof toolConnections.$inferSelect,
+): Record<string, unknown> {
+ return tokenBrokerConfigFromConnectionConfig(asRecord(connection.config));
+}
+
+export function configuredTokenBrokerExchangeUrls(
+ config: Record<string, unknown>,
+): string[] {
+ const broker = tokenBrokerConfigFromConnectionConfig(config);
+ return [
+ ...new Set(
+ [
+ readConfigString(broker, "tokenUrl"),
+ readConfigString(broker, "exchangeTokenUrl"),
+ readConfigString(config, "tokenExchangeUrl"),
+ readConfigString(config, "pagesTokenExchangeUrl"),
+ ].filter((url): url is string => url !== null),
+ ),
+ ];
+}
+
+export function connectionTokenBrokerEnabled(
+ connection: typeof toolConnections.$inferSelect,
+): boolean {
+ const config = asRecord(connection.config);
+ const tokenBroker = asRecord(config.tokenBroker);
+ if (Object.keys(tokenBroker).length > 0)
+ return tokenBroker.enabled === true;
+ const broker = asRecord(config.broker);
+ if (Object.keys(broker).length > 0) return broker.enabled === true;
+ return false;
+}
+
+export function isPagesTokenConnection(
+ connection: typeof toolConnections.$inferSelect,
+ application?: typeof toolApplications.$inferSelect | null,
+) {
+ const config = asRecord(connection.config);
+ const broker = tokenBrokerConfig(connection);
+ const applicationKey = application?.applicationKey ?? "";
+ return Boolean(
+ applicationKey === "paperclip-pages" ||
+ applicationKey === "paperclip.pages" ||
+ applicationKey === "pages.paperclip" ||
+ readConfigString(config, "connectionType") === "pages" ||
+ readConfigString(config, "service") === "pages" ||
+ readConfigString(broker, "connectionType") === "pages" ||
+ readConfigString(broker, "service") === "pages" ||
+ asRecord(config.pages).enabled === true,
+ );
+}
+
+export function inferConnectionTokenPath(
+ connection: typeof toolConnections.$inferSelect,
+ application?: typeof toolApplications.$inferSelect | null,
+): ConnectionTokenIssuancePath {
+ const broker = tokenBrokerConfig(connection);
+ const configuredPath =
+ readConfigString(broker, "path") ??
+ readConfigString(asRecord(connection.config), "tokenPath");
+ if (
+ configuredPath === "exchange" ||
+ configuredPath === "oauth_access" ||
+ configuredPath === "static"
+ )
+ return configuredPath;
+ if (isPagesTokenConnection(connection, application)) return "exchange";
+ if (
+ readConfigString(broker, "tokenUrl") ||
+ readConfigString(asRecord(connection.config), "tokenExchangeUrl")
+ )
+ return "exchange";
+ return "static";
+}
+
+export function parentScopesForConnection(
+ connection: typeof toolConnections.$inferSelect,
+): string[] {
+ const config = asRecord(connection.config);
+ const broker = tokenBrokerConfig(connection);
+ const configured = [
+ ...readConfigStringArray(broker.parentScopes),
+ ...readConfigStringArray(broker.scopes),
+ ...readConfigStringArray(config.parentScopes),
+ ...readConfigStringArray(asRecord(config.oauth).scopes),
+ ...readConfigStringArray(asRecord(config.oauth).scope),
+ ];
+ const namespaceAllowlist = readConfigStringArray(
+ config.namespaceAllowlist,
+ ).map((namespace) => `pages:publish:ns/${namespace}`);
+ return [...new Set([...configured, ...namespaceAllowlist])];
+}
+
+export function defaultScopesForConnection(
+ connection: typeof toolConnections.$inferSelect,
+): string[] {
+ const broker = tokenBrokerConfig(connection);
+ return [
+ ...new Set([
+ ...readConfigStringArray(broker.defaultScopes),
+ ...readConfigStringArray(asRecord(connection.config).defaultScopes),
+ ]),
+ ];
+}
+
+export function assertScopeSubset(input: {
+ requestedScope: string[];
+ parentScopes: string[];
+}) {
+ if (input.requestedScope.length === 0) return;
+ const parent = new Set(input.parentScopes);
+ if (
+ parent.size === 0 ||
+ input.requestedScope.some((scope) => !parent.has(scope))
+ ) {
+ throw forbidden(
+ "Requested token scope exceeds the connection parent scope",
+ );
+ }
+}
+
+export function requestedTtlSeconds(
+ body: ConnectionTokenRequest,
+ connection: typeof toolConnections.$inferSelect,
+): number {
+ const broker = tokenBrokerConfig(connection);
+ const configured = Number(
+ broker.defaultTtlSeconds ?? broker.ttlSeconds ?? 900,
+ );
+ const requested = Number(body.requestedTtlSeconds ?? configured);
+ const finite =
+ Number.isFinite(requested) && requested > 0 ? Math.trunc(requested) : 900;
+ return Math.max(1, Math.min(900, finite));
+}
+
+export function sha256Hex(value: string): string {
+ return createHash("sha256").update(value).digest("hex");
+}
+
+export function bearerTokenHash(token: string): string {
+ return sha256Hex(token);
+}
+
+export function exchangeTokenUrl(
+ connection: typeof toolConnections.$inferSelect,
+ isPages: boolean,
+): string {
+ const broker = tokenBrokerConfig(connection);
+ const config = asRecord(connection.config);
+ const url =
+ readConfigString(broker, "tokenUrl") ??
+ readConfigString(broker, "exchangeTokenUrl") ??
+ readConfigString(config, "tokenExchangeUrl") ??
+ readConfigString(config, "pagesTokenExchangeUrl");
+ if (url) return url;
+ const pagesApiBase = process.env.PAPERCLIP_PAGES_API_URL?.trim();
+ if (isPages && pagesApiBase)
+ return new URL(
+ "/v1/tokens/exchange",
+ pagesApiBase.endsWith("/") ? pagesApiBase : `${pagesApiBase}/`,
+ ).toString();
+ throw unprocessable("Connection token exchange URL is not configured", {
+ code: "exchange_url_missing",
+ });
+}
+
+export function pagesNamespaceFromScope(scope: string[]): string | null {
+ const first = scope[0];
+ if (!first) return null;
+ const match = first.match(/^pages:publish:ns\/([^/\s]+)$/);
+ return match?.[1] ?? null;
+}
+
+export const CONNECTION_TOKEN_MINT_TOOL_NAME = "connection_token.mint";
diff --git a/server/src/services/tool-access/token-broker/endpoint-policy.ts b/server/src/services/tool-access/token-broker/endpoint-policy.ts
new file mode 100644
index 0000000000..306333df3b
--- /dev/null
+++ b/server/src/services/tool-access/token-broker/endpoint-policy.ts
@@ -0,0 +1,74 @@
+import { badRequest } from "../../../errors.js";
+import { assertPublicRemoteHttpEndpoint, parseRemoteHttpEndpoint } from "../../remote-http-endpoint-guard.js";
+import { type GuardedRemoteHttpFetchOptions } from "../../remote-http-fetch.js";
+import { configuredTokenBrokerExchangeUrls } from "./configuration.js";
+function normalizeTokenBrokerAllowedHost(value: string): string | null {
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+ try {
+ const parsed = new URL(
+ trimmed.includes("://") ? trimmed : `http://${trimmed}`,
+ );
+ return (
+ parsed.hostname
+ .replace(/^\[|\]$/g, "")
+ .replace(/\.$/, "")
+ .toLowerCase() || null
+ );
+ } catch {
+ // Invalid allowlist entries grant no access. The configured broker URL is
+ // still evaluated under the public-only policy below.
+ return null;
+ }
+}
+
+function tokenBrokerAllowedPrivateHosts(): Set<string> {
+ const configured = (process.env.PAPERCLIP_TOKEN_BROKER_ALLOWED_HOSTS ?? "")
+ .split(/[,\s]+/)
+ .map(normalizeTokenBrokerAllowedHost)
+ .filter((host): host is string => host !== null);
+ const pagesApiHost = normalizeTokenBrokerAllowedHost(
+ process.env.PAPERCLIP_PAGES_API_URL ?? "",
+ );
+ if (pagesApiHost) configured.push(pagesApiHost);
+ return new Set(configured);
+}
+
+function tokenBrokerAllowsPrivateNetwork(endpoint: URL): boolean {
+ const hostname = endpoint.hostname
+ .replace(/^\[|\]$/g, "")
+ .replace(/\.$/, "")
+ .toLowerCase();
+ return tokenBrokerAllowedPrivateHosts().has(hostname);
+}
+
+export function tokenBrokerHttpFetchOptions(
+ endpoint: URL,
+): GuardedRemoteHttpFetchOptions {
+ return {
+ allowPrivateNetwork: tokenBrokerAllowsPrivateNetwork(endpoint),
+ error: (message, code) => badRequest(message, { code }),
+ };
+}
+
+async function assertTokenBrokerHttpUrlAllowed(
+ value: string,
+): Promise<string> {
+ const endpoint = parseRemoteHttpEndpoint(value, (message, code) =>
+ badRequest(message, { code }),
+ );
+ await assertPublicRemoteHttpEndpoint(
+ endpoint,
+ { allowPrivateNetwork: tokenBrokerAllowsPrivateNetwork(endpoint) },
+ (message, code) => badRequest(message, { code }),
+ );
+ return endpoint.toString();
+}
+
+export async function assertConfiguredTokenBrokerEndpointsAllowed(
+ config: Record<string, unknown>,
+): Promise<void> {
+ for (const url of configuredTokenBrokerExchangeUrls(config)) {
+ await assertTokenBrokerHttpUrlAllowed(url);
+ }
+}
diff --git a/server/src/services/tool-access/token-broker/exchange.ts b/server/src/services/tool-access/token-broker/exchange.ts
new file mode 100644
index 0000000000..72b6e040d4
--- /dev/null
+++ b/server/src/services/tool-access/token-broker/exchange.ts
@@ -0,0 +1,306 @@
+import type { ActorInfo } from "../types.js";
+import { toolApplications, toolConnections } from "@paperclipai/db";
+import { badRequest, HttpError, unprocessable } from "../../../errors.js";
+import { parseRemoteHttpEndpoint } from "../../remote-http-endpoint-guard.js";
+import { guardedRemoteHttpFetch } from "../../remote-http-fetch.js";
+import { secretService } from "../../secrets.js";
+
+import { tokenBrokerHttpFetchOptions } from "./endpoint-policy.js";
+import { readConfigString, readConfigStringArray, tokenBrokerConfig, isPagesTokenConnection, exchangeTokenUrl, pagesNamespaceFromScope } from "./configuration.js";
+function asRecord(value: unknown): Record<string, unknown> {
+ if (value && typeof value === "object" && !Array.isArray(value))
+ return value as Record<string, unknown>;
+ return {};
+}
+
+export function createConnectionTokenExchange(now: () => Date, secrets: ReturnType<typeof secretService>) {
+ function accessContextForBroker(input: {
+ connection: typeof toolConnections.$inferSelect;
+ agentId: string;
+ runId: string;
+ issueId: string | null;
+ actorSource?: ActorInfo["actorType"] | null;
+ configPath: string;
+ }) {
+ return {
+ consumerType: "tool_connection" as const,
+ consumerId: input.connection.id,
+ configPath: input.configPath,
+ actorType: "agent" as const,
+ actorId: input.agentId,
+ actorSource: "agent_jwt" as const,
+ issueId: input.issueId,
+ heartbeatRunId: input.runId,
+ };
+ }
+
+ function findBrokerCredentialRef(
+ connection: typeof toolConnections.$inferSelect,
+ ) {
+ const broker = tokenBrokerConfig(connection);
+ const configuredPath =
+ readConfigString(broker, "parentCredentialConfigPath") ??
+ readConfigString(broker, "credentialConfigPath") ??
+ readConfigString(broker, "secretConfigPath");
+ const configuredName =
+ readConfigString(broker, "parentCredentialName") ??
+ readConfigString(broker, "credentialName");
+ const secretCandidates = connection.credentialSecretRefs.filter(
+ (ref) =>
+ ref.configPath !== "oauth.access_token" &&
+ ref.configPath !== "oauth.refresh_token" &&
+ ref.configPath !== "oauth.client_secret",
+ );
+ const secretRef = configuredPath
+ ? connection.credentialSecretRefs.find(
+ (ref) => ref.configPath === configuredPath,
+ )
+ : (secretCandidates.find(
+ (ref) => ref.configPath === "credentials.deploy_token",
+ ) ??
+ secretCandidates.find(
+ (ref) => ref.configPath === "pages.deploy_token",
+ ) ??
+ secretCandidates[0]);
+ if (secretRef)
+ return {
+ kind: "secret_ref" as const,
+ ref: secretRef,
+ configPath: secretRef.configPath,
+ };
+ const credentialRef = configuredName
+ ? connection.credentialRefs.find((ref) => ref.name === configuredName)
+ : connection.credentialRefs[0];
+ if (credentialRef)
+ return {
+ kind: "credential_ref" as const,
+ ref: credentialRef,
+ configPath: `credentials.${credentialRef.name}`,
+ };
+ return null;
+ }
+
+ async function resolveBrokerParentCredential(
+ input: {
+ connection: typeof toolConnections.$inferSelect;
+ agentId: string;
+ runId: string;
+ issueId: string | null;
+ },
+ secretClient: ReturnType<typeof secretService> = secrets,
+ ) {
+ const ref = findBrokerCredentialRef(input.connection);
+ if (!ref) {
+ throw unprocessable(
+ "Connection token exchange requires a vault-backed parent credential",
+ {
+ code: "parent_credential_missing",
+ },
+ );
+ }
+ if (ref.kind === "secret_ref") {
+ return secretClient.resolveSecretValue(
+ input.connection.companyId,
+ ref.ref.secretId,
+ ref.ref.versionSelector ?? "latest",
+ {
+ accessContext: accessContextForBroker({
+ ...input,
+ configPath: ref.configPath,
+ }),
+ bindingContext: accessContextForBroker({
+ ...input,
+ configPath: ref.configPath,
+ }),
+ },
+ );
+ }
+ return secretClient.resolveSecretValue(
+ input.connection.companyId,
+ ref.ref.secretId,
+ ref.ref.version ?? "latest",
+ {
+ accessContext: accessContextForBroker({
+ ...input,
+ configPath: ref.configPath,
+ }),
+ bindingContext: accessContextForBroker({
+ ...input,
+ configPath: ref.configPath,
+ }),
+ },
+ );
+ }
+
+ async function mintExchangeConnectionToken(
+ input: {
+ connection: typeof toolConnections.$inferSelect;
+ application: typeof toolApplications.$inferSelect | null;
+ agentId: string;
+ runId: string;
+ issueId: string | null;
+ responsibleUserId: string | null;
+ scope: string[];
+ ttlSeconds: number;
+ },
+ secretClient: ReturnType<typeof secretService> = secrets,
+ ) {
+ const isPages = isPagesTokenConnection(input.connection, input.application);
+ const parentToken = await resolveBrokerParentCredential(
+ input,
+ secretClient,
+ );
+ const broker = tokenBrokerConfig(input.connection);
+ const protocol =
+ readConfigString(broker, "protocol") ??
+ readConfigString(broker, "exchangeProtocol") ??
+ (isPages ? "pages" : "generic");
+ const url = exchangeTokenUrl(input.connection, isPages);
+ const actor = {
+ type: "agent",
+ id: input.agentId,
+ runId: input.runId,
+ ...(input.responsibleUserId
+ ? { onBehalfOf: `user:${input.responsibleUserId}` }
+ : {}),
+ };
+ let response: Response;
+ if (protocol === "rfc8693") {
+ const body = new URLSearchParams();
+ body.set("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange");
+ body.set("subject_token", parentToken);
+ body.set(
+ "subject_token_type",
+ readConfigString(broker, "subjectTokenType") ??
+ "urn:ietf:params:oauth:token-type:access_token",
+ );
+ body.set("scope", input.scope.join(" "));
+ const audience = readConfigString(broker, "audience");
+ if (audience) body.set("audience", audience);
+ body.set(
+ "requested_token_type",
+ readConfigString(broker, "requestedTokenType") ??
+ "urn:ietf:params:oauth:token-type:access_token",
+ );
+ body.set(
+ "actor_token",
+ Buffer.from(JSON.stringify(actor)).toString("base64url"),
+ );
+ body.set(
+ "actor_token_type",
+ readConfigString(broker, "actorTokenType") ??
+ "urn:ietf:params:oauth:token-type:jwt",
+ );
+ const endpoint = parseRemoteHttpEndpoint(url, (message, code) =>
+ badRequest(message, { code }),
+ );
+ response = await guardedRemoteHttpFetch(
+ endpoint,
+ {
+ method: "POST",
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ body,
+ },
+ tokenBrokerHttpFetchOptions(endpoint),
+ );
+ } else {
+ const namespace = isPages ? pagesNamespaceFromScope(input.scope) : null;
+ const body =
+ isPages && namespace
+ ? {
+ namespace,
+ ttlSeconds: input.ttlSeconds,
+ actions: ["publish"],
+ actor,
+ }
+ : {
+ scope: input.scope,
+ ttlSeconds: input.ttlSeconds,
+ actor,
+ audience: readConfigString(broker, "audience"),
+ };
+ const endpoint = parseRemoteHttpEndpoint(url, (message, code) =>
+ badRequest(message, { code }),
+ );
+ response = await guardedRemoteHttpFetch(
+ endpoint,
+ {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${parentToken}`,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(body),
+ },
+ tokenBrokerHttpFetchOptions(endpoint),
+ );
+ }
+ const payload = (await response.json().catch(() => ({}))) as unknown;
+ const record = asRecord(payload);
+ if (!response.ok) {
+ const code =
+ typeof record.code === "string"
+ ? record.code
+ : typeof record.error === "string"
+ ? record.error
+ : "upstream_error";
+ throw new HttpError(
+ response.status === 401 || response.status === 403 ? 409 : 502,
+ "Connection token exchange failed",
+ {
+ code:
+ code === "parent_revoked" ? "credential_revoked" : "upstream_error",
+ upstreamCode: code,
+ upstreamStatus: response.status,
+ upstreamRequestId:
+ typeof record.requestId === "string" ? record.requestId : null,
+ },
+ );
+ }
+ const token =
+ typeof record.token === "string"
+ ? record.token
+ : typeof record.access_token === "string"
+ ? record.access_token
+ : null;
+ if (!token)
+ throw new HttpError(
+ 502,
+ "Connection token exchange did not return a token",
+ { code: "upstream_token_missing" },
+ );
+ const expiresIn =
+ typeof record.expires_in === "number"
+ ? record.expires_in
+ : Number(record.expires_in);
+ const expiresAt =
+ typeof record.expiresAt === "string" &&
+ Number.isFinite(Date.parse(record.expiresAt))
+ ? new Date(record.expiresAt)
+ : typeof record.expires_at === "string" &&
+ Number.isFinite(Date.parse(record.expires_at))
+ ? new Date(record.expires_at)
+ : new Date(
+ now().getTime() +
+ Math.min(
+ input.ttlSeconds,
+ Number.isFinite(expiresIn) && expiresIn > 0
+ ? expiresIn
+ : input.ttlSeconds,
+ ) *
+ 1000,
+ );
+ const responseScope =
+ readConfigStringArray(record.scope).length > 0
+ ? readConfigStringArray(record.scope)
+ : input.scope;
+ return {
+ token,
+ tokenType:
+ typeof record.token_type === "string" ? record.token_type : "Bearer",
+ expiresAt,
+ scope: responseScope,
+ };
+ }
+ return mintExchangeConnectionToken;
+}
diff --git a/server/src/services/tool-access/token-broker/issuance.ts b/server/src/services/tool-access/token-broker/issuance.ts
new file mode 100644
index 0000000000..988b583a28
--- /dev/null
+++ b/server/src/services/tool-access/token-broker/issuance.ts
@@ -0,0 +1,95 @@
+import type { ToolAccessMutationDb } from "../types.js";
+import type { Db } from "@paperclipai/db";
+import { connectionTokenIssuances } from "@paperclipai/db";
+import type { ConnectionTokenIssuanceOutcome, ConnectionTokenIssuancePath } from "@paperclipai/shared";
+import { logActivity } from "../../activity-log.js";
+
+import type { ToolAccessAudit } from "../audit.js";
+export function createTokenIssuanceRecorder(db: Db, audit: ToolAccessAudit) {
+ async function recordConnectionTokenIssuance(
+ input: {
+ companyId: string;
+ applicationId: string | null;
+ connectionId: string;
+ agentId: string;
+ runId: string | null;
+ issueId: string | null;
+ projectId: string | null;
+ responsibleUserId: string | null;
+ path: ConnectionTokenIssuancePath;
+ requestedScope: string[];
+ issuedScope: string[];
+ ttlSeconds: number | null;
+ expiresAt: Date | null;
+ tokenHash: string | null;
+ outcome: ConnectionTokenIssuanceOutcome;
+ errorCode?: string | null;
+ metadata?: Record<string, unknown>;
+ },
+ dbClient: ToolAccessMutationDb = db,
+ ) {
+ await dbClient.insert(connectionTokenIssuances).values({
+ companyId: input.companyId,
+ applicationId: input.applicationId,
+ connectionId: input.connectionId,
+ agentId: input.agentId,
+ runId: input.runId,
+ issueId: input.issueId,
+ projectId: input.projectId,
+ responsibleUserId: input.responsibleUserId,
+ path: input.path,
+ requestedScope: input.requestedScope,
+ issuedScope: input.issuedScope,
+ ttlSeconds: input.ttlSeconds,
+ expiresAt: input.expiresAt,
+ tokenHash: input.tokenHash,
+ outcome: input.outcome,
+ errorCode: input.errorCode ?? null,
+ metadata: input.metadata ?? {},
+ });
+ }
+
+ async function auditConnectionTokenIssuance(input: {
+ companyId: string;
+ connectionId: string;
+ agentId: string;
+ runId: string;
+ path: ConnectionTokenIssuancePath;
+ outcome: ConnectionTokenIssuanceOutcome;
+ reasonCode?: string | null;
+ details?: Record<string, unknown>;
+ }) {
+ const success = input.outcome === "success";
+ await audit({
+ companyId: input.companyId,
+ connectionId: input.connectionId,
+ action: success ? "connection_token.minted" : "connection_token.denied",
+ outcome: success ? "success" : "failure",
+ reasonCode: input.reasonCode ?? null,
+ actor: { actorType: "agent", actorId: input.agentId },
+ details: {
+ path: input.path,
+ outcome: input.outcome,
+ runId: input.runId,
+ ...(input.details ?? {}),
+ },
+ });
+ await logActivity(db, {
+ companyId: input.companyId,
+ actorType: "agent",
+ actorId: input.agentId,
+ agentId: input.agentId,
+ runId: input.runId,
+ action: success ? "connection_token.minted" : "connection_token.denied",
+ entityType: "tool_connection",
+ entityId: input.connectionId,
+ details: {
+ path: input.path,
+ outcome: input.outcome,
+ reasonCode: input.reasonCode ?? null,
+ ...(input.details ?? {}),
+ },
+ });
+ }
+ return { recordConnectionTokenIssuance, auditConnectionTokenIssuance };
+}
diff --git a/server/src/services/tool-access/token-broker/service.ts b/server/src/services/tool-access/token-broker/service.ts
new file mode 100644
index 0000000000..f6757e383b
--- /dev/null
+++ b/server/src/services/tool-access/token-broker/service.ts
@@ -0,0 +1,755 @@
+import { isDaytonaConnection } from "../../daytona.js";
+import { isBrowserUseConnection } from "../../browser-use-client.js";
+import { and, eq, sql } from "drizzle-orm";
+import type { Db } from "@paperclipai/db";
+import { connectionGrantMembers, connectionGrantDelegations, connectionGrants, companyMemberships, toolApplications, toolConnectionInstalls, toolConnections } from "@paperclipai/db";
+import type { ConnectionTokenIssuanceOutcome, ConnectionTokenRequest, ConnectionTokenResponse } from "@paperclipai/shared";
+import { forbidden, HttpError, unprocessable } from "../../../errors.js";
+import { secretService } from "../../secrets.js";
+import { toolAccessPolicyService } from "../../tool-access-policy.js";
+import type { ToolAccessAudit } from "../audit.js";
+import { createTokenBrokerAdmission, lockAuthorizedBrokerResponsibleMembership } from "./admission.js";
+import { createTokenIssuanceRecorder } from "./issuance.js";
+import { createConnectionTokenExchange } from "./exchange.js";
+import { CONNECTION_TOKEN_MINT_TOOL_NAME, assertScopeSubset, bearerTokenHash, connectionTokenBrokerEnabled, defaultScopesForConnection, inferConnectionTokenPath, normalizeConnectionTokenScopes, parentScopesForConnection, requestedTtlSeconds } from "./configuration.js";
+type TokenBrokerDependencies = {
+ now: () => Date;
+ secrets: ReturnType<typeof secretService>;
+ policySvc: Pick<ReturnType<typeof toolAccessPolicyService>, "decide" | "writeAudit">;
+ audit: ToolAccessAudit;
+ getConnectionRow(idOrUid: string, companyId?: string): Promise<typeof toolConnections.$inferSelect>;
+ ensureDefaultOrganizationGrant(connection: typeof toolConnections.$inferSelect): Promise<typeof connectionGrants.$inferSelect>;
+};
+
+function asRecord(value: unknown): Record<string, unknown> {
+ if (value && typeof value === "object" && !Array.isArray(value))
+ return value as Record<string, unknown>;
+ return {};
+}
+
+export function createConnectionTokenBroker(db: Db, { now, secrets, policySvc, audit, getConnectionRow, ensureDefaultOrganizationGrant }: TokenBrokerDependencies) {
+ const { loadBrokerRunContext, enforceDefaultConnectionTokenRateLimit, hasExplicitConnectionTokenMintProfileGrant } = createTokenBrokerAdmission(db, now);
+ const { recordConnectionTokenIssuance, auditConnectionTokenIssuance } = createTokenIssuanceRecorder(db, audit);
+ const mintExchangeConnectionToken = createConnectionTokenExchange(now, secrets);
+ async function getConnectionApplication(
+ connection: typeof toolConnections.$inferSelect,
+ ) {
+ const [application] = await db
+ .select()
+ .from(toolApplications)
+ .where(eq(toolApplications.id, connection.applicationId));
+ return application ?? null;
+ }
+ return {
+ loadBrokerRunContext,
+ mintConnectionTokenForAgent: async (input: {
+ connectionId: string;
+ companyId: string;
+ agentId: string;
+ runId: string;
+ body: ConnectionTokenRequest;
+ }): Promise<ConnectionTokenResponse> => {
+ const runContext = await loadBrokerRunContext({
+ companyId: input.companyId,
+ agentId: input.agentId,
+ runId: input.runId,
+ });
+ const connection = await getConnectionRow(
+ input.connectionId,
+ input.companyId,
+ );
+ if (isDaytonaConnection(connection)) throw forbidden("Daytona credentials stay in the governed tool gateway and cannot be exported.");
+ if (isBrowserUseConnection(connection)) throw forbidden("Browser Use credentials stay in the governed tool gateway and cannot be exported.");
+ if (connection.connectionPurpose === "ai") throw unprocessable("AI credentials are available only through the runtime resolver");
+ const application = await getConnectionApplication(connection);
+ const brokerEnabled = connectionTokenBrokerEnabled(connection);
+ const path = brokerEnabled
+ ? inferConnectionTokenPath(connection, application)
+ : "static";
+ const requestedScope = normalizeConnectionTokenScopes(input.body.scope);
+ const parentScopes = parentScopesForConnection(connection);
+ const fallbackScopes = defaultScopesForConnection(connection);
+ const issuedScope =
+ requestedScope.length > 0
+ ? requestedScope
+ : fallbackScopes.length > 0
+ ? fallbackScopes
+ : parentScopes;
+ const ttlSeconds = requestedTtlSeconds(input.body, connection);
+ const attribution = {
+ agentId: input.agentId,
+ runId: input.runId,
+ issueId: runContext.issueId,
+ projectId: runContext.projectId,
+ responsibleUserId: runContext.responsibleUserId,
+ };
+
+ const recordFailure = async (
+ outcome: ConnectionTokenIssuanceOutcome,
+ errorCode: string,
+ details: Record<string, unknown> = {},
+ ) => {
+ await recordConnectionTokenIssuance({
+ companyId: connection.companyId,
+ applicationId: connection.applicationId,
+ connectionId: connection.id,
+ agentId: input.agentId,
+ runId: input.runId,
+ issueId: runContext.issueId,
+ projectId: runContext.projectId,
+ responsibleUserId: runContext.responsibleUserId,
+ path,
+ requestedScope,
+ issuedScope,
+ ttlSeconds: outcome === "use_env_lease" ? null : ttlSeconds,
+ expiresAt: null,
+ tokenHash: null,
+ outcome,
+ errorCode,
+ metadata: details,
+ });
+ await auditConnectionTokenIssuance({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ agentId: input.agentId,
+ runId: input.runId,
+ path,
+ outcome,
+ reasonCode: errorCode,
+ details,
+ });
+ };
+
+ const fail = async (
+ status: number,
+ message: string,
+ outcome: ConnectionTokenIssuanceOutcome,
+ errorCode: string,
+ details: Record<string, unknown> = {},
+ ): Promise<never> => {
+ await recordFailure(outcome, errorCode, details);
+ throw new HttpError(status, message, {
+ code: errorCode,
+ path,
+ ...details,
+ });
+ };
+
+ const [install] = await db
+ .select({ id: toolConnectionInstalls.id })
+ .from(toolConnectionInstalls)
+ .where(
+ and(
+ eq(toolConnectionInstalls.companyId, connection.companyId),
+ eq(toolConnectionInstalls.connectionId, connection.id),
+ sql`((${toolConnectionInstalls.targetType} = 'company' and ${toolConnectionInstalls.targetId} = ${connection.companyId}) or (${toolConnectionInstalls.targetType} = 'agent' and ${toolConnectionInstalls.targetId} = ${input.agentId}))`,
+ ),
+ )
+ .limit(1);
+ if (!install) {
+ await fail(
+ 403,
+ `Connection ${connection.name} must be installed for this agent before it can mint a token`,
+ "denied",
+ "installation_required",
+ {
+ connection: {
+ id: connection.id,
+ uid: connection.uid,
+ name: connection.name,
+ },
+ agentId: input.agentId,
+ remediation: {
+ action: "install_connection",
+ targetType: "agent",
+ targetId: input.agentId,
+ },
+ },
+ );
+ }
+
+ if (
+ runContext.run.activeIdentityContextId &&
+ (connection.config.sourceTemplateKey === "github" ||
+ connection.transportConfig?.sourceTemplateKey === "github")
+ ) {
+ await fail(
+ 409,
+ "Use managed git, gh, or GitHub tools for this run",
+ "denied",
+ "managed_github_invocation_required",
+ );
+ }
+ const requestedSubject = input.body.subject;
+ if (
+ requestedSubject?.type === "user" &&
+ requestedSubject.userId !== runContext.responsibleUserId
+ ) {
+ await fail(
+ 403,
+ "The agent run cannot act as the requested user",
+ "denied",
+ "subject_not_permitted",
+ {
+ connection: { uid: connection.uid },
+ subject: requestedSubject,
+ },
+ );
+ }
+
+ const actingUserId = runContext.responsibleUserId;
+ const autonomous =
+ runContext.run.invocationSource === "automation" ||
+ runContext.run.invocationSource === "timer";
+ let subject: { type: "app" } | { type: "user"; userId: string } =
+ connection.credentialPolicy === "shared" ||
+ connection.credentialPolicy === "per_agent" ||
+ !actingUserId
+ ? { type: "app" as const }
+ : { type: "user" as const, userId: actingUserId };
+ let grant: typeof connectionGrants.$inferSelect | undefined;
+ if (connection.credentialPolicy === "per_agent") {
+ [grant] = await db
+ .select()
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "agent"),
+ eq(connectionGrants.subjectAgentId, input.agentId),
+ ),
+ )
+ .limit(1);
+ if (!grant) {
+ await fail(
+ 409,
+ "This agent's dedicated authorization is required",
+ "denied",
+ "agent_authorization_required",
+ {
+ connection: { uid: connection.uid },
+ agentId: input.agentId,
+ remediation: {
+ action: "start_agent_authorization",
+ agentId: input.agentId,
+ },
+ },
+ );
+ }
+ } else if (connection.credentialPolicy !== "shared" && actingUserId) {
+ // Installation targets express the grant owner's consent to agent use;
+ // the control-plane-resolved responsible user selects whose grant is in
+ // force. A separate standing delegation is required only when no such
+ // responsible user exists for unattended work.
+ const [membership] = await db
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, connection.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, actingUserId),
+ eq(companyMemberships.status, "active"),
+ ),
+ )
+ .limit(1);
+ if (!membership) {
+ await fail(
+ 403,
+ "The personal grant owner is not an active company member",
+ "denied",
+ "grant_owner_membership_inactive",
+ {
+ connection: {
+ id: connection.id,
+ uid: connection.uid,
+ name: connection.name,
+ },
+ subject: { type: "user", userId: actingUserId },
+ remediation: { action: "restore_membership_or_reconnect" },
+ },
+ );
+ }
+ [grant] = await db
+ .select()
+ .from(connectionGrants)
+ .where(
+ and(
+ eq(connectionGrants.companyId, connection.companyId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "user"),
+ eq(connectionGrants.subjectUserId, actingUserId),
+ ),
+ )
+ .limit(1);
+ } else if (connection.credentialPolicy === "per_user" && autonomous) {
+ const delegated = await db
+ .select({ grant: connectionGrants })
+ .from(connectionGrantDelegations)
+ .innerJoin(
+ connectionGrants,
+ and(
+ eq(connectionGrants.id, connectionGrantDelegations.grantId),
+ eq(
+ connectionGrants.companyId,
+ connectionGrantDelegations.companyId,
+ ),
+ ),
+ )
+ .where(
+ and(
+ eq(connectionGrantDelegations.companyId, connection.companyId),
+ eq(connectionGrantDelegations.agentId, input.agentId),
+ eq(connectionGrants.connectionId, connection.id),
+ eq(connectionGrants.kind, "user"),
+ ),
+ )
+ .limit(2);
+ if (delegated.length > 1) {
+ await fail(
+ 409,
+ "More than one delegated personal authorization matches this run",
+ "denied",
+ "subject_not_permitted",
+ {
+ connection: { uid: connection.uid },
+ agentId: input.agentId,
+ },
+ );
+ }
+ grant = delegated[0]?.grant;
+ if (grant?.subjectUserId)
+ subject = { type: "user", userId: grant.subjectUserId };
+ }
+ if (!grant && connection.credentialPolicy === "per_user") {
+ await fail(
+ 409,
+ "User authorization is required",
+ "denied",
+ "user_authorization_required",
+ {
+ connection: { uid: connection.uid },
+ subject: actingUserId
+ ? { type: "user", userId: actingUserId }
+ : { type: "app" },
+ remediation: { action: "start_authorization" },
+ },
+ );
+ }
+ if (!grant) {
+ grant = await ensureDefaultOrganizationGrant(connection);
+ }
+
+ if (
+ grant.kind === "user" &&
+ grant.subjectUserId &&
+ grant.subjectUserId !== actingUserId
+ ) {
+ const [membership] = await db
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, connection.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, grant.subjectUserId),
+ eq(companyMemberships.status, "active"),
+ ),
+ )
+ .limit(1);
+ if (!membership) {
+ await fail(
+ 403,
+ "The delegated personal grant owner is not an active company member",
+ "denied",
+ "grant_owner_membership_inactive",
+ {
+ connection: {
+ id: connection.id,
+ uid: connection.uid,
+ name: connection.name,
+ },
+ subject,
+ remediation: { action: "restore_membership_or_reconnect" },
+ },
+ );
+ }
+ }
+
+ if (grant.kind === "organization") {
+ const activeAudienceMember = actingUserId
+ ? await db
+ .select({ id: companyMemberships.id })
+ .from(companyMemberships)
+ .where(
+ and(
+ eq(companyMemberships.companyId, connection.companyId),
+ eq(companyMemberships.principalType, "user"),
+ eq(companyMemberships.principalId, actingUserId),
+ eq(companyMemberships.status, "active"),
+ ),
+ )
+ .limit(1)
+ .then((rows) => rows[0] ?? null)
+ : null;
+ const audience = await db
+ .select({ subjectId: connectionGrantMembers.subjectId })
+ .from(connectionGrantMembers)
+ .where(
+ and(
+ eq(connectionGrantMembers.companyId, connection.companyId),
+ eq(connectionGrantMembers.grantId, grant.id),
+ eq(connectionGrantMembers.subjectType, "user"),
+ ),
+ );
+ if (
+ (actingUserId !== null && !activeAudienceMember) ||
+ (audience.length > 0 &&
+ (!actingUserId ||
+ !audience.some((member) => member.subjectId === actingUserId)))
+ ) {
+ await fail(
+ 403,
+ "The acting user is not in this grant's audience",
+ "denied",
+ "grant_audience_denied",
+ {
+ connection: { uid: connection.uid },
+ subject,
+ grantId: grant.id,
+ },
+ );
+ }
+ }
+
+ if (grant.status !== "active") {
+ const code =
+ grant.status === "needs_reauthorization"
+ ? "needs_reauthorization"
+ : "grant_revoked";
+ await fail(
+ 409,
+ "The selected connection grant is not active",
+ "denied",
+ code,
+ {
+ connection: { uid: connection.uid },
+ subject,
+ grantId: grant.id,
+ remediation: { action: "reauthorize" },
+ },
+ );
+ }
+ const requestedScopeSelectors = new Set(requestedScope);
+ const matchingScopedRefs = grant.credentialSecretRefs.filter(
+ (ref) => ref.keyScope && requestedScopeSelectors.has(ref.keyScope),
+ );
+ const selectedCredentialSecretRefs =
+ matchingScopedRefs.length > 0
+ ? grant.credentialSecretRefs.filter(
+ (ref) =>
+ !ref.keyScope || requestedScopeSelectors.has(ref.keyScope),
+ )
+ : grant.credentialSecretRefs.filter((ref) => !ref.keyScope);
+ const rotateBefore = Date.now() + 14 * 24 * 60 * 60 * 1000;
+ const expiringRef = selectedCredentialSecretRefs.find(
+ (ref) => ref.expiresAt && Date.parse(ref.expiresAt) <= rotateBefore,
+ );
+ if (expiringRef && connection.healthStatus !== "degraded") {
+ await db
+ .update(toolConnections)
+ .set({
+ healthStatus: "degraded",
+ healthMessage: `Rotate ${expiringRef.label ?? expiringRef.configPath} before it expires.`,
+ updatedAt: new Date(),
+ })
+ .where(eq(toolConnections.id, connection.id));
+ }
+ const credentialConnection = {
+ ...connection,
+ credentialSecretRefs: selectedCredentialSecretRefs,
+ };
+
+ if (!connection.enabled || connection.status !== "active") {
+ await fail(
+ 409,
+ "Connection is not active",
+ "denied",
+ "connection_not_active",
+ {
+ connectionStatus: connection.status,
+ enabled: connection.enabled,
+ },
+ );
+ }
+ if (
+ ["failed", "error", "missing_secret"].includes(connection.healthStatus)
+ ) {
+ await fail(
+ 409,
+ "Connection credential needs attention",
+ "denied",
+ "credential_revoked",
+ {
+ healthStatus: connection.healthStatus,
+ healthMessage: connection.healthMessage ?? null,
+ },
+ );
+ }
+ if (!brokerEnabled) {
+ await fail(
+ 403,
+ "Connection token broker is not enabled for this connection",
+ "denied",
+ "broker_not_enabled",
+ {
+ reason:
+ "Connections must explicitly opt in with tokenBroker.enabled before agents can request brokered tokens.",
+ },
+ );
+ }
+ try {
+ assertScopeSubset({ requestedScope: issuedScope, parentScopes });
+ } catch {
+ await fail(
+ 403,
+ "Requested token scope exceeds the connection parent scope",
+ "denied",
+ "scope_exceeds_parent",
+ {
+ parentScopeCount: parentScopes.length,
+ },
+ );
+ }
+
+ const hasBrokerGrant = await hasExplicitConnectionTokenMintProfileGrant({
+ companyId: connection.companyId,
+ agentId: input.agentId,
+ issueId: runContext.issueId,
+ projectId: runContext.projectId,
+ routineId: runContext.routineId,
+ });
+ if (!hasBrokerGrant) {
+ await fail(
+ 403,
+ "Connection token minting requires an explicit broker profile grant",
+ "denied",
+ "broker_mint_not_granted",
+ {
+ reason:
+ "A connection-level profile grant is not sufficient for connection_token.mint.",
+ },
+ );
+ }
+
+ const decisionInput = {
+ companyId: connection.companyId,
+ actor: {
+ actorType: "agent" as const,
+ actorId: input.agentId,
+ agentId: input.agentId,
+ },
+ runContext: {
+ heartbeatRunId: input.runId,
+ issueId: runContext.issueId,
+ projectId: runContext.projectId,
+ routineId: runContext.routineId,
+ },
+ request: {
+ applicationId: connection.applicationId,
+ connectionId: connection.id,
+ providerType: "connection_token_broker",
+ applicationKey: application?.applicationKey ?? null,
+ upstreamToolName: CONNECTION_TOKEN_MINT_TOOL_NAME,
+ riskLevel: "write",
+ toolName: CONNECTION_TOKEN_MINT_TOOL_NAME,
+ arguments: {
+ path,
+ scope: issuedScope,
+ requestedTtlSeconds: input.body.requestedTtlSeconds ?? null,
+ },
+ },
+ consumeRateLimit: true,
+ };
+ const decision = await policySvc.decide(decisionInput);
+ await policySvc.writeAudit(decisionInput, decision);
+ if (!decision.allowed) {
+ await fail(
+ decision.decision === "rate_limited" ? 429 : 403,
+ decision.explanation,
+ decision.decision === "rate_limited" ? "rate_limited" : "denied",
+ decision.reasonCode,
+ {
+ decision: decision.decision,
+ effectiveProfileIds: decision.effectiveProfileIds,
+ matchedPolicyIds: decision.matchedPolicyIds,
+ rateLimitState: decision.rateLimitState ?? null,
+ },
+ );
+ }
+
+ try {
+ await enforceDefaultConnectionTokenRateLimit({
+ connection,
+ agentId: input.agentId,
+ path,
+ });
+ } catch (error) {
+ if (error instanceof HttpError && error.status === 429) {
+ await fail(
+ 429,
+ error.message,
+ "rate_limited",
+ "rate_limited",
+ asRecord(error.details),
+ );
+ }
+ throw error;
+ }
+
+ if (path === "static") {
+ await recordFailure("use_env_lease", "use_env_lease", {
+ reason:
+ "Connection uses durable static credentials; broker token delivery is refused.",
+ });
+ return {
+ status: "use_env_lease",
+ code: "use_env_lease",
+ connectionId: connection.id,
+ connection: { id: connection.id, uid: connection.uid },
+ grantId: grant.id,
+ path: "static",
+ message:
+ "This connection uses static credentials. Use an audited environment lease projection instead.",
+ scope: issuedScope,
+ attribution,
+ };
+ }
+ if (path === "oauth_access") {
+ await fail(
+ 422,
+ "OAuth access-token projection is disabled; configure a short-lived exchange mint path instead",
+ "denied",
+ "oauth_access_projection_disabled",
+ {
+ reason:
+ "The broker must not return stored upstream OAuth bearer tokens directly.",
+ },
+ );
+ }
+
+ const selectedGrant = grant;
+ try {
+ const mintResult = await db.transaction(async (tx) => {
+ await lockAuthorizedBrokerResponsibleMembership(
+ {
+ companyId: connection.companyId,
+ responsibleUserId: runContext.responsibleUserId,
+ },
+ tx,
+ );
+ const minted = await mintExchangeConnectionToken(
+ {
+ connection: credentialConnection,
+ application,
+ agentId: input.agentId,
+ runId: input.runId,
+ issueId: runContext.issueId,
+ responsibleUserId: runContext.responsibleUserId,
+ scope: issuedScope,
+ ttlSeconds,
+ },
+ secretService(tx),
+ );
+ const expiresAt = minted.expiresAt;
+ const mintedScope = "scope" in minted ? minted.scope : issuedScope;
+ const effectiveTtlSeconds = Math.max(
+ 1,
+ Math.min(
+ 900,
+ Math.ceil((expiresAt.getTime() - now().getTime()) / 1000),
+ ),
+ );
+ const tokenHash = bearerTokenHash(minted.token);
+ await recordConnectionTokenIssuance(
+ {
+ companyId: connection.companyId,
+ applicationId: connection.applicationId,
+ connectionId: connection.id,
+ agentId: input.agentId,
+ runId: input.runId,
+ issueId: runContext.issueId,
+ projectId: runContext.projectId,
+ responsibleUserId: runContext.responsibleUserId,
+ path,
+ requestedScope,
+ issuedScope: mintedScope,
+ ttlSeconds: effectiveTtlSeconds,
+ expiresAt,
+ tokenHash,
+ outcome: "success",
+ metadata: { tokenRef: tokenHash, tokenType: minted.tokenType },
+ },
+ tx,
+ );
+ await tx
+ .update(connectionGrants)
+ .set({ lastUsedAt: new Date(), updatedAt: new Date() })
+ .where(eq(connectionGrants.id, selectedGrant.id));
+ return {
+ minted,
+ expiresAt,
+ mintedScope,
+ effectiveTtlSeconds,
+ tokenHash,
+ };
+ });
+ await auditConnectionTokenIssuance({
+ companyId: connection.companyId,
+ connectionId: connection.id,
+ agentId: input.agentId,
+ runId: input.runId,
+ path,
+ outcome: "success",
+ details: {
+ ttlSeconds: mintResult.effectiveTtlSeconds,
+ scopeCount: mintResult.mintedScope.length,
+ tokenRef: mintResult.tokenHash,
+ },
+ });
+ return {
+ status: "minted",
+ connectionId: connection.id,
+ connection: { id: connection.id, uid: connection.uid },
+ grantId: selectedGrant.id,
+ providerTenantId: selectedGrant.providerTenant?.externalId,
+ path: "exchange",
+ token: mintResult.minted.token,
+ tokenType: mintResult.minted.tokenType,
+ expiresAt: mintResult.expiresAt.toISOString(),
+ ttlSeconds: mintResult.effectiveTtlSeconds,
+ scope: mintResult.mintedScope,
+ attribution,
+ };
+ } catch (error) {
+ const details =
+ error instanceof HttpError && asRecord(error.details).code
+ ? asRecord(error.details)
+ : {};
+ const errorCode =
+ typeof details.code === "string" ? details.code : "mint_failed";
+ const outcome: ConnectionTokenIssuanceOutcome =
+ errorCode === "upstream_error" ||
+ errorCode === "upstream_token_missing"
+ ? "upstream_error"
+ : "failure";
+ await recordFailure(outcome, errorCode, {
+ ...details,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ throw error;
+ }
+ }
+ };
+}