import { createHash } from "node:crypto"; import { apiIntegrationRequiredApprovals, apiIntegrationToolMeaningUnchanged, } from "./api-integration-approvals"; import { resolveConnectorActionPolicy, connectorActionPolicyDecision, } from "./connector-action-policy"; import { assertOrganizationIntegrationAllowed, stableJson, type ApiIntegrationAuthPreview, type IntegrationSourceInput, type McpServerConnectionRef, } from "@opengeni/contracts"; import { and, asc, eq, inArray, ne, or, sql } from "drizzle-orm"; import { assertCapabilityComponentVersionCanChange, effectiveCapabilityOwnerSql, lockCapabilityComponentIdentity, } from "./capability-components"; import { setSubjectRlsContext, withRlsContext, withWorkspaceRls, withWorkspaceSubjectRls, type Database, } from "./database"; import { connectionScopeKey } from "./connection-scopes"; import { withOrganizationIntegrationPolicyFence } from "./organization-integration-policy"; import { ensureIntegrationFacetDefinition, IntegrationChangeRequiresAdminError, integrationBindingKey, integrationDefinitionHasBindingOwner, integrationRuntimeKey, listIntegrationFacetBindingOwners, removeIntegrationFacetBindingOwner, upsertIntegrationFacetBinding, type IntegrationFacetBindingOwner, } from "./integration-bindings"; import { organizationApiIntegrationDefinition, organizationConnectorLogin, } from "./organization-connectors"; import * as schema from "./schema"; export type ApiIntegrationProtocol = "openapi" | "graphql"; export type ApiIntegrationToolSafety = "read" | "write" | "destructive"; export type ApiIntegrationApprovalMode = "never" | "ask"; export type ApiIntegrationFacetDefinition = { readonly facetKey: string; readonly kind: "inbound_trigger" | "delivery_destination" | "identity_link"; readonly configSchema: Readonly>; readonly capabilities: Readonly>; }; export type ApiIntegrationToolDefinition = { readonly id: string; readonly operationKey: string; readonly name: string; readonly description: string; readonly inputSchema: Readonly>; readonly outputSchema?: Readonly>; readonly safety: ApiIntegrationToolSafety; readonly approvalMode: ApiIntegrationApprovalMode; readonly deprecated: boolean; }; type StoredApiIntegrationRevisionBase = { readonly id: string; readonly definitionId: string; readonly contentSha256: string; readonly source: { readonly url?: string; readonly provider?: string; readonly fetchedAt?: string; }; readonly title: string; readonly description?: string; readonly version?: string; readonly tools: readonly ApiIntegrationToolDefinition[]; }; export type StoredOpenApiOperationBinding = { readonly method: "get" | "put" | "post" | "delete" | "patch" | "head" | "options" | "trace"; readonly pathTemplate: string; readonly serverUrl: string; readonly parameters: readonly { readonly name: string; readonly location: "path" | "query" | "header" | "cookie"; readonly required: boolean; readonly schema: Readonly>; readonly description?: string; }[]; readonly requestBody?: { readonly required: boolean; readonly contentTypes: readonly string[]; readonly schemas: Readonly>>>; }; readonly requiredScopeAlternatives?: readonly (readonly string[])[]; /** Reviewed Microsoft Search entity types a read-only search may request. */ readonly searchEntityTypes?: readonly string[]; /** One of the generic find and call tools of a reviewed definition's path scope. */ readonly genericPath?: { readonly role: "find" | "read" | "change"; readonly operations?: readonly { readonly method: "get" | "put" | "post" | "delete" | "patch"; readonly path: string; readonly summary?: string; readonly scopes?: readonly (readonly string[])[]; }[]; }; }; export type StoredGraphqlOperationBinding = { readonly kind: "query" | "mutation"; readonly fieldName: string; readonly operationName: string; readonly variableDefinitions: readonly string[]; readonly variableNames: readonly string[]; readonly defaultSelection?: string; readonly selectionAllowed: boolean; }; /** Protocol-normalized immutable revision persisted in integration_spec_revisions.spec. */ export type StoredApiIntegrationRevision = | (StoredApiIntegrationRevisionBase & { readonly protocol: "openapi"; readonly bindings: Readonly>; }) | (StoredApiIntegrationRevisionBase & { readonly protocol: "graphql"; readonly bindings: Readonly>; }); export type InstallApiIntegrationInput = { accountId: string; workspaceId: string; subjectId: string; capabilityId: string; pluginKey: string; serverId: string; name: string; description?: string | null; category?: string; tags?: string[]; definitionId: string; definitionProvenance: "curated" | "workspace"; provider?: string; providerDomain: string; protocol: ApiIntegrationProtocol; baseUrl: string; sourceUrl?: string | null; authScheme?: Record; connectionId?: string | null; instanceKey?: string; displayName?: string; expectedInstanceVersion?: number; requiredScopes?: string[]; ownership?: "workspace" | "subject" | "either"; allowedTools?: string[]; /** * Selected write/destructive tools that run without per-call human approval. * Removing an approval requirement is never a permission reduction, so it * always passes installation acquisition (organization policy) again. */ autoApprovedTools?: string[]; facetDefinitions?: readonly ApiIntegrationFacetDefinition[]; revision: StoredApiIntegrationRevision; owner?: ApiIntegrationOwner; /** * A member's add (no integration management): create only. An instance that * is already set up, or a new revision that would move the other instances, * throws {@link IntegrationChangeRequiresAdminError} inside the transaction. */ memberCreate?: boolean; }; export type InstalledApiIntegration = { capabilityId: string; pluginId: string; pluginVersionId: string; integrationFacetId: string; apiFacetId: string; pluginInstallationId: string; integrationFacetInstallationId: string; apiFacetInstallationId: string; installationVersion: number; instanceId: string; instanceKey: string; displayName: string; instanceVersion: number; revisionId: string; serverId: string; status: "installed"; }; export type ApiIntegrationRuntime = { capabilityId: string; pluginKey: string; pluginInstallationId: string; installationVersion: number; instanceId: string; instanceKey: string; displayName: string; instanceVersion: number; serverId: string; name: string; description: string | null; protocol: ApiIntegrationProtocol; definitionId: string; definitionProvenance: "curated" | "workspace"; baseUrl: string; sourceUrl: string | null; providerDomain: string; authScheme: Record; connectionRef: McpServerConnectionRef | null; /** The bound connection's status (`active`, `needs_reauth`, `revoked`, `error`); null without one. */ connectionStatus: string | null; /** When the bound connection was last used (ISO time); null without one or before first use. */ connectionLastUsedAt: string | null; /** Live credential authority revision used to invalidate stale human approvals. */ connectionAuthorityGeneration: number | null; allowedTools: string[]; requireApproval: true | string[]; revision: StoredApiIntegrationRevision; /** * Set when the organization serves it here (an organization connector of * kind "api"), not an installation of this workspace's own. */ organizationConnector?: { id: string; generation: number; login: "each_person" | "organization_key" | "none"; /** How the API authenticates, as the organization reviewed it. */ auth: ApiIntegrationAuthPreview; }; /** * An organization key: where each credential goes and its encrypted value, * decrypted only by the adapter that sends it. */ organizationCredential?: { placements: readonly OrganizationApiCredentialPlacement[]; }; /** Who added this instance (a member removes only their own); set by the installed list. */ instanceCreatedBySubjectId?: string; }; /** One encrypted credential placement of an organization key for an API integration. */ export type OrganizationApiCredentialPlacement = { carrier: "header" | "query" | "cookie"; name: string; prefix?: string; valueEncrypted: string; }; /** The instance key an organization's API integration runs under in every workspace it reaches. */ export const ORGANIZATION_API_INTEGRATION_INSTANCE_KEY = "organization"; /** Bound to an account that is signed in now; an expired or revoked one needs reconnecting. */ export function apiIntegrationConnected( integration: Pick, ): boolean { return integration.connectionRef !== null && integration.connectionStatus === "active"; } export type ApiIntegrationOwner = { kind: "direct" | "plugin" | "migration"; id: string; removable: boolean; }; export type ApiIntegrationUninstallPreview = { capabilityId: string; instanceKey: string; displayName: string | null; installed: boolean; installationVersion: number | null; instanceVersion: number | null; directOwner: ApiIntegrationOwner | null; remainingOwners: ApiIntegrationOwner[]; removesRuntimeIntegration: boolean; removesDefinition: boolean; }; export type UninstallApiIntegrationResult = { capabilityId: string; instanceKey: string; status: "not_installed" | "uninstalled" | "retained_by_other_owners"; remainingOwners: ApiIntegrationOwner[]; definitionStatus: "retained" | "disabled"; }; export class ApiIntegrationInstallationVersionConflictError extends Error { readonly name = "ApiIntegrationInstallationVersionConflictError"; constructor( readonly capabilityId: string, readonly expectedVersion: number, readonly actualVersion: number, ) { super( `API Integration ${capabilityId} changed: expected version ${expectedVersion}, current version ${actualVersion}`, ); } } /** A known rejection of the selected credential, not an internal install failure. */ export class ApiIntegrationConnectionReferenceError extends Error { readonly name = "ApiIntegrationConnectionReferenceError"; constructor( readonly reason: | "not_found" | "inactive" | "provider_mismatch" | "kind_mismatch" | "scope_mismatch", message: string, ) { super(message); } } export async function installApiIntegration( db: Database, input: InstallApiIntegrationInput, ): Promise { // Inputs here are server-resolved immutable previews, not deserialized client // provenance. Custom documents never gain curated permission by their URL. const snapshot = structuredClone(input); const key = snapshot.definitionProvenance === "curated" ? snapshot.definitionId : `custom:${snapshot.protocol}`; return withOrganizationIntegrationPolicyFence(db, snapshot, (tx, policy) => { // Re-checked under the policy fence: the organization may have reserved // turning integrations on for admins since the route checked. if (snapshot.memberCreate && policy.personalIntegrationSetup !== "members") throw new IntegrationChangeRequiresAdminError( "Your organization lets only admins turn on integrations", ); return installApiIntegrationInScope(tx, snapshot, () => assertOrganizationIntegrationAllowed(policy, key), ); }); } async function installApiIntegrationInScope( db: Database, input: InstallApiIntegrationInput, assertAcquisition: () => void, ): Promise { assertInstallInput(input); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.subjectId); return await scopedDb.transaction(async (tx) => { const now = new Date(); await lockCapabilityComponentIdentity( tx as unknown as Database, input.workspaceId, input.pluginKey, ); const connection = input.connectionId ? await loadInstallConnection(tx as unknown as Database, input) : null; let [plugin] = await tx .select() .from(schema.capabilityPlugins) .where( and( eq(schema.capabilityPlugins.workspaceId, input.workspaceId), eq(schema.capabilityPlugins.pluginKey, input.pluginKey), ), ) .for("update") .limit(1); if (!plugin) { [plugin] = await tx .insert(schema.capabilityPlugins) .values({ pluginKey: input.pluginKey, accountId: input.accountId, workspaceId: input.workspaceId, name: input.name, description: input.description ?? null, category: input.category ?? "integrations", tags: normalizedStrings(input.tags ?? ["integration", input.protocol], 64), provenance: "workspace", }) .returning(); } else if (plugin.accountId !== input.accountId) { throw new Error("API Integration plugin tenant mismatch"); } else if ( plugin.name !== input.name || plugin.description !== (input.description ?? null) || plugin.category !== (input.category ?? "integrations") ) { [plugin] = await tx .update(schema.capabilityPlugins) .set({ name: input.name, description: input.description ?? null, category: input.category ?? "integrations", tags: normalizedStrings(input.tags ?? ["integration", input.protocol], 64), updatedAt: now, }) .where(eq(schema.capabilityPlugins.id, plugin.id)) .returning(); } if (!plugin) throw new Error("Failed to create API Integration plugin"); const manifest = { schemaVersion: 1, kind: "integration", capabilityId: input.capabilityId, serverId: input.serverId, protocol: input.protocol, definitionId: input.definitionId, definitionProvenance: input.definitionProvenance, provider: input.provider ?? null, providerDomain: input.providerDomain, baseUrl: input.baseUrl, sourceUrl: input.sourceUrl ?? null, revisionId: input.revision.id, contentSha256: input.revision.contentSha256, toolCount: input.revision.tools.length, }; const manifestDigest = sha256(stableJson(manifest)); let [pluginVersion] = await tx .select() .from(schema.capabilityPluginVersions) .where( and( eq(schema.capabilityPluginVersions.pluginId, plugin.id), eq(schema.capabilityPluginVersions.version, input.revision.id), ), ) .for("update") .limit(1); if (pluginVersion && pluginVersion.manifestDigest !== manifestDigest) { throw new Error( `API Integration revision ${input.revision.id} conflicts with stored content`, ); } if (!pluginVersion) { [pluginVersion] = await tx .insert(schema.capabilityPluginVersions) .values({ pluginId: plugin.id, version: input.revision.id, manifestDigest, manifest, status: "published", }) .returning(); } if (!pluginVersion) throw new Error("Failed to create API Integration version"); const integrationFacet = await ensureFacet(tx as unknown as Database, { pluginVersionId: pluginVersion.id, facetKey: "integration", kind: "integration", }); const apiFacet = await ensureFacet(tx as unknown as Database, { pluginVersionId: pluginVersion.id, facetKey: "api", kind: "api", }); await tx .insert(schema.capabilityIntegrationFacets) .values({ facetId: integrationFacet.id, providerDomain: input.providerDomain, connectionKinds: connection ? [connection.kind] : [], ownership: input.ownership ?? (connection?.subjectId ? "subject" : "workspace"), requiredScopes: normalizedStrings(input.requiredScopes ?? [], 256), resourceSelection: "none", }) .onConflictDoNothing(); await tx .insert(schema.capabilityApiFacets) .values({ facetId: apiFacet.id, protocol: input.protocol, baseUrl: input.baseUrl, specSourceUrl: input.sourceUrl ?? null, authScheme: input.authScheme ?? {}, integrationFacetId: integrationFacet.id, }) .onConflictDoNothing(); await tx .insert(schema.integrationSpecRevisions) .values({ apiFacetId: apiFacet.id, revision: 1, protocol: input.protocol, sourceUrl: input.sourceUrl ?? null, specDigest: input.revision.contentSha256, spec: input.revision as unknown as Record, status: "active", }) .onConflictDoNothing(); await tx .insert(schema.integrationTools) .values( input.revision.tools.map((tool) => ({ facetId: apiFacet.id, toolKey: tool.id, name: tool.name, description: tool.description || null, inputSchema: tool.inputSchema, outputSchema: tool.outputSchema ?? null, effect: tool.safety, active: !tool.deprecated, })), ) .onConflictDoNothing(); const owner: IntegrationFacetBindingOwner = input.owner ?? { kind: "direct", id: input.capabilityId, removable: true, }; const instanceKey = integrationBindingKey(input.connectionId, input.instanceKey); const runtimeServerId = integrationRuntimeKey(input.serverId, instanceKey); const displayName = input.displayName?.trim() || (instanceKey === "default" ? input.name : `${input.name} — connected account`); // Capture immutable definition identity before any ensure helper can // repair it. A repair/addition is acquisition, not unchanged replay. const previousDefinitions = await tx .select() .from(schema.integrationFacetDefinitions) .where(eq(schema.integrationFacetDefinitions.integrationFacetId, integrationFacet.id)); const toolsFacet = await ensureIntegrationFacetDefinition(tx as unknown as Database, { integrationFacetId: integrationFacet.id, facetKey: "tools", kind: "tools", configSchema: { type: "object", properties: { allowedTools: { type: "array", items: { type: "string" } }, requireApproval: { type: "array", items: { type: "string" } }, }, additionalProperties: false, }, capabilities: { protocol: input.protocol, runtime: "mcp" }, }); const facetDefinitions = new Map< string, typeof schema.integrationFacetDefinitions.$inferSelect >([[toolsFacet.facetKey, toolsFacet]]); for (const definition of input.facetDefinitions ?? []) { const facet = await ensureIntegrationFacetDefinition(tx as unknown as Database, { integrationFacetId: integrationFacet.id, facetKey: definition.facetKey, kind: definition.kind, configSchema: { ...definition.configSchema }, capabilities: { ...definition.capabilities }, }); facetDefinitions.set(facet.facetKey, facet); } let [pluginInstallation] = await tx .select() .from(schema.capabilityPluginInstallations) .where( and( eq(schema.capabilityPluginInstallations.workspaceId, input.workspaceId), eq(schema.capabilityPluginInstallations.pluginId, plugin.id), ), ) .for("update") .limit(1); const existingPluginInstallation = pluginInstallation; // A member never moves the instances already set up to a new revision. if ( input.memberCreate && pluginInstallation?.status === "active" && pluginInstallation.pluginVersionId !== pluginVersion.id ) throw new IntegrationChangeRequiresAdminError(); const oldFacetInstallations = pluginInstallation ? await installedFacetRows(tx as unknown as Database, pluginInstallation.id) : []; const oldApi = oldFacetInstallations.find((row) => row.kind === "api"); const [previousSpec] = oldApi ? await tx .select({ revision: schema.integrationSpecRevisions.spec, baseUrl: schema.capabilityApiFacets.baseUrl, authScheme: schema.capabilityApiFacets.authScheme, }) .from(schema.integrationSpecRevisions) .innerJoin( schema.capabilityApiFacets, eq(schema.capabilityApiFacets.facetId, schema.integrationSpecRevisions.apiFacetId), ) .where( and( eq(schema.integrationSpecRevisions.apiFacetId, oldApi.facetId), eq(schema.integrationSpecRevisions.status, "active"), ), ) .limit(1) : []; const previousRevision = previousSpec ? storedRevision(previousSpec.revision) : null; const sameEndpoint = previousSpec?.baseUrl === input.baseUrl && stableJson(previousSpec.authScheme) === stableJson(input.authScheme ?? {}); let pluginInstallationGenerationAdvanced = false; if (pluginInstallation && pluginInstallation.pluginVersionId !== pluginVersion.id) { await assertCapabilityComponentVersionCanChange(tx as unknown as Database, { workspaceId: input.workspaceId, pluginKey: input.pluginKey, pluginInstallationId: pluginInstallation.id, owner: { kind: owner.kind, id: owner.id, }, }); } if (!pluginInstallation) { [pluginInstallation] = await tx .insert(schema.capabilityPluginInstallations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, pluginId: plugin.id, pluginVersionId: pluginVersion.id, status: "active", installedBySubjectId: input.subjectId, }) .returning(); } else if ( pluginInstallation.pluginVersionId !== pluginVersion.id || pluginInstallation.status !== "active" ) { [pluginInstallation] = await tx .update(schema.capabilityPluginInstallations) .set({ pluginVersionId: pluginVersion.id, status: "active", version: pluginInstallation.version + 1, installedBySubjectId: input.subjectId, installedAt: now, updatedAt: now, }) .where(eq(schema.capabilityPluginInstallations.id, pluginInstallation.id)) .returning(); pluginInstallationGenerationAdvanced = true; } if (!pluginInstallation) throw new Error("Failed to create API Integration installation"); const integrationFacetInstallationResult = await ensureFacetInstallation( tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, pluginInstallationId: pluginInstallation.id, facetId: integrationFacet.id, connectionId: null, config: {}, }, ); const integrationFacetInstallation = integrationFacetInstallationResult.row; const selectedTools = selectedToolIds(input); const apiFacetInstallationResult = await ensureFacetInstallation( tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, pluginInstallationId: pluginInstallation.id, facetId: apiFacet.id, connectionId: null, config: { baseServerId: input.serverId, }, }, ); const apiFacetInstallation = apiFacetInstallationResult.row; if (pluginInstallationGenerationAdvanced) { await migrateApiIntegrationFacetInstallations(tx as unknown as Database, { workspaceId: input.workspaceId, subjectId: input.subjectId, oldFacetInstallations, integrationFacetInstallationId: integrationFacetInstallation.id, apiFacetInstallationId: apiFacetInstallation.id, integrationFacetId: integrationFacet.id, facetDefinitions, excludedRuntimeKey: runtimeServerId, revision: input.revision, previousRevision, sameEndpoint, baseUrl: input.baseUrl, }); } // This is the same advisory -> row prefix used by the binding upsert. // All preceding ensure writes are local to this transaction and roll // back if admission below denies a new acquisition. await tx.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`integration-binding:${input.workspaceId}:${runtimeServerId}`}, 0))`, ); const [previousBinding] = await tx .select() .from(schema.integrationFacetBindings) .where( and( eq(schema.integrationFacetBindings.workspaceId, input.workspaceId), eq(schema.integrationFacetBindings.runtimeKey, runtimeServerId), ), ) .for("update") .limit(1); const nextConfig = { baseServerId: input.serverId, allowedTools: selectedTools, requireApproval: apiIntegrationRequiredApprovals({ revision: input.revision, previousRevision, selectedTools, previousConfig: previousBinding?.config ?? null, sameAuthority: sameEndpoint && previousBinding?.connectionId === (input.connectionId ?? null), ...(input.autoApprovedTools === undefined ? {} : { autoApprovedTools: [...autoApprovedToolIds(input, selectedTools)] }), }), connectionKind: connection?.kind ?? null, subjectScope: connection?.subjectId ? "subject" : connection ? "workspace" : "none", }; const bindingOwners = previousBinding ? await listIntegrationFacetBindingOwners(tx as unknown as Database, previousBinding.id) : []; // A member never changes an instance that is already set up. The one // exception is the same plugin installation resuming its own install. if ( input.memberCreate && previousBinding?.status === "active" && !( owner.kind === "plugin" && bindingOwners.some( (candidate) => candidate.kind === owner.kind && candidate.id === owner.id, ) ) ) throw new IntegrationChangeRequiresAdminError(); const componentOwners = await tx .select() .from(schema.capabilityComponentOwners) .where( inArray(schema.capabilityComponentOwners.facetInstallationId, [ integrationFacetInstallation.id, apiFacetInstallation.id, ]), ); const [storedSpec] = await tx .select() .from(schema.integrationSpecRevisions) .where( and( eq(schema.integrationSpecRevisions.apiFacetId, apiFacet.id), eq(schema.integrationSpecRevisions.status, "active"), ), ) .limit(1); const [storedAuthority] = await tx .select() .from(schema.capabilityIntegrationFacets) .where(eq(schema.capabilityIntegrationFacets.facetId, integrationFacet.id)) .limit(1); const [storedApi] = await tx .select() .from(schema.capabilityApiFacets) .where(eq(schema.capabilityApiFacets.facetId, apiFacet.id)) .limit(1); const sameOwner = (candidate: { kind: string; id: string; removable: boolean }) => candidate.kind === owner.kind && candidate.id === owner.id && candidate.removable === owner.removable; const unchangedAuthority = existingPluginInstallation?.status === "active" && existingPluginInstallation.pluginVersionId === pluginVersion.id && !integrationFacetInstallationResult.changed && !apiFacetInstallationResult.changed && previousBinding?.status === "active" && previousBinding.bindingKey === instanceKey && previousBinding.integrationFacetInstallationId === integrationFacetInstallation.id && previousBinding.facetDefinitionId === toolsFacet.id && previousBinding.connectionId === (input.connectionId ?? null) && isApiIntegrationPermissionReduction(previousBinding.config, nextConfig) && bindingOwners.some(sameOwner) && [integrationFacetInstallation.id, apiFacetInstallation.id].every((id) => componentOwners.some( (candidate) => candidate.facetInstallationId === id && sameOwner({ kind: candidate.ownerKind, id: candidate.ownerId, removable: candidate.removable, }), ), ) && stableJson(storedSpec?.spec) === stableJson(input.revision) && storedApi?.protocol === input.protocol && storedApi.baseUrl === input.baseUrl && storedApi.specSourceUrl === (input.sourceUrl ?? null) && storedAuthority?.providerDomain === input.providerDomain && stableJson(storedApi?.authScheme) === stableJson(input.authScheme ?? {}) && stableJson(storedAuthority?.requiredScopes) === stableJson(normalizedStrings(input.requiredScopes ?? [], 256)) && storedAuthority?.ownership === (input.ownership ?? (connection?.subjectId ? "subject" : "workspace")) && previousDefinitions.some( (definition) => definition.id === toolsFacet.id && definition.kind === toolsFacet.kind && stableJson(definition.configSchema) === stableJson(toolsFacet.configSchema) && stableJson(definition.capabilities) === stableJson(toolsFacet.capabilities), ) && (input.facetDefinitions ?? []).every((definition) => previousDefinitions.some( (old) => old.facetKey === definition.facetKey && old.kind === definition.kind && stableJson(old.configSchema) === stableJson(definition.configSchema) && stableJson(old.capabilities) === stableJson(definition.capabilities), ), ); if (!unchangedAuthority) assertAcquisition(); const bindingResult = await upsertIntegrationFacetBinding(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, integrationFacetInstallationId: integrationFacetInstallation.id, facetDefinitionId: toolsFacet.id, bindingKey: instanceKey, displayName, runtimeKey: runtimeServerId, connectionId: input.connectionId ?? null, config: nextConfig, createdBySubjectId: input.subjectId, owner, ...(input.expectedInstanceVersion !== undefined ? { expectedVersion: input.expectedInstanceVersion } : {}), }); await resetChangedApiToolPreferences(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, serverId: runtimeServerId, connectionId: input.connectionId ?? null, baseUrl: input.baseUrl, selectedTools, previousRevision, revision: input.revision, sameEndpoint, }); if (input.autoApprovedTools !== undefined) await applyLegacyApiApprovalChoices(tx as unknown as Database, { accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, serverId: runtimeServerId, connectionId: input.connectionId ?? null, baseUrl: input.baseUrl, choices: input.revision.tools .filter((tool) => selectedTools.includes(tool.id) && tool.approvalMode === "ask") .map((tool) => ({ toolName: tool.id, policy: input.autoApprovedTools!.includes(tool.id) ? ("allow" as const) : ("ask" as const), })), }); if ( existingPluginInstallation && !pluginInstallationGenerationAdvanced && (integrationFacetInstallationResult.changed || apiFacetInstallationResult.changed || bindingResult.changed) ) { [pluginInstallation] = await tx .update(schema.capabilityPluginInstallations) .set({ version: pluginInstallation.version + 1, updatedAt: now, }) .where(eq(schema.capabilityPluginInstallations.id, pluginInstallation.id)) .returning(); if (!pluginInstallation) { throw new Error("Failed to advance API Integration installation version"); } } for (const facetInstallation of [integrationFacetInstallation, apiFacetInstallation]) { await tx .insert(schema.capabilityComponentOwners) .values({ accountId: input.accountId, workspaceId: input.workspaceId, facetInstallationId: facetInstallation.id, ownerKind: owner.kind, ownerId: owner.id, removable: owner.removable, }) .onConflictDoNothing(); } if (pluginInstallationGenerationAdvanced && oldFacetInstallations.length > 0) { await tx.delete(schema.capabilityFacetInstallations).where( inArray( schema.capabilityFacetInstallations.id, oldFacetInstallations.map((row) => row.id), ), ); } return { capabilityId: input.capabilityId, pluginId: plugin.id, pluginVersionId: pluginVersion.id, integrationFacetId: integrationFacet.id, apiFacetId: apiFacet.id, pluginInstallationId: pluginInstallation.id, integrationFacetInstallationId: integrationFacetInstallation.id, apiFacetInstallationId: apiFacetInstallation.id, installationVersion: pluginInstallation.version, instanceId: bindingResult.row.id, instanceKey: bindingResult.row.bindingKey, displayName: bindingResult.row.displayName, instanceVersion: bindingResult.row.version, revisionId: input.revision.id, serverId: runtimeServerId, status: "installed", }; }); }, ); } export async function listInstalledApiIntegrations( db: Database, workspaceId: string, subjectId?: string, /** Only bindings with these runtime server ids (a live target fence). */ serverIds?: readonly string[], ): Promise { if (serverIds && serverIds.length === 0) return []; return subjectId ? await withWorkspaceSubjectRls( db, workspaceId, subjectId, async (scopedDb) => await listInstalledApiIntegrationsInRlsContext( scopedDb, workspaceId, subjectId, serverIds, ), ) : await withWorkspaceRls( db, workspaceId, async (scopedDb) => await listInstalledApiIntegrationsInRlsContext( scopedDb, workspaceId, undefined, serverIds, ), ); } type ApiIntegrationServerAuthorityMetadata = { serverId: string; connectionId: string | null; providerDomain: string; connectionKind: string | null; subjectScope: "workspace" | "subject"; }; async function listInstalledApiIntegrationServerAuthorityMetadataInRlsContext( scopedDb: Database, workspaceId: string, subjectId?: string, ): Promise { const rows = await scopedDb .select({ serverId: schema.integrationFacetBindings.runtimeKey, connectionId: schema.integrationFacetBindings.connectionId, providerDomain: schema.capabilityIntegrationFacets.providerDomain, connectionKind: sql< string | null >`${schema.integrationFacetBindings.config} ->> 'connectionKind'`, subjectScope: sql< string | null >`${schema.integrationFacetBindings.config} ->> 'subjectScope'`, }) .from(schema.integrationFacetBindings) .innerJoin( schema.integrationFacetDefinitions, eq(schema.integrationFacetDefinitions.id, schema.integrationFacetBindings.facetDefinitionId), ) .innerJoin( schema.capabilityIntegrationFacets, eq( schema.capabilityIntegrationFacets.facetId, schema.integrationFacetDefinitions.integrationFacetId, ), ) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.id, schema.integrationFacetBindings.integrationFacetInstallationId, ), ) .innerJoin( schema.capabilityPluginInstallations, eq( schema.capabilityPluginInstallations.id, schema.capabilityFacetInstallations.pluginInstallationId, ), ) .innerJoin( schema.capabilityApiFacets, eq(schema.capabilityApiFacets.integrationFacetId, schema.capabilityIntegrationFacets.facetId), ) .where( and( eq(schema.capabilityPluginInstallations.workspaceId, workspaceId), eq(schema.capabilityPluginInstallations.status, "active"), eq(schema.capabilityFacetInstallations.status, "active"), eq(schema.integrationFacetDefinitions.kind, "tools"), eq(schema.integrationFacetBindings.status, "active"), sql`${schema.integrationFacetBindings.runtimeKey} is not null`, sql`exists ( select 1 from ${schema.capabilityComponentOwners} owner where owner.facet_installation_id = ${schema.capabilityFacetInstallations.id} and ${effectiveCapabilityOwnerSql(sql`owner.owner_kind`, sql`owner.owner_id`)} )`, sql`exists ( select 1 from ${schema.integrationFacetBindingOwners} owner where owner.binding_id = ${schema.integrationFacetBindings.id} and ${effectiveCapabilityOwnerSql(sql`owner.owner_kind`, sql`owner.owner_id`)} )`, sql`exists ( select 1 from ${schema.capabilityFacetInstallations} api_installation where api_installation.plugin_installation_id = ${schema.capabilityPluginInstallations.id} and api_installation.facet_id = ${schema.capabilityApiFacets.facetId} and api_installation.status = 'active' )`, subjectId ? sql`( ${schema.integrationFacetBindings.connectionId} is null or exists ( select 1 from ${schema.connections} connection where connection.id = ${schema.integrationFacetBindings.connectionId} and (connection.subject_id is null or connection.subject_id = ${subjectId}) ) )` : sql`( ${schema.integrationFacetBindings.connectionId} is null or exists ( select 1 from ${schema.connections} connection where connection.id = ${schema.integrationFacetBindings.connectionId} and connection.subject_id is null ) )`, ), ); return rows.flatMap((row) => row.serverId ? [ { serverId: row.serverId, connectionId: row.connectionId, providerDomain: row.providerDomain, connectionKind: row.connectionKind, subjectScope: row.subjectScope === "subject" ? "subject" : "workspace", }, ] : [], ); } /** * Exact runnable API-integration server ids for a scheduled service run. * Only runtime ids and the minimum delegation-matching metadata are selected; * no integration definition, credential, token, endpoint, or tool schema is * materialized before incident admission. */ export async function listInstalledApiIntegrationServerIdsForDelegations( db: Database, workspaceId: string, delegations: readonly { serverId: string; connectionId: string; providerDomain: string; ownerSubjectId: string; kind?: string | undefined; }[], ): Promise { const workspace = await withWorkspaceRls( db, workspaceId, async (scopedDb) => await listInstalledApiIntegrationServerAuthorityMetadataInRlsContext(scopedDb, workspaceId), ); const byServerId = new Set(workspace.map((entry) => entry.serverId)); // The organization's API integrations here: an organization key or no // sign-in runs for anyone; "each person signs in" only for a delegated // person's own account to that provider. const organization = await withWorkspaceRls(db, workspaceId, async (scopedDb) => (await organizationApiIntegrationRows(scopedDb, workspaceId)).flatMap( organizationApiIntegrationRuntime, ), ); for (const integration of organization) { if (byServerId.has(integration.serverId)) continue; if ( !integration.connectionRef || delegations.some( (delegation) => delegation.serverId === integration.serverId && delegation.providerDomain.toLowerCase() === integration.providerDomain.toLowerCase(), ) ) byServerId.add(integration.serverId); } const owners = [...new Set(delegations.map((delegation) => delegation.ownerSubjectId))]; for (const ownerSubjectId of owners) { const ownerEntries = await withWorkspaceSubjectRls( db, workspaceId, ownerSubjectId, async (scopedDb) => await listInstalledApiIntegrationServerAuthorityMetadataInRlsContext( scopedDb, workspaceId, ownerSubjectId, ), ); const exact = delegations.filter((delegation) => delegation.ownerSubjectId === ownerSubjectId); for (const entry of ownerEntries) { if ( entry.subjectScope === "subject" && entry.connectionId && exact.some( (delegation) => delegation.serverId === entry.serverId && delegation.connectionId === entry.connectionId && delegation.providerDomain.toLowerCase() === entry.providerDomain.toLowerCase() && (delegation.kind ?? "") === (entry.connectionKind ?? ""), ) ) { byServerId.add(entry.serverId); } } } return [...byServerId]; } /** * The API integrations that run in this workspace for the reading subject: * the workspace's own installations it can see (shared ones, plus its own * "Only me" ones), then the organization's API integrations that reach the * workspace. A workspace's own setup of the same integration wins: an * organization one is left out when the reader already has an instance of * the same capability here, or when the workspace turned it off. */ export async function listInstalledApiIntegrationsInRlsContext( scopedDb: Database, workspaceId: string, subjectId?: string, serverIds?: readonly string[], ): Promise { if (serverIds && serverIds.length === 0) return []; const own = await listOwnApiIntegrationsInRlsContext(scopedDb, workspaceId, subjectId, serverIds); const organization = (await organizationApiIntegrationRows(scopedDb, workspaceId)) .flatMap(organizationApiIntegrationRuntime) .filter((integration) => !serverIds || serverIds.includes(integration.serverId)); if (organization.length === 0) return own; const ownCapabilityIds = new Set( (serverIds ? await listOwnApiIntegrationsInRlsContext(scopedDb, workspaceId, subjectId) : own ).map((integration) => integration.capabilityId), ); const served = organization.filter( (integration) => !ownCapabilityIds.has(integration.capabilityId), ); return served.length === 0 ? own : [...own, ...served]; } /** * The organization's active API integrations that reach this workspace (row * security decides reach) and that this workspace has not turned off: a * turned-off installation row of the same capability is how a workspace * turns an organization connector off, for MCP servers and APIs alike. */ async function organizationApiIntegrationRows( scopedDb: Database, workspaceId: string, ): Promise<(typeof schema.organizationConnectors.$inferSelect)[]> { return await scopedDb .select() .from(schema.organizationConnectors) .where( and( eq(schema.organizationConnectors.kind, "api"), eq(schema.organizationConnectors.status, "active"), sql`not exists ( select 1 from ${schema.capabilityInstallations} installation where installation.workspace_id = ${workspaceId}::uuid and installation.capability_id = ${schema.organizationConnectors.capabilityId} )`, ), ) .orderBy(asc(schema.organizationConnectors.capabilityId)); } /** * The organization's active API integrations that reach this workspace and * that this workspace turned off (its turned-off override installation, the * `organizationOverride` marker of ORGANIZATION_CONNECTOR_OVERRIDE_METADATA_KEY), * so the workspace can list each as off here and turn it back on. */ export async function listOrganizationApiIntegrationsTurnedOffHere( db: Database, workspaceId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => ( await scopedDb .select() .from(schema.organizationConnectors) .where( and( eq(schema.organizationConnectors.kind, "api"), eq(schema.organizationConnectors.status, "active"), sql`exists ( select 1 from ${schema.capabilityInstallations} installation where installation.workspace_id = ${workspaceId}::uuid and installation.capability_id = ${schema.organizationConnectors.capabilityId} and installation.status = 'disabled' and installation.metadata -> 'organizationOverride' = 'true'::jsonb )`, ), ) .orderBy(asc(schema.organizationConnectors.capabilityId)) ).flatMap(organizationApiIntegrationRuntime), ); } /** * An organization API integration as the runtime a workspace installation of * it would be, under the "organization" instance key. "Each person signs in" * is a per-person selector (no connection id): each turn attaches the * initiating person's own account for that provider, exactly as for an * organization MCP connector. An organization key carries its encrypted * placements; "none" calls the API without credentials. */ export function organizationApiIntegrationRuntime( row: typeof schema.organizationConnectors.$inferSelect, ): ApiIntegrationRuntime[] { const definition = organizationApiIntegrationDefinition(row); if (!definition) return []; let revision: StoredApiIntegrationRevision; try { revision = storedRevision(definition.revision as unknown as Record); } catch { return []; } if (revision.protocol !== definition.protocol) return []; const login = organizationConnectorLogin(row.config); const ref = objectValue(row.config.connectionRef); const kind = stringValue(ref.kind); const connectionRef: McpServerConnectionRef | null = login === "each_person" ? { providerDomain: definition.providerDomain, ...(definition.provider ? { provider: definition.provider } : {}), ...(kind === "oauth2" || kind === "api_key" ? { kind } : {}), ...(definition.requiredScopes.length > 0 ? { scopes: [...definition.requiredScopes] } : {}), subjectScope: "subject", } : null; const placements = organizationApiCredentialPlacements(row.config); const allowedTools = stringArray(row.config.allowedTools) ?? revision.tools.map((tool) => tool.id); return [ { capabilityId: row.capabilityId, pluginKey: definition.pluginKey, pluginInstallationId: row.id, installationVersion: row.generation, instanceId: row.id, instanceKey: ORGANIZATION_API_INTEGRATION_INSTANCE_KEY, displayName: definition.name, instanceVersion: row.generation, serverId: integrationRuntimeKey( definition.serverId, ORGANIZATION_API_INTEGRATION_INSTANCE_KEY, ), name: definition.name, description: definition.description, protocol: revision.protocol, definitionId: definition.definitionId, definitionProvenance: definition.definitionProvenance, baseUrl: definition.baseUrl, sourceUrl: definition.sourceUrl, providerDomain: definition.providerDomain, authScheme: objectValue(definition.authScheme), connectionRef, connectionStatus: null, connectionLastUsedAt: null, connectionAuthorityGeneration: null, allowedTools, requireApproval: revision.tools .filter((tool) => tool.approvalMode === "ask" && allowedTools.includes(tool.id)) .map((tool) => tool.id), revision, organizationConnector: { id: row.id, generation: row.generation, // API connectors never connect people automatically. login: login === "auto_connect" ? "each_person" : login, auth: definition.auth, }, ...(login === "organization_key" && placements.length > 0 ? { organizationCredential: { placements } } : {}), }, ]; } /** The encrypted placements of an organization key, as stored on an API organization connector. */ export function organizationApiCredentialPlacements( config: Record, ): OrganizationApiCredentialPlacement[] { const placements = config.placementsEncrypted; if (!Array.isArray(placements)) return []; return placements.flatMap((entry): OrganizationApiCredentialPlacement[] => { const value = objectValue(entry); const carrier = value.carrier; const name = stringValue(value.name); const valueEncrypted = stringValue(value.valueEncrypted); if ( (carrier !== "header" && carrier !== "query" && carrier !== "cookie") || !name || !valueEncrypted ) return []; const prefix = stringValue(value.prefix); return [{ carrier, name, valueEncrypted, ...(prefix ? { prefix } : {}) }]; }); } /** This workspace's own installations the reader can see; never the organization's. */ async function listOwnApiIntegrationsInRlsContext( scopedDb: Database, workspaceId: string, subjectId?: string, serverIds?: readonly string[], ): Promise { if (serverIds && serverIds.length === 0) return []; const rows = await scopedDb .select({ pluginKey: schema.capabilityPlugins.pluginKey, pluginName: schema.capabilityPlugins.name, pluginDescription: schema.capabilityPlugins.description, manifest: schema.capabilityPluginVersions.manifest, pluginInstallationId: schema.capabilityPluginInstallations.id, installationVersion: schema.capabilityPluginInstallations.version, apiFacetId: schema.capabilityApiFacets.facetId, protocol: schema.capabilityApiFacets.protocol, baseUrl: schema.capabilityApiFacets.baseUrl, sourceUrl: schema.capabilityApiFacets.specSourceUrl, authScheme: schema.capabilityApiFacets.authScheme, providerDomain: schema.capabilityIntegrationFacets.providerDomain, requiredScopes: schema.capabilityIntegrationFacets.requiredScopes, instanceId: schema.integrationFacetBindings.id, instanceKey: schema.integrationFacetBindings.bindingKey, displayName: schema.integrationFacetBindings.displayName, instanceVersion: schema.integrationFacetBindings.version, runtimeKey: schema.integrationFacetBindings.runtimeKey, bindingConfig: schema.integrationFacetBindings.config, instanceCreatedBySubjectId: schema.integrationFacetBindings.createdBySubjectId, connectionId: schema.integrationFacetBindings.connectionId, connectionAuthorityGeneration: schema.connections.authorityGeneration, connectionStatus: schema.connections.status, connectionLastUsedAt: schema.connections.lastUsedAt, revision: schema.integrationSpecRevisions.spec, }) .from(schema.integrationFacetBindings) .innerJoin( schema.integrationFacetDefinitions, eq(schema.integrationFacetDefinitions.id, schema.integrationFacetBindings.facetDefinitionId), ) .innerJoin( schema.capabilityIntegrationFacets, eq( schema.capabilityIntegrationFacets.facetId, schema.integrationFacetDefinitions.integrationFacetId, ), ) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.id, schema.integrationFacetBindings.integrationFacetInstallationId, ), ) .innerJoin( schema.capabilityPluginInstallations, eq( schema.capabilityPluginInstallations.id, schema.capabilityFacetInstallations.pluginInstallationId, ), ) .innerJoin( schema.capabilityPlugins, eq(schema.capabilityPlugins.id, schema.capabilityPluginInstallations.pluginId), ) .innerJoin( schema.capabilityPluginVersions, eq(schema.capabilityPluginVersions.id, schema.capabilityPluginInstallations.pluginVersionId), ) .innerJoin( schema.capabilityApiFacets, eq(schema.capabilityApiFacets.integrationFacetId, schema.capabilityIntegrationFacets.facetId), ) .innerJoin( schema.integrationSpecRevisions, and( eq(schema.integrationSpecRevisions.apiFacetId, schema.capabilityApiFacets.facetId), eq(schema.integrationSpecRevisions.status, "active"), ), ) .leftJoin( schema.connections, eq(schema.connections.id, schema.integrationFacetBindings.connectionId), ) .where( and( eq(schema.capabilityPluginInstallations.workspaceId, workspaceId), eq(schema.capabilityPluginInstallations.status, "active"), eq(schema.capabilityFacetInstallations.status, "active"), eq(schema.integrationFacetDefinitions.kind, "tools"), eq(schema.integrationFacetBindings.status, "active"), sql`${schema.integrationFacetBindings.runtimeKey} is not null`, serverIds ? inArray(schema.integrationFacetBindings.runtimeKey, [...serverIds]) : undefined, sql`exists ( select 1 from ${schema.capabilityComponentOwners} owner where owner.facet_installation_id = ${schema.capabilityFacetInstallations.id} and ${effectiveCapabilityOwnerSql(sql`owner.owner_kind`, sql`owner.owner_id`)} )`, sql`exists ( select 1 from ${schema.integrationFacetBindingOwners} owner where owner.binding_id = ${schema.integrationFacetBindings.id} and ${effectiveCapabilityOwnerSql(sql`owner.owner_kind`, sql`owner.owner_id`)} )`, sql`exists ( select 1 from ${schema.capabilityFacetInstallations} api_installation where api_installation.plugin_installation_id = ${schema.capabilityPluginInstallations.id} and api_installation.facet_id = ${schema.capabilityApiFacets.facetId} and api_installation.status = 'active' )`, subjectId ? sql`( ${schema.integrationFacetBindings.connectionId} is null or exists ( select 1 from ${schema.connections} connection where connection.id = ${schema.integrationFacetBindings.connectionId} and (connection.subject_id is null or connection.subject_id = ${subjectId}) ) )` : sql`( ${schema.integrationFacetBindings.connectionId} is null or exists ( select 1 from ${schema.connections} connection where connection.id = ${schema.integrationFacetBindings.connectionId} and connection.subject_id is null ) )`, ), ) .orderBy( asc(schema.capabilityPlugins.name), asc(schema.integrationFacetBindings.displayName), asc(schema.integrationFacetBindings.bindingKey), ); return rows.flatMap((row): ApiIntegrationRuntime[] => { const revision = storedRevision(row.revision); const config = objectValue(row.bindingConfig); const manifest = objectValue(row.manifest); const capabilityId = stringValue(manifest.capabilityId); const definitionId = stringValue(manifest.definitionId); const definitionProvenance = stringValue(manifest.definitionProvenance); const serverId = row.runtimeKey; if ( !capabilityId || !definitionId || (definitionProvenance !== "curated" && definitionProvenance !== "workspace") || !serverId || row.protocol !== revision.protocol ) { throw new Error(`Installed API Integration ${row.pluginKey} has invalid immutable metadata`); } const allowedTools = stringArray(config.allowedTools) ?? revision.tools.map((tool) => tool.id); const requireApproval = stringArray(config.requireApproval) ?? revision.tools.filter((tool) => tool.approvalMode === "ask").map((tool) => tool.id); const connectionKind = stringValue(config.connectionKind); const subjectScope = stringValue(config.subjectScope); const connectionRef: McpServerConnectionRef | null = row.connectionId ? { connectionId: row.connectionId, providerDomain: row.providerDomain, ...(stringValue(manifest.provider) ? { provider: stringValue(manifest.provider)! } : {}), ...(connectionKind === "oauth2" || connectionKind === "api_key" || connectionKind === "app_install" || connectionKind === "delegated" ? { kind: connectionKind } : {}), ...(row.requiredScopes.length > 0 ? { scopes: [...row.requiredScopes] } : {}), subjectScope: subjectScope === "subject" ? "subject" : "workspace", } : null; return [ { capabilityId, pluginKey: row.pluginKey, pluginInstallationId: row.pluginInstallationId, installationVersion: row.installationVersion, instanceId: row.instanceId, instanceKey: row.instanceKey, displayName: row.displayName, instanceVersion: row.instanceVersion, serverId, name: row.displayName, description: row.pluginDescription, protocol: revision.protocol, definitionId, definitionProvenance, baseUrl: row.baseUrl, sourceUrl: row.sourceUrl, providerDomain: row.providerDomain, authScheme: objectValue(row.authScheme), connectionRef, connectionStatus: row.connectionId ? row.connectionStatus : null, connectionLastUsedAt: row.connectionId && row.connectionLastUsedAt ? new Date(row.connectionLastUsedAt).toISOString() : null, connectionAuthorityGeneration: row.connectionAuthorityGeneration, allowedTools, requireApproval, revision, instanceCreatedBySubjectId: row.instanceCreatedBySubjectId, }, ]; }); } export async function getApiIntegrationUninstallPreview( db: Database, workspaceId: string, subjectId: string, capabilityId: string, instanceKey: string, ): Promise { return await withWorkspaceSubjectRls(db, workspaceId, subjectId, async (scopedDb) => { const context = await integrationInstanceContext( scopedDb, workspaceId, subjectId, capabilityId, instanceKey, ); if (!context) { return { capabilityId, instanceKey, displayName: null, installed: false, installationVersion: null, instanceVersion: null, directOwner: null, remainingOwners: [], removesRuntimeIntegration: false, removesDefinition: false, }; } const owners = await listIntegrationFacetBindingOwners(scopedDb, context.instanceId); const directOwner = owners.find( (owner) => owner.kind === "direct" && owner.id === capabilityId, ); const remainingOwners = owners.filter( (owner) => !(owner.kind === "direct" && owner.id === capabilityId), ); const definitionOwners = await integrationOwners(scopedDb, context.pluginInstallationId); const remainingDefinitionOwners = definitionOwners.filter( (owner) => !(owner.kind === "direct" && owner.id === capabilityId), ); const hasOtherDirectInstance = await integrationDefinitionHasOtherBindingOwner(scopedDb, { workspaceId, pluginInstallationId: context.pluginInstallationId, excludedBindingId: context.instanceId, owner: { kind: "direct", id: capabilityId }, }); return { capabilityId, instanceKey, displayName: context.displayName, installed: true, installationVersion: context.installationVersion, instanceVersion: context.instanceVersion, directOwner: directOwner ?? null, remainingOwners, removesRuntimeIntegration: remainingOwners.length === 0, removesDefinition: remainingOwners.length === 0 && !hasOtherDirectInstance && remainingDefinitionOwners.length === 0, }; }); } /** No discovery or new authority: recover only an exact, currently visible and * directly owned installed source. The installer must still lock and recheck * the snapshot before committing; this read is not installation admission. */ export async function getApiIntegrationReconciliationSnapshot( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; source: IntegrationSourceInput; connectionId?: string; instanceKey?: string; expectedRevisionId: string; expectedContentSha256: string; allowedTools?: string[]; }, ): Promise<{ runtime: ApiIntegrationRuntime; baseServerId: string; name: string; provider: string | null; requiredScopes: string[]; } | null> { return withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, async (tx) => { const instanceKey = integrationBindingKey(input.connectionId, input.instanceKey); // Only this workspace's own installations can be reconciled: the // organization's API integrations are never a stored installation here. const candidates = ( await listOwnApiIntegrationsInRlsContext(tx, input.workspaceId, input.subjectId) ).filter((runtime) => { if ( runtime.instanceKey !== instanceKey || (runtime.connectionRef?.connectionId ?? null) !== (input.connectionId ?? null) || runtime.revision.id !== input.expectedRevisionId || runtime.revision.contentSha256 !== input.expectedContentSha256 || !(input.allowedTools ?? runtime.revision.tools.map((tool) => tool.id)).every((tool) => runtime.allowedTools.includes(tool), ) ) return false; const source = input.source; if (source.kind === "definition") return ( runtime.definitionProvenance === "curated" && runtime.definitionId === source.definitionId ); if (runtime.definitionProvenance !== "workspace") return false; // No stored-preview recovery for inline documents: they carry their // full content in the request, so ordinary resolution always applies. if (source.kind === "openapi_document") return false; if (source.kind === "graphql") return runtime.protocol === "graphql" && source.endpoint === runtime.sourceUrl; return ( (source.kind === "auto" || runtime.protocol === "openapi") && source.url === runtime.sourceUrl && (source.baseUrl === undefined || source.baseUrl === runtime.baseUrl) ); }); if (candidates.length !== 1) return null; const runtime = candidates[0]!; const owners = await listIntegrationFacetBindingOwners(tx, runtime.instanceId); if ( !owners.some( (owner) => owner.kind === "direct" && owner.id === runtime.capabilityId && owner.removable, ) ) return null; const [stored] = await tx .select({ manifest: schema.capabilityPluginVersions.manifest, name: schema.capabilityPlugins.name, requiredScopes: schema.capabilityIntegrationFacets.requiredScopes, }) .from(schema.capabilityPluginInstallations) .innerJoin( schema.capabilityPlugins, eq(schema.capabilityPlugins.id, schema.capabilityPluginInstallations.pluginId), ) .innerJoin( schema.capabilityPluginVersions, eq( schema.capabilityPluginVersions.id, schema.capabilityPluginInstallations.pluginVersionId, ), ) .innerJoin( schema.integrationFacetBindings, eq(schema.integrationFacetBindings.id, runtime.instanceId), ) .innerJoin( schema.integrationFacetDefinitions, eq( schema.integrationFacetDefinitions.id, schema.integrationFacetBindings.facetDefinitionId, ), ) .innerJoin( schema.capabilityIntegrationFacets, eq( schema.capabilityIntegrationFacets.facetId, schema.integrationFacetDefinitions.integrationFacetId, ), ) .where( and( eq(schema.capabilityPluginInstallations.id, runtime.pluginInstallationId), eq(schema.capabilityPluginInstallations.accountId, input.accountId), eq(schema.capabilityPluginInstallations.workspaceId, input.workspaceId), eq(schema.capabilityPluginInstallations.status, "active"), ), ) .limit(1); const manifest = objectValue(stored?.manifest); const baseServerId = stringValue(manifest.serverId); if ( !stored || !baseServerId || manifest.revisionId !== runtime.revision.id || manifest.contentSha256 !== runtime.revision.contentSha256 || manifest.capabilityId !== runtime.capabilityId ) return null; return { runtime, baseServerId, name: stored.name, provider: stringValue(manifest.provider) ?? null, requiredScopes: stored.requiredScopes, }; }); } export async function uninstallApiIntegration( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; capabilityId: string; instanceKey: string; expectedInstallationVersion: number; expectedInstanceVersion: number; /** * A member's removal: only an instance this subject added. One an admin * or another person added throws {@link IntegrationChangeRequiresAdminError}. */ memberRemoval?: boolean; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await setSubjectRlsContext(scopedDb, input.subjectId); return await scopedDb.transaction(async (tx) => { const context = await integrationInstanceContext( tx as unknown as Database, input.workspaceId, input.subjectId, input.capabilityId, input.instanceKey, true, ); if (!context) { return { capabilityId: input.capabilityId, instanceKey: input.instanceKey, status: "not_installed", remainingOwners: [], definitionStatus: "retained", }; } if (input.memberRemoval && context.createdBySubjectId !== input.subjectId) throw new IntegrationChangeRequiresAdminError( "Only an admin can remove an account someone else added.", ); if (context.installationVersion !== input.expectedInstallationVersion) { throw new ApiIntegrationInstallationVersionConflictError( input.capabilityId, input.expectedInstallationVersion, context.installationVersion, ); } const bindingOwners = await listIntegrationFacetBindingOwners( tx as unknown as Database, context.instanceId, ); if ( !bindingOwners.some((owner) => owner.kind === "direct" && owner.id === input.capabilityId) ) { return { capabilityId: input.capabilityId, instanceKey: input.instanceKey, status: "not_installed", remainingOwners: bindingOwners, definitionStatus: "retained", }; } const removed = await removeIntegrationFacetBindingOwner(tx as unknown as Database, { workspaceId: input.workspaceId, bindingId: context.instanceId, owner: { kind: "direct", id: input.capabilityId }, expectedVersion: input.expectedInstanceVersion, }); const hasAnotherDirectInstance = await integrationDefinitionHasBindingOwner( tx as unknown as Database, { workspaceId: input.workspaceId, pluginInstallationId: context.pluginInstallationId, owner: { kind: "direct", id: input.capabilityId }, }, ); if (!hasAnotherDirectInstance) { await tx.delete(schema.capabilityComponentOwners).where( and( eq(schema.capabilityComponentOwners.workspaceId, input.workspaceId), eq(schema.capabilityComponentOwners.ownerKind, "direct"), eq(schema.capabilityComponentOwners.ownerId, input.capabilityId), sql`${schema.capabilityComponentOwners.facetInstallationId} in ( select id from ${schema.capabilityFacetInstallations} where plugin_installation_id = ${context.pluginInstallationId} )`, ), ); } const remainingDefinitionOwners = await integrationOwners( tx as unknown as Database, context.pluginInstallationId, ); const now = new Date(); if (remainingDefinitionOwners.length > 0 || hasAnotherDirectInstance) { await tx .update(schema.capabilityPluginInstallations) .set({ version: context.installationVersion + 1, updatedAt: now }) .where(eq(schema.capabilityPluginInstallations.id, context.pluginInstallationId)); return { capabilityId: input.capabilityId, instanceKey: input.instanceKey, status: removed.remainingOwners.length > 0 ? "retained_by_other_owners" : "uninstalled", remainingOwners: removed.remainingOwners, definitionStatus: "retained", }; } await tx .delete(schema.capabilityFacetInstallations) .where( eq( schema.capabilityFacetInstallations.pluginInstallationId, context.pluginInstallationId, ), ); await tx .update(schema.capabilityPluginInstallations) .set({ status: "disabled", version: context.installationVersion + 1, updatedAt: now, }) .where(eq(schema.capabilityPluginInstallations.id, context.pluginInstallationId)); return { capabilityId: input.capabilityId, instanceKey: input.instanceKey, status: removed.remainingOwners.length > 0 ? "retained_by_other_owners" : "uninstalled", remainingOwners: removed.remainingOwners, definitionStatus: "disabled", }; }); }, ); } type InstalledFacetRow = { id: string; kind: string; facetId: string; }; /** Compatibility input adapter: legacy exemptions write ordinary preferences. */ async function applyLegacyApiApprovalChoices( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; serverId: string; connectionId: string | null; baseUrl: string; choices: Array<{ toolName: string; policy: "allow" | "ask" }>; }, ) { if (!input.choices.length) return; const connectionId = input.connectionId ?? `session-mcp:${input.serverId}:${createHash("sha256").update(input.baseUrl, "utf8").digest("hex")}`; await db.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`connector-tool-permissions:${input.workspaceId}`}, 0))`, ); const existing = await db .select() .from(schema.connectorActionPolicies) .where(eq(schema.connectorActionPolicies.workspaceId, input.workspaceId)); const choices = input.choices.filter( ({ toolName, policy }) => !existing.some( (row) => row.connectionId === connectionId && row.serverId === input.serverId && row.toolName === toolName && row.actionName === "*" && row.policy === policy, ), ); const names = input.choices.map((choice) => choice.toolName); const removedExceptions = await db .delete(schema.connectorActionPolicies) .where( and( eq(schema.connectorActionPolicies.workspaceId, input.workspaceId), eq(schema.connectorActionPolicies.connectionId, connectionId), eq(schema.connectorActionPolicies.serverId, input.serverId), inArray(schema.connectorActionPolicies.toolName, names), ne(schema.connectorActionPolicies.actionName, "*"), ), ) .returning({ toolName: schema.connectorActionPolicies.toolName, actionName: schema.connectorActionPolicies.actionName, }); const added = choices.filter( ({ toolName }) => !existing.some( (row) => row.connectionId === connectionId && row.serverId === input.serverId && row.toolName === toolName && row.actionName === "*", ), ); if (existing.length - removedExceptions.length + added.length > 2048) throw new Error("The workspace tool permission limit has been reached"); if (!choices.length && !removedExceptions.length) return; if (choices.length) await db .insert(schema.connectorActionPolicies) .values( choices.map(({ toolName, policy }) => ({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId, serverId: input.serverId, toolName, actionName: "*", policy, createdBySubjectId: input.subjectId, updatedBySubjectId: input.subjectId, })), ) .onConflictDoUpdate({ target: [ schema.connectorActionPolicies.workspaceId, schema.connectorActionPolicies.connectionId, schema.connectorActionPolicies.serverId, schema.connectorActionPolicies.toolName, schema.connectorActionPolicies.actionName, ], set: { policy: sql`excluded.policy`, version: sql`${schema.connectorActionPolicies.version} + 1`, updatedBySubjectId: input.subjectId, updatedAt: new Date(), }, }); await db.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: "connector.action.preferences_changed", targetType: "connector_action_policy", targetId: connectionId, metadata: { source: "api_install_compatibility", serverId: input.serverId, choices, removedExceptions, }, }); } /** A changed operation must not silently reuse Allow granted to its former * meaning. The resulting Ask is an ordinary editable preference, never a floor. */ async function resetChangedApiToolPreferences( db: Database, input: { accountId: string; workspaceId: string; subjectId: string; serverId: string; connectionId: string | null; baseUrl: string; selectedTools: readonly string[]; previousRevision: StoredApiIntegrationRevision | null; revision: StoredApiIntegrationRevision; sameEndpoint: boolean; }, ) { const changed = input.selectedTools.filter( (id) => !input.sameEndpoint || !apiIntegrationToolMeaningUnchanged(input.previousRevision, input.revision, id), ); if (!changed.length) return; const connectionId = input.connectionId ?? `session-mcp:${input.serverId}:${createHash("sha256").update(input.baseUrl, "utf8").digest("hex")}`; await db.execute( sql`select pg_advisory_xact_lock(hashtextextended(${`connector-tool-permissions:${input.workspaceId}`}, 0))`, ); const all = await db .select() .from(schema.connectorActionPolicies) .where(eq(schema.connectorActionPolicies.workspaceId, input.workspaceId)); const policies = all.filter((row) => row.connectionId === connectionId); let count = all.length; for (const toolName of changed) { const actions = new Set([ toolName, ...policies .filter( (row) => (row.serverId === input.serverId || row.serverId === "*") && (row.toolName === toolName || row.toolName === "*") && row.actionName !== "*", ) .map((row) => row.actionName), ]); for (const action of actions) { const resolved = resolveConnectorActionPolicy(policies, { connectionId, serverId: input.serverId, toolName, actionName: action, }); if (!resolved.managed || connectorActionPolicyDecision(resolved) !== "allow") continue; const actionName = action === toolName && resolved.entry?.actionName === "*" ? "*" : action; const existing = policies.find( (row) => row.serverId === input.serverId && row.toolName === toolName && row.actionName === actionName, ); if (!existing && ++count > 2048) throw new Error("The workspace tool permission limit has been reached"); const [updated] = await db .insert(schema.connectorActionPolicies) .values({ accountId: input.accountId, workspaceId: input.workspaceId, connectionId, serverId: input.serverId, toolName, actionName, policy: "ask", createdBySubjectId: input.subjectId, updatedBySubjectId: input.subjectId, }) .onConflictDoUpdate({ target: [ schema.connectorActionPolicies.workspaceId, schema.connectorActionPolicies.connectionId, schema.connectorActionPolicies.serverId, schema.connectorActionPolicies.toolName, schema.connectorActionPolicies.actionName, ], set: { policy: "ask", version: sql`${schema.connectorActionPolicies.version} + 1`, updatedBySubjectId: input.subjectId, updatedAt: new Date(), }, }) .returning(); if (updated) await db.insert(schema.auditEvents).values({ accountId: input.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, action: "connector.action.policy_reset", targetType: "connector_action_policy", targetId: updated.id, metadata: { reason: "operation_changed", policy: "ask", version: updated.version }, }); } } } async function installedFacetRows( db: Database, pluginInstallationId: string, ): Promise { return await db .select({ id: schema.capabilityFacetInstallations.id, kind: schema.capabilityFacets.kind, facetId: schema.capabilityFacets.id, }) .from(schema.capabilityFacetInstallations) .innerJoin( schema.capabilityFacets, eq(schema.capabilityFacets.id, schema.capabilityFacetInstallations.facetId), ) .where(eq(schema.capabilityFacetInstallations.pluginInstallationId, pluginInstallationId)); } async function migrateApiIntegrationFacetInstallations( db: Database, input: { workspaceId: string; subjectId: string; oldFacetInstallations: InstalledFacetRow[]; integrationFacetInstallationId: string; apiFacetInstallationId: string; /** The target revision's integration facet, which owns its facet definitions. */ integrationFacetId: string; facetDefinitions: ReadonlyMap; excludedRuntimeKey: string; revision: StoredApiIntegrationRevision; previousRevision: StoredApiIntegrationRevision | null; sameEndpoint: boolean; baseUrl: string; }, ): Promise { if (input.oldFacetInstallations.length === 0) return; const oldIntegration = input.oldFacetInstallations.find((row) => row.kind === "integration"); const targetByKind = new Map([ ["integration", input.integrationFacetInstallationId], ["api", input.apiFacetInstallationId], ]); const oldIds = input.oldFacetInstallations.map((row) => row.id); const owners = await db .select({ facetInstallationId: schema.capabilityComponentOwners.facetInstallationId, accountId: schema.capabilityComponentOwners.accountId, workspaceId: schema.capabilityComponentOwners.workspaceId, ownerKind: schema.capabilityComponentOwners.ownerKind, ownerId: schema.capabilityComponentOwners.ownerId, removable: schema.capabilityComponentOwners.removable, }) .from(schema.capabilityComponentOwners) .where(inArray(schema.capabilityComponentOwners.facetInstallationId, oldIds)); const kindByOldId = new Map(input.oldFacetInstallations.map((row) => [row.id, row.kind])); for (const owner of owners) { const targetId = targetByKind.get(kindByOldId.get(owner.facetInstallationId) ?? ""); if (!targetId) continue; await db .insert(schema.capabilityComponentOwners) .values({ accountId: owner.accountId, workspaceId: owner.workspaceId, facetInstallationId: targetId, ownerKind: owner.ownerKind, ownerId: owner.ownerId, removable: owner.removable, }) .onConflictDoNothing(); } if (!oldIntegration) return; const bindings = await db .select({ binding: schema.integrationFacetBindings, facetKey: schema.integrationFacetDefinitions.facetKey, facetKind: schema.integrationFacetDefinitions.kind, }) .from(schema.integrationFacetBindings) .innerJoin( schema.integrationFacetDefinitions, eq(schema.integrationFacetDefinitions.id, schema.integrationFacetBindings.facetDefinitionId), ) .where( and( eq(schema.integrationFacetBindings.workspaceId, input.workspaceId), eq(schema.integrationFacetBindings.integrationFacetInstallationId, oldIntegration.id), or( sql`${schema.integrationFacetBindings.runtimeKey} is null`, ne(schema.integrationFacetBindings.runtimeKey, input.excludedRuntimeKey), ), ), ) .for("update"); const available = new Set(input.revision.tools.map((tool) => tool.id)); const previousTools = input.previousRevision?.tools.map((tool) => tool.id) ?? []; // Tools that call operations no other tool covers (a reviewed definition's // generic path tools). They keep a removed tool's operation reachable. const genericTools = input.revision.tools .map((tool) => tool.id) .filter((id) => { const binding = (input.revision.bindings as Record)[id]; return binding?.genericPath !== undefined; }); for (const row of bindings) { const binding = row.binding; const targetFacet = input.facetDefinitions.get(row.facetKey); if (!targetFacet || targetFacet.kind !== row.facetKind) { throw new Error(`API Integration update would remove configured facet ${row.facetKey}`); } const config = objectValue(binding.config); const toolsConfig = row.facetKind === "tools"; const previouslySelected = toolsConfig ? (stringArray(config.allowedTools) ?? []) : []; const selected = !toolsConfig ? [] : previousTools.length > 0 && previousTools.every((tool) => previouslySelected.includes(tool)) ? // An instance that had every tool keeps having every tool, so // moving other people's instances never narrows them. [...available] : [ ...new Set([ ...previouslySelected.filter((tool) => available.has(tool)), // A selected tool the new revision drops stays reachable // through the generic tools, when the definition has them. ...(previouslySelected.some((tool) => !available.has(tool)) ? genericTools : []), ]), ]; const requireApproval = toolsConfig ? apiIntegrationRequiredApprovals({ revision: input.revision, previousRevision: input.previousRevision, selectedTools: selected, previousConfig: config, sameAuthority: input.sameEndpoint, }) : []; await db .update(schema.integrationFacetBindings) .set({ integrationFacetInstallationId: input.integrationFacetInstallationId, facetDefinitionId: targetFacet.id, config: toolsConfig ? { ...config, allowedTools: selected, requireApproval } : config, status: toolsConfig && selected.length === 0 ? "needs_attention" : binding.status, lastErrorCode: toolsConfig && selected.length === 0 ? "selected_tools_removed" : binding.lastErrorCode, version: binding.version + 1, updatedAt: new Date(), }) .where(eq(schema.integrationFacetBindings.id, binding.id)); if (toolsConfig && binding.runtimeKey) await resetChangedApiToolPreferences(db, { accountId: binding.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, serverId: binding.runtimeKey, connectionId: binding.connectionId, baseUrl: input.baseUrl, selectedTools: selected, previousRevision: input.previousRevision, revision: input.revision, sameEndpoint: input.sameEndpoint, }); } } async function loadInstallConnection( db: Database, input: InstallApiIntegrationInput, ): Promise { const [connection] = await db .select() .from(schema.connections) .where( and( eq(schema.connections.workspaceId, input.workspaceId), eq(schema.connections.id, input.connectionId!), ), ) .limit(1); if (!connection || connection.accountId !== input.accountId) { throw new ApiIntegrationConnectionReferenceError( "not_found", "API Integration connection was not found in this workspace", ); } if (connection.subjectId && connection.subjectId !== input.subjectId) { // Do not reveal the existence or owner of a Connection the caller cannot use. throw new ApiIntegrationConnectionReferenceError( "not_found", "API Integration connection was not found in this workspace", ); } if (connection.status !== "active") { throw new ApiIntegrationConnectionReferenceError( "inactive", "API Integration connection is not active", ); } if (connection.providerDomain.toLowerCase() !== input.providerDomain.toLowerCase()) { throw new ApiIntegrationConnectionReferenceError( "provider_mismatch", "API Integration connection provider does not match the destination", ); } assertConnectionKindMatchesAuth(input.authScheme, connection.kind); const grantedScopes = new Set( connection.grantedScopes.map((scope) => connectionScopeKey(connection.providerDomain, scope)), ); const missing = normalizedStrings(input.requiredScopes ?? [], 256).filter( (scope) => !grantedScopes.has(connectionScopeKey(connection.providerDomain, scope)), ); if (missing.length > 0) { throw new ApiIntegrationConnectionReferenceError( "scope_mismatch", "API Integration connection is missing required scopes", ); } return connection; } function assertConnectionKindMatchesAuth( authScheme: Record | undefined, connectionKind: string, ): void { const auth = objectValue(authScheme); const authKind = stringValue(auth.kind); if (authKind === undefined || authKind === "none") return; if (authKind === "oauth2") { if (connectionKind !== "oauth2") { throw new ApiIntegrationConnectionReferenceError( "kind_mismatch", "API Integration requires an OAuth Connection", ); } return; } if (authKind === "api_key" || authKind === "http") { if (connectionKind !== "api_key") { throw new ApiIntegrationConnectionReferenceError( "kind_mismatch", "API Integration requires a credential Connection, not OAuth", ); } return; } throw new Error("API Integration auth scheme is unsupported"); } async function ensureFacet( db: Database, input: { pluginVersionId: string; facetKey: string; kind: "integration" | "api" }, ): Promise { const [existing] = await db .select() .from(schema.capabilityFacets) .where( and( eq(schema.capabilityFacets.pluginVersionId, input.pluginVersionId), eq(schema.capabilityFacets.facetKey, input.facetKey), ), ) .limit(1); if (existing) { if (existing.kind !== input.kind) throw new Error(`Capability facet ${input.facetKey} changed kind`); return existing; } const [created] = await db .insert(schema.capabilityFacets) .values({ pluginVersionId: input.pluginVersionId, facetKey: input.facetKey, kind: input.kind, activationMode: "workspace_managed", required: true, }) .returning(); if (!created) throw new Error(`Failed to create capability facet ${input.facetKey}`); return created; } async function ensureFacetInstallation( db: Database, input: { accountId: string; workspaceId: string; pluginInstallationId: string; facetId: string; connectionId: string | null; config: Record; }, ): Promise<{ row: typeof schema.capabilityFacetInstallations.$inferSelect; changed: boolean }> { const [existing] = await db .select() .from(schema.capabilityFacetInstallations) .where( and( eq(schema.capabilityFacetInstallations.pluginInstallationId, input.pluginInstallationId), eq(schema.capabilityFacetInstallations.facetId, input.facetId), ), ) .limit(1); if (!existing) { const [created] = await db .insert(schema.capabilityFacetInstallations) .values({ accountId: input.accountId, workspaceId: input.workspaceId, pluginInstallationId: input.pluginInstallationId, facetId: input.facetId, connectionId: input.connectionId, status: "active", config: input.config, }) .returning(); if (!created) throw new Error("Failed to create capability facet installation"); return { row: created, changed: true }; } if ( existing.connectionId === input.connectionId && stableJson(existing.config) === stableJson(input.config) && existing.status === "active" ) { return { row: existing, changed: false }; } const [updated] = await db .update(schema.capabilityFacetInstallations) .set({ connectionId: input.connectionId, status: "active", config: input.config, version: existing.version + 1, attentionCode: null, updatedAt: new Date(), }) .where(eq(schema.capabilityFacetInstallations.id, existing.id)) .returning(); if (!updated) throw new Error("Failed to update capability facet installation"); return { row: updated, changed: true }; } type IntegrationInstanceContext = { instanceId: string; instanceVersion: number; displayName: string; pluginInstallationId: string; installationVersion: number; /** Who added this instance; a member removes only their own. */ createdBySubjectId: string; }; async function integrationInstanceContext( db: Database, workspaceId: string, subjectId: string, capabilityId: string, instanceKey: string, lock = false, ): Promise { let query = db .select({ instanceId: schema.integrationFacetBindings.id, instanceVersion: schema.integrationFacetBindings.version, displayName: schema.integrationFacetBindings.displayName, pluginInstallationId: schema.capabilityPluginInstallations.id, installationVersion: schema.capabilityPluginInstallations.version, createdBySubjectId: schema.integrationFacetBindings.createdBySubjectId, }) .from(schema.integrationFacetBindings) .innerJoin( schema.integrationFacetDefinitions, eq(schema.integrationFacetDefinitions.id, schema.integrationFacetBindings.facetDefinitionId), ) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.id, schema.integrationFacetBindings.integrationFacetInstallationId, ), ) .innerJoin( schema.capabilityPluginInstallations, eq( schema.capabilityPluginInstallations.id, schema.capabilityFacetInstallations.pluginInstallationId, ), ) .innerJoin( schema.capabilityPluginVersions, eq(schema.capabilityPluginVersions.id, schema.capabilityPluginInstallations.pluginVersionId), ) .where( and( eq(schema.integrationFacetBindings.workspaceId, workspaceId), eq(schema.integrationFacetBindings.bindingKey, instanceKey), eq(schema.integrationFacetDefinitions.kind, "tools"), sql`${schema.capabilityPluginVersions.manifest} ->> 'capabilityId' = ${capabilityId}`, sql`( ${schema.integrationFacetBindings.connectionId} is null or exists ( select 1 from ${schema.connections} connection where connection.id = ${schema.integrationFacetBindings.connectionId} and (connection.subject_id is null or connection.subject_id = ${subjectId}) ) )`, ), ) .limit(2); if (lock) query = query.for("update") as typeof query; const rows = await query; if (rows.length === 0) return null; if (rows.length !== 1) throw new Error(`API Integration ${capabilityId} instance is ambiguous`); return rows[0]!; } async function integrationDefinitionHasOtherBindingOwner( db: Database, input: { workspaceId: string; pluginInstallationId: string; excludedBindingId: string; owner: Pick; }, ): Promise { const [row] = await db .select({ id: schema.integrationFacetBindingOwners.id }) .from(schema.integrationFacetBindingOwners) .innerJoin( schema.integrationFacetBindings, eq(schema.integrationFacetBindings.id, schema.integrationFacetBindingOwners.bindingId), ) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.id, schema.integrationFacetBindings.integrationFacetInstallationId, ), ) .where( and( eq(schema.integrationFacetBindingOwners.workspaceId, input.workspaceId), eq(schema.integrationFacetBindingOwners.ownerKind, input.owner.kind), eq(schema.integrationFacetBindingOwners.ownerId, input.owner.id), ne(schema.integrationFacetBindingOwners.bindingId, input.excludedBindingId), eq(schema.capabilityFacetInstallations.pluginInstallationId, input.pluginInstallationId), or( eq(schema.integrationFacetBindings.status, "active"), eq(schema.integrationFacetBindings.status, "needs_attention"), eq(schema.integrationFacetBindings.status, "paused"), ), ), ) .limit(1); return Boolean(row); } async function integrationOwners( db: Database, pluginInstallationId: string, ): Promise { const rows = await db .select({ kind: schema.capabilityComponentOwners.ownerKind, id: schema.capabilityComponentOwners.ownerId, removable: schema.capabilityComponentOwners.removable, }) .from(schema.capabilityComponentOwners) .innerJoin( schema.capabilityFacetInstallations, eq( schema.capabilityFacetInstallations.id, schema.capabilityComponentOwners.facetInstallationId, ), ) .where( and( eq(schema.capabilityFacetInstallations.pluginInstallationId, pluginInstallationId), effectiveCapabilityOwnerSql( schema.capabilityComponentOwners.ownerKind, schema.capabilityComponentOwners.ownerId, ), ), ) .orderBy( asc(schema.capabilityComponentOwners.ownerKind), asc(schema.capabilityComponentOwners.ownerId), ); const owners = new Map(); for (const row of rows) { if (row.kind !== "direct" && row.kind !== "plugin" && row.kind !== "migration") { throw new Error(`Unknown API Integration owner kind: ${row.kind}`); } const key = `${row.kind}\0${row.id}`; const existing = owners.get(key); owners.set(key, { kind: row.kind, id: row.id, removable: (existing?.removable ?? true) && row.removable, }); } return [...owners.values()]; } function assertInstallInput(input: InstallApiIntegrationInput): void { if (input.revision.protocol !== input.protocol) throw new Error("API Integration protocol mismatch"); if (!input.definitionId.trim() || input.revision.definitionId !== input.definitionId) { throw new Error("API Integration Definition identity mismatch"); } if ( input.revision.contentSha256.length !== 64 || !/^[0-9a-f]+$/.test(input.revision.contentSha256) ) { throw new Error("API Integration revision digest is invalid"); } if (input.revision.tools.length === 0 || input.revision.tools.length > 2_000) { throw new Error("API Integration revision must expose 1-2000 tools"); } if (new Set(input.revision.tools.map((tool) => tool.id)).size !== input.revision.tools.length) { throw new Error("API Integration revision has duplicate tool ids"); } const facetDefinitions = input.facetDefinitions ?? []; if (facetDefinitions.length > 128) { throw new Error("API Integration exposes too many facet definitions"); } if (new Set(facetDefinitions.map((facet) => facet.facetKey)).size !== facetDefinitions.length) { throw new Error("API Integration has duplicate facet keys"); } const base = new URL(input.baseUrl); if (base.protocol !== "https:" || base.username || base.password || base.hash) { throw new Error("API Integration baseUrl must be a credential-free HTTPS URL"); } if ( base.hostname !== input.providerDomain && !base.hostname.endsWith(`.${input.providerDomain}`) ) { throw new Error("API Integration providerDomain does not match baseUrl"); } const authKind = objectValue(input.authScheme).kind; if (authKind !== undefined && authKind !== "none" && !input.connectionId) { throw new Error("Authenticated API Integrations require a Connection"); } } function selectedToolIds(input: InstallApiIntegrationInput): string[] { const available = new Set(input.revision.tools.map((tool) => tool.id)); const selected = input.allowedTools === undefined ? [...available] : normalizedStrings(input.allowedTools, 2_000); if (selected.some((tool) => !available.has(tool))) { throw new Error("API Integration selected an unknown tool"); } return selected; } function autoApprovedToolIds( input: InstallApiIntegrationInput, selectedTools: readonly string[], ): Set { const requested = normalizedStrings(input.autoApprovedTools ?? [], 2_000); if (requested.some((tool) => !selectedTools.includes(tool))) { throw new Error("API Integration auto-approved a tool that is not selected"); } return new Set(requested); } function isApiIntegrationPermissionReduction( previous: Record, next: Record, ): boolean { const { allowedTools: previousTools, requireApproval: previousApproval, ...previousIdentity } = previous; const { allowedTools: nextTools, requireApproval: nextApproval, ...nextIdentity } = next; const before = stringArray(previousTools); const after = stringArray(nextTools); const requiredBefore = stringArray(previousApproval); const requiredAfter = stringArray(nextApproval); return ( before !== undefined && after !== undefined && requiredAfter !== undefined && (previousApproval === true || requiredBefore !== undefined) && stableJson(previousIdentity) === stableJson(nextIdentity) && after.every( (tool) => before.includes(tool) && (!(previousApproval === true || requiredBefore?.includes(tool)) || requiredAfter.includes(tool)), ) ); } function storedRevision(value: Record): StoredApiIntegrationRevision { const protocol = value.protocol; const tools = value.tools; const bindings = value.bindings; if ( (protocol !== "openapi" && protocol !== "graphql") || typeof value.id !== "string" || typeof value.definitionId !== "string" || typeof value.contentSha256 !== "string" || typeof value.title !== "string" || !Array.isArray(tools) || !bindings || typeof bindings !== "object" || Array.isArray(bindings) ) { throw new Error("Stored API Integration revision is invalid"); } return value as StoredApiIntegrationRevision; } function normalizedStrings(values: string[], limit: number): string[] { const normalized = [...new Set(values.map((value) => value.trim()).filter(Boolean))].sort(); if (normalized.length > limit) throw new Error(`String selection exceeds ${limit} entries`); return normalized; } function stringArray(value: unknown): string[] | undefined { return Array.isArray(value) ? normalizedStrings( value.filter((entry): entry is string => typeof entry === "string"), 2_000, ) : undefined; } function objectValue(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; } function stringValue(value: unknown): string | undefined { return typeof value === "string" && value.length > 0 ? value : undefined; } function sha256(value: string): string { return createHash("sha256").update(value).digest("hex"); }