import { isSlackPrivateFileUrl, normalizeSlackScopes, OFFICIAL_SLACK_MCP_URL, } from "@opengeni/contracts/slack-rest-mcp"; import { beginMcpPhase, measureMcpPhase } from "@opengeni/observability"; import { environmentsEncryptionKeyBytes, type McpServerConnectionRef, type Settings, } from "@opengeni/config"; import type { ConnectionCredentialPlacement, ConnectionKind, ConnectionStatus, ConnectionMetadata, McpConnectionResourceScope, McpCredentialAuthNeededReason, } from "@opengeni/contracts"; import { type ConnectionUseAttribution } from "@opengeni/contracts/connection-authority"; import { containsSecretReference, credentialHeadersHaveSecretReferences, isVaultCredentialConnection, MCP_DESTINATION_CONNECTION_ERRORS, } from "@opengeni/contracts"; import { isNangoConnectionCredential, isNangoProviderDomain, nangoAuthHeaders, nangoDestinationAllowed, nangoIntegrationKeyFromProviderDomain, nangoToolsMcpUrl, nativeNangoIntegrationByKey, type NangoProxyTransport, } from "@opengeni/contracts/nango"; import { BUSINESS_CENTRAL_API_ROOT, businessCentralApiBase, dataverseWebApiBase, FINANCE_OPERATIONS_DATA_PATH, FINANCE_OPERATIONS_METADATA_PATH, financeOperationsOrigin, } from "@opengeni/contracts/microsoft-dynamics"; import { PERSONAL_GITHUB_REQUESTED_SCOPES, PERSONAL_GITHUB_PROVIDER_DOMAIN, PERSONAL_GITHUB_TOKEN_URL, PersonalGitHubConnectionMetadata, } from "@opengeni/contracts/personal-github"; import { createHash } from "node:crypto"; import { OAUTH_MAX_RESPONSE_BYTES, pinnedFetch, readResponseJsonBounded, readResponseTextBounded, undiciFetch, validateHttpUrl, type DnsLookup, type FetchLike, } from "@opengeni/network"; export { isPrivateAddress } from "@opengeni/network"; import { Buffer } from "node:buffer"; import { encryptEnvironmentValue } from "./environment-crypto"; import type { Database } from "./database"; import { withConnectionRefreshLock } from "./connection-refresh-lock"; import { IdJagExchangeError, isIdJagCredential, refreshIdJagConnectionCredential, } from "./id-jag-issuer"; import type { AcceptedConnectionUseContext, AcceptedConnectionUseResolution, } from "./connection-authority"; import { connectionScopeKey } from "./connection-scopes"; const MAX_CREDENTIAL_PLACEMENTS = 32; const MAX_CREDENTIAL_NAME_BYTES = 256; const MAX_CREDENTIAL_VALUE_BYTES = 16_384; const HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/; const QUERY_NAME_PATTERN = /^[A-Za-z0-9._~-]+$/; const COOKIE_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; const FORBIDDEN_CREDENTIAL_HEADERS = new Set([ "connection", "content-length", "host", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", ]); export type ConnectionCredentialForBroker = { id: string; accountId: string; workspaceId: string; subjectId: string | null; providerDomain: string; kind: ConnectionKind; status: ConnectionStatus; credential: Record; grantedScopes: string[]; expiresAt: Date | null; lastRefreshAt: Date | null; version: number; /** Immutable execution authority generation; distinct from token refresh version. */ authorityGeneration?: number; metadata: Record; }; export type ConnectionCredentialLookupInput = { workspaceId: string; connectionId?: string; providerDomain: string; kind?: ConnectionKind; subjectId?: string | null; allowSubjectOwned?: boolean; expectedAuthorityGeneration?: number; }; export type ConnectionTokenRefreshInput = { id: string; version: number; workspaceId: string; credentialEncrypted: string; expiresAt: Date | null; grantedScopes?: string[]; metadata?: Record; lastRefreshAt: Date; subjectId?: string | null; }; export type ConnectionStatusGuard = { id: string; version: number; subjectId?: string | null; }; export type ResolveConnectionCredentialResult = | { status: "ok"; headers: Record; /** Credential authority is owned by the embedding host, not the native connection store. */ authoritySource?: "host"; /** Present when the credential bundle or embedding host supplied explicit placements. */ placements?: ConnectionCredentialPlacement[]; connectionId: string; /** Exact durable version when the credential came from the local connection store. */ connectionVersion?: number; /** Mark a rejected MCP setup on the exact native credential version that was used. */ reportMcpDestinationRefusal?: ( reason: keyof typeof MCP_DESTINATION_CONNECTION_ERRORS, ) => Promise; /** Actual provider grants; never inferred from requested connection scopes. */ grantedScopes?: string[]; /** Metadata-only owner attribution from the immediate pre-use fence. */ connectionUseAttribution?: ConnectionUseAttribution; /** Metadata-only equality key from current live authority; never credentials or authorization. */ operationAuthorityDigest?: string; /** * Revalidate the exact accepted attempt immediately before one target * provider request. Credential lookup/refresh is a separate audited * boundary and must not manufacture a provider-request fact by itself. */ authorizeProviderRequest?: () => Promise; expiresAt?: Date | null; /** * Present for a Nango-backed connection: `headers` authenticate to the * Nango API, and the caller must send its already-validated provider * request through this proxy (see credentialRequestTarget). */ proxy?: NangoProxyTransport; } | { status: "auth_needed"; reason: McpCredentialAuthNeededReason; providerDomain: string; /** Credential authority is owned by the embedding host, not the native connection store. */ authoritySource?: "host"; provider?: string; connectionId?: string; scopes?: string[]; resource?: string; selectedResources?: McpConnectionResourceScope[]; authorizationUrl?: string; }; type AuthNeededReason = Extract< ResolveConnectionCredentialResult, { status: "auth_needed" } >["reason"]; export type ResolveConnectionCredentialInput = { workspaceId: string; subjectId?: string; serverId: string; toolName?: string; /** @deprecated Use toolName. Retained for the API's pre-existing broker call shape. */ toolId?: string; connectionRef: McpServerConnectionRef; /** Exact MCP destination whose request would receive the resolved headers. */ destinationUrl: string; /** Defaults to header-only MCP transport. */ credentialTarget?: "mcp" | "http_api"; forceRefresh?: boolean; /** Internal lookup mode. Preflight must not refresh credentials or record provider usage. */ credentialResolutionMode?: "execution" | "preflight"; /** * Approval preflight only: an expired OAuth access token that still has a * refresh token passes, because execution (never the preflight) refreshes * it. Ignored in execution mode. */ preflightAcceptsRefreshableExpiry?: boolean; /** Frozen provider authority generation captured by the calling integration/catalog. */ expectedAuthorityGeneration?: number; /** Attribution already authorized for forwarding to a host resolver; never authorizes local use. */ hostConnectionUseAttribution?: ConnectionUseAttribution; /** Exact accepted attempt plus one stable physical-provider request id. */ connectionUseContext?: AcceptedConnectionUseContext; /** * Transports the caller can apply besides sending `headers` to * `destinationUrl` directly. A Nango-backed connection resolves only for a * caller that declares `nango_proxy`; any other caller gets auth_needed. */ acceptedTransports?: readonly "nango_proxy"[]; }; const OFFICIAL_GMAIL_MCP_RESOURCE = "https://gmailmcp.googleapis.com/mcp/v1"; const OFFICIAL_GMAIL_REST_HOST = "gmail.googleapis.com"; /** * The Gmail bridge reuses the exact OAuth grant created for the official * hosted Gmail MCP resource, executing every tool against Gmail's REST API * instead of Google's Developer Preview MCP endpoint. Keep this exception * narrower than ordinary provider-domain binding: HTTPS only, Google's * canonical Gmail API host, and the authenticated `users/me` path. */ function isOfficialGmailRestDestination( destinationUrl: string, ref: McpServerConnectionRef, ): boolean { if ( ref.providerDomain.toLowerCase() !== "gmailmcp.googleapis.com" || ref.kind !== "oauth2" || ref.subjectScope !== "subject" ) { return false; } const destination = new URL(destinationUrl); return ( destination.protocol === "https:" && destination.hostname.toLowerCase() === OFFICIAL_GMAIL_REST_HOST && (destination.pathname === "/gmail/v1/users/me" || destination.pathname.startsWith("/gmail/v1/users/me/")) ); } /** The reviewed Drive extensions share one personal MCP grant and exact Google API routes. */ function isOfficialDriveRestDestination( destinationUrl: string, ref: McpServerConnectionRef, ): boolean { if ( ref.providerDomain !== "drivemcp.googleapis.com" || ref.kind !== "oauth2" || ref.subjectScope !== "subject" ) return false; const url = new URL(destinationUrl); return ( url.origin === "https://www.googleapis.com" && !url.username && !url.password && !url.hash && (/^\/drive\/v3\/(?:files\/[a-zA-Z0-9_-]+(?:\/permissions(?:\/[a-zA-Z0-9_-]+)?)?|changes(?:\/startPageToken)?)$/u.test( url.pathname, ) || /^\/upload\/drive\/v3\/files\/[a-zA-Z0-9_-]+$/u.test(url.pathname)) ); } /** * The Google Calendar bridge reuses the personal grant created for the hosted * Calendar MCP identity and executes every tool against Calendar's REST API. * Like Gmail, this exception is narrower than provider-domain binding: HTTPS, * Google's API origin and only the calendar-list, event and free/busy routes. */ function isOfficialGoogleCalendarRestDestination( destinationUrl: string, ref: McpServerConnectionRef, ): boolean { if ( ref.providerDomain.toLowerCase() !== "calendarmcp.googleapis.com" || ref.kind !== "oauth2" || ref.subjectScope !== "subject" ) return false; const url = new URL(destinationUrl); return ( url.origin === "https://www.googleapis.com" && !url.username && !url.password && !url.hash && /^\/calendar\/v3\/(?:users\/me\/calendarList(?:\/[^/]+)?|calendars\/[^/]+\/events(?:\/[^/]+)?|freeBusy)$/u.test( url.pathname, ) ); } /** * Adapts the public embedding credential port to the runtime's connection * resolver contract. Scope echoes are checked before credential headers can * reach a request; the returned object is a fresh copy so a host cannot mutate * headers after resolution. */ function copySelectedResources( resources: McpConnectionResourceScope[], ): McpConnectionResourceScope[] { if (resources.length === 0 || resources.length > 256) { throw new Error("connection credential returned an invalid selected resource count"); } const seen = new Set(); return resources.map((resource) => { if ( resource.kind !== "repository" || typeof resource.id !== "string" || resource.id.length === 0 || resource.id.length > 512 ) { throw new Error("connection credential returned an invalid selected resource"); } const key = `${resource.kind}\0${resource.id}`; if (seen.has(key)) { throw new Error("connection credential returned duplicate selected resources"); } seen.add(key); return { kind: resource.kind, id: resource.id }; }); } export function normalizedCredentialHeaders( headers: Record, allowEmpty = false, ): Record { const entries = Object.entries(headers); if ((!allowEmpty && entries.length === 0) || entries.length > 32) { throw new Error("connection credential returned an invalid header count"); } const normalized: Record = {}; for (const [name, value] of entries) { if ( name.length > 256 || !HEADER_NAME_PATTERN.test(name) || value.length === 0 || value.length > 16_384 || /[\r\n\0]/.test(value) || FORBIDDEN_CREDENTIAL_HEADERS.has(name.toLowerCase()) || name.toLowerCase().startsWith("sec-") ) { throw new Error("connection credential returned an invalid header"); } if (Object.keys(normalized).some((existing) => existing.toLowerCase() === name.toLowerCase())) { throw new Error("connection credential returned duplicate headers"); } normalized[name] = value; } return normalized; } export const BROKERED_CREDENTIAL_SHAPE_HINT = 'store { headers: { "": "" } } or { placements: [{ carrier: "header" | "query" | "cookie", name, value, prefix? }] }'; /** * Why a non-OAuth credential bundle cannot be placed on a brokered request, * or null when the runtime broker can use it. Mirrors * `credentialMaterialForConnection` exactly so create-time validation and * execution never disagree. */ export function brokeredCredentialBundleProblem( credential: Record, ): string | null { if (credential.placements !== undefined) { try { normalizedCredentialPlacements(credential.placements); return null; } catch (error) { return `invalid credential placements (${credentialProblemDetail(error)}); ${BROKERED_CREDENTIAL_SHAPE_HINT}`; } } if (credential.headers !== undefined) { const headers = stringRecord(credential.headers); if (!headers) { return `credential.headers must map header names to string values; ${BROKERED_CREDENTIAL_SHAPE_HINT}`; } try { normalizedCredentialHeaders(headers); return null; } catch (error) { return `invalid credential headers (${credentialProblemDetail(error)}); ${BROKERED_CREDENTIAL_SHAPE_HINT}`; } } const unplaced = Object.keys(credential).filter( (key) => key !== "headers" && key !== "placements", ); return `an api_key credential must say where the secret goes on each request${ unplaced.length > 0 ? ` (fields such as ${unplaced .slice(0, 3) .map((key) => JSON.stringify(key.slice(0, 64))) .join(", ")} are never sent)` : "" }; ${BROKERED_CREDENTIAL_SHAPE_HINT}`; } function credentialProblemDetail(error: unknown): string { return error instanceof Error ? error.message.replace(/^connection credential returned /, "") : "invalid value"; } function normalizedCredentialPlacements(value: unknown): ConnectionCredentialPlacement[] { if (!Array.isArray(value) || value.length === 0 || value.length > MAX_CREDENTIAL_PLACEMENTS) { throw new Error("connection credential returned an invalid placement count"); } const seen = new Set(); return value.map((raw) => { if (!raw || typeof raw !== "object" || Array.isArray(raw)) { throw new Error("connection credential returned an invalid placement"); } const record = raw as Record; if ( Object.keys(record).some( (key) => key !== "carrier" && key !== "name" && key !== "value" && key !== "prefix", ) ) { throw new Error("connection credential returned an invalid placement"); } const carrier = record.carrier; const name = record.name; const credentialValue = record.value; const prefix = record.prefix; if ( (carrier !== "header" && carrier !== "query" && carrier !== "cookie") || typeof name !== "string" || name.length === 0 || Buffer.byteLength(name) > MAX_CREDENTIAL_NAME_BYTES || typeof credentialValue !== "string" || credentialValue.length === 0 || (typeof prefix !== "undefined" && typeof prefix !== "string") || /[\r\n\0]/.test(name) || /[\r\n\0]/.test(credentialValue) || (typeof prefix === "string" && /[\r\n\0]/.test(prefix)) || Buffer.byteLength(`${typeof prefix === "string" ? prefix : ""}${credentialValue}`) > MAX_CREDENTIAL_VALUE_BYTES ) { throw new Error("connection credential returned an invalid placement"); } const normalizedName = carrier === "header" ? name.toLowerCase() : name; if ( (carrier === "header" && (!HEADER_NAME_PATTERN.test(name) || FORBIDDEN_CREDENTIAL_HEADERS.has(normalizedName) || normalizedName.startsWith("sec-"))) || (carrier === "query" && !QUERY_NAME_PATTERN.test(name)) || (carrier === "cookie" && (!COOKIE_NAME_PATTERN.test(name) || /;/.test(`${prefix ?? ""}${credentialValue}`))) ) { throw new Error("connection credential returned an invalid placement"); } const key = `${carrier}\0${normalizedName}`; if (seen.has(key)) { throw new Error("connection credential returned duplicate placements"); } seen.add(key); return { carrier, name, value: credentialValue, ...(typeof prefix === "string" && prefix.length > 0 ? { prefix } : {}), }; }); } function headerMapForPlacements( placements: readonly ConnectionCredentialPlacement[], ): Record { const headers: Record = {}; for (const placement of placements) { if (placement.carrier === "header") { headers[placement.name] = `${placement.prefix ?? ""}${placement.value}`; } } return headers; } export type ConnectionBrokerDeps = { loadCredential: ( db: Database, settings: Settings, input: ConnectionCredentialLookupInput, ) => Promise; recordRefresh: (db: Database, input: ConnectionTokenRefreshInput) => Promise; setStatus: ( db: Database, workspaceId: string, status: ConnectionStatus, lastError: string | null, guard: ConnectionStatusGuard, ) => Promise; recordUsed: ( db: Database, workspaceId: string, connectionId: string, subjectId?: string | null, ) => Promise; refresh: typeof refreshOAuthConnectionCredential; /** Test/adapter seam; standalone defaults to the database-backed refresh lock. */ withRefreshLock?: typeof withConnectionRefreshLock; encrypt: typeof encryptEnvironmentValue; keyBytes: typeof environmentsEncryptionKeyBytes; now: () => Date; authorizeAcceptedUse?: ( db: Database, input: AcceptedConnectionUseContext & { serverId: string; connectionId?: string; providerDomain: string; connectionKind?: ConnectionKind; subjectScope?: "workspace" | "subject"; ownerSubjectId?: string; }, ) => Promise; }; export type PermanentConnectionRefreshFailure = { workspaceId: string; connectionId: string; connectionVersion: number; subjectId: string | null; providerDomain: string; httpStatus: number; oauthErrorCode: string | null; }; export type ConnectionTokenResolverOptions = { /** Provider-aware transport override used by local/integration adapters. */ refreshTransport?: RefreshTransportOptions; /** * Optional provider adapter for an atomic, metadata-aware permanent refresh * transition. Returning true means the adapter owned the transition (even if * its CAS lost to newer truth); false falls back to generic needs_reauth. */ transitionPermanentRefreshFailure?: ( failure: PermanentConnectionRefreshFailure, ) => Promise; /** * Called when a refresh was attempted and failed for a reason that may pass * (the token endpoint was unreachable, answered 5xx, 408 or 429, or the * refresh raced another change). The connection stays active and the result * is still `refresh_failed`. Not called for a rejected grant or for a * connection that cannot be refreshed at all (see * ConnectionNotRefreshableError): only reconnecting fixes those. */ onTransientRefreshFailure?: (failure: { connectionId: string }) => void; /** * Called once, when this resolve is the one that moved an active connection * to `needs_reauth` because its provider rejected the stored grant. A later * resolve of the already-broken connection, a transient failure or a lost * status race never calls it, so the owner can be told exactly once. */ onConnectionNeedsReauth?: (broken: ConnectionNeedsReauth) => void | Promise; /** * Swaps the vault values into a shared service connection's stored headers * (its credential holds `{{secret:…}}` references, see docs/secrets.md) * for one request. Runs with the connection's own vault reach, records the * use, and throws when a reference can't be resolved. Without it such a * connection never resolves: the result is auth_needed, and no reference * text is ever sent to the tool. */ resolveCredentialReferences?: ( input: CredentialReferenceResolution, ) => Promise>; }; /** One request's shared-key resolution (see `resolveCredentialReferences`). */ export type CredentialReferenceResolution = { connection: { id: string; accountId: string; workspaceId: string; providerDomain: string; }; /** The stored headers, references and all. */ headers: Record; serverId: string; toolName?: string; destinationUrl: string; /** Who and what caused this request, for the vault audit entry only. */ onBehalfOf?: { subjectId?: string; sessionId?: string; turnId?: string }; }; /** A connection this resolve just found broken: only reconnecting fixes it. */ export type ConnectionNeedsReauth = { /** The workspace that holds the connection (a personal account may live elsewhere). */ workspaceId: string; connectionId: string; subjectId: string | null; providerDomain: string; httpStatus: number; /** The accepted chat turn whose use found it, when there was one. */ use?: { workspaceId: string; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; }; }; export type RefreshTransportOptions = { fetchImpl?: FetchLike; dnsLookup?: DnsLookup; }; const inflight = new Map>(); const REFRESH_WINDOW_MS = 60_000; const CONNECTION_REFRESH_TIMEOUT_MS = 10_000; export function buildConnectionTokenResolver( db: Database, settings: Settings, deps: ConnectionBrokerDeps, options: ConnectionTokenResolverOptions = {}, ): (input: ResolveConnectionCredentialInput) => Promise { type CredentialLookupInput = Pick< ResolveConnectionCredentialInput, "workspaceId" | "connectionRef" | "subjectId" > & { expectedAuthorityGeneration?: number }; const load = async ( input: CredentialLookupInput, lookupDb: Database = db, ): Promise => { const subjectOwned = input.connectionRef.subjectScope === "subject"; if (subjectOwned && !input.subjectId) { return null; } const request: ConnectionCredentialLookupInput = { workspaceId: input.workspaceId, providerDomain: input.connectionRef.providerDomain, allowSubjectOwned: subjectOwned, ...(subjectOwned ? { subjectId: input.subjectId! } : {}), ...(input.expectedAuthorityGeneration !== undefined ? { expectedAuthorityGeneration: input.expectedAuthorityGeneration } : {}), }; if (input.connectionRef.connectionId !== undefined) { request.connectionId = input.connectionRef.connectionId; } if (input.connectionRef.kind !== undefined) { request.kind = input.connectionRef.kind; } const credential = await deps.loadCredential(lookupDb, settings, request); if (!credential) return null; if ( input.expectedAuthorityGeneration !== undefined && credential.authorityGeneration !== input.expectedAuthorityGeneration ) { return null; } if (subjectOwned) { return credential.subjectId === input.subjectId ? credential : null; } return credential.subjectId === null ? credential : null; }; const snapshot = async ( cred: ConnectionCredentialForBroker, ref: McpServerConnectionRef, destinationUrl: string, inputCredentialTarget: "mcp" | "http_api", connectionUseAttribution?: ConnectionUseAttribution, recordUsage = true, acceptedTransports: readonly string[] = [], use: { serverId: string; toolName?: string; onBehalfOf?: CredentialReferenceResolution["onBehalfOf"]; } = { serverId: "" }, ): Promise => { if (cred.status !== "active") { return authNeededForStatus(cred, ref); } if (!connectionBindingMatches(cred, ref, destinationUrl)) { return authNeeded(ref, "missing_connection", cred.id); } const missingScopes = missingRequestedScopes( ref.scopes, cred.grantedScopes, cred.providerDomain, ); if (missingScopes.length > 0) { return { status: "auth_needed", reason: "insufficient_scope", providerDomain: ref.providerDomain, ...(ref.provider ? { provider: ref.provider } : {}), connectionId: cred.id, scopes: missingScopes, ...(ref.resource ? { resource: ref.resource } : {}), ...(ref.selectedResources ? { selectedResources: copySelectedResources(ref.selectedResources) } : {}), }; } const material = isNangoProviderDomain(cred.providerDomain) ? nangoCredentialMaterial(cred, settings, acceptedTransports) : credentialMaterialForConnection(cred, inputCredentialTarget); if (material.status !== "ok") { return { status: "auth_needed", reason: material.status === "unsupported" ? "unsupported_auth" : "refresh_failed", providerDomain: ref.providerDomain, ...(ref.provider ? { provider: ref.provider } : {}), connectionId: cred.id, ...(ref.scopes ? { scopes: ref.scopes } : {}), ...(ref.resource ? { resource: ref.resource } : {}), ...(ref.selectedResources ? { selectedResources: copySelectedResources(ref.selectedResources) } : {}), }; } let headers = material.headers; if (!isVaultCredentialConnection(cred.metadata)) { // A reference stored without the shared-key marker (for example a key // saved by an older replica during a rolling deploy) is never sent as // text and never resolved: only a connection set up as a shared key may // read a vault. Fail closed and send nothing. if ( credentialHeadersHaveSecretReferences(material.headers) || material.placements?.some((placement) => containsSecretReference(placement.value)) ) return authNeeded(ref, "designated_credential_unavailable", cred.id); } else { // A shared service connection: its headers hold vault references. Only // a workspace-owned header key qualifies, and the values are read only // for a real request; the credential-free preflight sends nothing. if (cred.subjectId !== null || cred.kind !== "api_key" || material.placements) return authNeeded(ref, "unsupported_auth", cred.id); if (!recordUsage) headers = {}; else { if (!options.resolveCredentialReferences) return authNeeded(ref, "designated_credential_unavailable", cred.id); try { headers = normalizedCredentialHeaders( await options.resolveCredentialReferences({ connection: { id: cred.id, accountId: cred.accountId, workspaceId: cred.workspaceId, providerDomain: cred.providerDomain, }, headers: material.headers, serverId: use.serverId, ...(use.toolName ? { toolName: use.toolName } : {}), ...(use.onBehalfOf ? { onBehalfOf: use.onBehalfOf } : {}), destinationUrl, }), ); } catch { // Missing item, no access, provider down: fail closed. The reason // tells the person an admin must fix the shared key; nothing about // the item or its value leaves here. return authNeeded(ref, "designated_credential_unavailable", cred.id); } } } if (recordUsage) { await deps.recordUsed(db, cred.workspaceId, cred.id, cred.subjectId); } return { status: "ok", headers, ...(material.placements ? { placements: material.placements } : {}), connectionId: cred.id, connectionVersion: cred.version, ...(recordUsage && inputCredentialTarget === "mcp" && connectionUseAttribution ? { reportMcpDestinationRefusal: (reason: keyof typeof MCP_DESTINATION_CONNECTION_ERRORS) => deps.setStatus( db, cred.workspaceId, "error", MCP_DESTINATION_CONNECTION_ERRORS[reason], { id: cred.id, version: cred.version, subjectId: cred.subjectId, }, ), } : {}), // Reviewed bridges gate each tool on the provider's actual OAuth grants. ...(cred.providerDomain.toLowerCase() === "slack.com" ? { grantedScopes: normalizeSlackScopes(cred.grantedScopes) } : cred.kind === "oauth2" && // A Nango-managed app's fixed scopes are known only when the // integration definition lists them; otherwise the provider decides. !(isNangoProviderDomain(cred.providerDomain) && cred.grantedScopes.length === 0) ? { grantedScopes: [...cred.grantedScopes] } : {}), ...(connectionUseAttribution ? { connectionUseAttribution } : {}), expiresAt: cred.expiresAt, ...(material.proxy ? { proxy: material.proxy } : {}), }; }; const performRefresh = async ( cred: ConnectionCredentialForBroker, ref: McpServerConnectionRef, lockedDb: Database, ): Promise => { const key = deps.keyBytes(settings); if (!key) { throw new Error("OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is not configured"); } const refreshed = await measureMcpPhase("oauth_refresh", () => isIdJagCredential(cred.credential) ? refreshAutoConnectedCredential(lockedDb, settings, cred, ref, options.refreshTransport) : deps.refresh(cred, ref, settings, options.refreshTransport), ); const refreshRecord: ConnectionTokenRefreshInput = { id: cred.id, version: cred.version, workspaceId: cred.workspaceId, credentialEncrypted: deps.encrypt(key, JSON.stringify(refreshed.credential)), expiresAt: refreshed.expiresAt, lastRefreshAt: deps.now(), subjectId: cred.subjectId, }; if (refreshed.grantedScopes !== undefined) { refreshRecord.grantedScopes = refreshed.grantedScopes; } if (refreshed.metadata !== undefined) { refreshRecord.metadata = refreshed.metadata; } const persisted = await deps.recordRefresh(lockedDb, refreshRecord); if (persisted) { const current = await load( { workspaceId: cred.workspaceId, connectionRef: { ...ref, connectionId: cred.id }, ...(cred.subjectId ? { subjectId: cred.subjectId } : {}), }, lockedDb, ); if (current) { return current; } } const winner = await load( { workspaceId: cred.workspaceId, connectionRef: { ...ref, connectionId: cred.id }, ...(cred.subjectId ? { subjectId: cred.subjectId } : {}), }, lockedDb, ); if (winner?.status === "active") { return winner; } throw new Error("connection credential changed during token refresh"); }; const refreshSingleFlight = ( cred: ConnectionCredentialForBroker, ref: McpServerConnectionRef, ): Promise => { const key = `${cred.subjectId ?? "workspace"}:${cred.id}:${cred.version}`; const existing = inflight.get(key); if (existing) { return measureMcpPhase("oauth_wait", () => existing); } const lockWait = beginMcpPhase("oauth_wait"); const promise = (deps.withRefreshLock ?? withConnectionRefreshLock)( db, cred, async (lockedDb) => { lockWait.end(); // A different worker may have rotated while this request waited. Never // exchange the old token again, or switch to another authority generation. const current = await load( { workspaceId: cred.workspaceId, connectionRef: { ...ref, connectionId: cred.id }, ...(cred.subjectId ? { subjectId: cred.subjectId } : {}), }, lockedDb, ); if (!current || current.authorityGeneration !== cred.authorityGeneration) throw new Error("Connection authority changed before token refresh"); if (current.status !== "active" || current.version !== cred.version) return current; return performRefresh(current, ref, lockedDb); }, ).finally(() => { // A lock acquisition failure must also close the diagnostic interval. lockWait.end("failed"); if (inflight.get(key) === promise) { inflight.delete(key); } }); inflight.set(key, promise); return promise; }; return async (input) => { const credentialResolutionMode = input.credentialResolutionMode ?? "execution"; let ref = input.connectionRef; let subjectId = input.subjectId; let credentialWorkspaceId = input.workspaceId; let expectedAuthorityGeneration = input.expectedAuthorityGeneration; let connectionUseAttribution: ConnectionUseAttribution | undefined; if (ref.authoritySource === "host") { return authNeeded(ref, "unsupported_auth", ref.connectionId); } // Repository-scoped provider bindings require a broker that can prove the // selected-resource boundary. The generic standalone credential store has // no provider-specific containment adapter, so it must fail closed instead // of handing an account-wide token to the configured endpoint. if (ref.selectedResources) { return authNeeded(ref, "resource_scope_unavailable", ref.connectionId); } if (input.connectionUseContext !== undefined) { if (!deps.authorizeAcceptedUse) { return authNeeded( ref, ref.subjectScope === "subject" ? "personal_authority_unavailable" : "missing_connection", ref.connectionId, ); } const connectionUseContext = input.connectionUseContext; const authorization = await measureMcpPhase( "provider_authorization", () => deps.authorizeAcceptedUse!(db, { ...connectionUseContext, serverId: input.serverId, ...(ref.connectionId ? { connectionId: ref.connectionId } : {}), providerDomain: ref.providerDomain, ...(ref.kind ? { connectionKind: ref.kind } : {}), subjectScope: ref.subjectScope === "subject" ? "subject" : "workspace", // An owner binding belongs only to the personal lanes. Interactive // turns stamp the initiating human's subjectId on every credential // request regardless of ref scope; forwarding it for a workspace ref // would make the 0279 workspace lane deny the ambient shared row. ...(ref.subjectScope === "subject" && subjectId ? { ownerSubjectId: subjectId } : {}), }), (result) => (result.status === "authorized" ? "completed" : "rejected"), ); if (authorization.status === "denied") { return authNeeded( ref, ref.subjectScope === "subject" ? "personal_authority_unavailable" : "missing_connection", ref.connectionId, ); } if ( expectedAuthorityGeneration !== undefined && authorization.attribution.connectionGeneration !== expectedAuthorityGeneration ) { return authNeeded( ref, authorityReasonForScope(ref.subjectScope === "subject"), ref.connectionId, ); } connectionUseAttribution = authorization.attribution; expectedAuthorityGeneration = authorization.attribution.connectionGeneration; const expectedPersonal = authorization.attribution.scope !== "workspace"; credentialWorkspaceId = authorization.originWorkspaceId; subjectId = authorization.attribution.ownerSubjectId ?? undefined; ref = { ...ref, connectionId: authorization.attribution.connectionId, kind: authorization.connectionKind, subjectScope: expectedPersonal ? "subject" : "workspace", }; } if (ref.subjectScope === "subject" && !subjectId) { return authNeeded(ref, "personal_authority_unavailable", ref.connectionId); } let cred: ConnectionCredentialForBroker | null; try { cred = await load({ workspaceId: credentialWorkspaceId, connectionRef: ref, ...(subjectId ? { subjectId } : {}), ...(expectedAuthorityGeneration !== undefined ? { expectedAuthorityGeneration } : {}), }); } catch { return authNeeded(ref, "refresh_failed"); } if (!cred) { return authNeeded(ref, "missing_connection"); } if (cred.status !== "active") { return authNeededForStatus(cred, ref); } // Reject an audience/destination mismatch before any provider-side refresh // or usage update. Refreshing first would still create an unauthorized // external side effect even though the token was never sent to the target. if (!connectionBindingMatches(cred, ref, input.destinationUrl)) { return authNeeded(ref, "missing_connection", cred.id); } const now = deps.now(); if ( credentialResolutionMode === "preflight" && cred.kind === "oauth2" && (input.forceRefresh === true || (cred.expiresAt !== null && cred.expiresAt.getTime() <= now.getTime() && !( input.preflightAcceptsRefreshableExpiry === true && (stringValue((cred.credential as { refresh_token?: unknown }).refresh_token) || isIdJagCredential(cred.credential)) ))) ) { return authNeeded(ref, "refresh_failed", cred.id); } if ( credentialResolutionMode === "execution" && shouldRefresh(cred, input.forceRefresh === true, now) ) { try { cred = await refreshSingleFlight(cred, ref); } catch (error) { // Only a rejected grant may poison the connection; transient failures // (network errors, AS 5xx) leave it active so the next resolve retries. if (isPermanentRefreshError(error)) { let handled = false; if (options.transitionPermanentRefreshFailure) { try { handled = await options.transitionPermanentRefreshFailure({ workspaceId: cred.workspaceId, connectionId: cred.id, connectionVersion: cred.version, subjectId: cred.subjectId, providerDomain: cred.providerDomain, httpStatus: error.httpStatus, oauthErrorCode: error.oauthErrorCode, }); } catch { handled = false; } } if (!handled) { const transitioned = await deps // A personal credential may originate outside the workspace // consuming it. Apply the CAS to the same row we refreshed. .setStatus(db, cred.workspaceId, "needs_reauth", error.message, { id: cred.id, version: cred.version, subjectId: cred.subjectId, }) .catch(() => false); if (transitioned && options.onConnectionNeedsReauth) { const use = input.connectionUseContext; try { await options.onConnectionNeedsReauth({ workspaceId: cred.workspaceId, connectionId: cred.id, subjectId: cred.subjectId, providerDomain: cred.providerDomain, httpStatus: error.httpStatus, ...(use ? { use: { workspaceId: use.workspaceId, sessionId: use.sessionId, turnId: use.turnId, attemptId: use.attemptId, executionGeneration: use.executionGeneration, }, } : {}), }); } catch { // Telling the owner never changes the credential result. } } } } else if (!(error instanceof ConnectionNotRefreshableError)) { options.onTransientRefreshFailure?.({ connectionId: cred.id }); } return authNeeded(ref, "refresh_failed", cred.id); } } if ( expectedAuthorityGeneration !== undefined && cred.authorityGeneration !== expectedAuthorityGeneration ) { return authNeeded(ref, authorityReasonForScope(ref.subjectScope === "subject"), cred.id); } return await snapshot( cred, ref, input.destinationUrl, input.credentialTarget ?? "mcp", connectionUseAttribution, credentialResolutionMode === "execution", input.acceptedTransports ?? [], { serverId: input.serverId, ...((input.toolName ?? input.toolId) ? { toolName: input.toolName ?? input.toolId } : {}), onBehalfOf: { ...((subjectId ?? input.subjectId) ? { subjectId: (subjectId ?? input.subjectId)! } : {}), ...(input.connectionUseContext ? { sessionId: input.connectionUseContext.sessionId, turnId: input.connectionUseContext.turnId, } : {}), }, }, ); }; } function authorityReasonForScope(personal: boolean): AuthNeededReason { return personal ? "personal_authority_unavailable" : "missing_connection"; } function connectionBindingMatches( cred: Pick, ref: McpServerConnectionRef, destinationUrl: string, ): boolean { if (cred.providerDomain.toLowerCase() !== ref.providerDomain.toLowerCase()) return false; if (ref.kind && cred.kind !== ref.kind) return false; if (isNangoProviderDomain(cred.providerDomain)) return nangoConnectionBindingMatches(cred, ref, destinationUrl); const credential = cred.credential as Record; const metadata = cred.metadata as Record; const boundMcpUrl = stringValue(credential.mcp_url) ?? stringValue(metadata.mcpUrl); const destination = canonicalHttpUrl(destinationUrl); if (!destination) return false; if (boundMcpUrl) { const binding = canonicalHttpUrl(boundMcpUrl); if ( !binding || (destination !== binding && !( binding === "https://drivemcp.googleapis.com/mcp/v1" && isOfficialDriveRestDestination(destination, ref) ) && !( binding === canonicalHttpUrl(OFFICIAL_GMAIL_MCP_RESOURCE) && isOfficialGmailRestDestination(destination, ref) ) && !( binding === "https://calendarmcp.googleapis.com/mcp/v1" && isOfficialGoogleCalendarRestDestination(destination, ref) ) && !( binding === canonicalHttpUrl(OFFICIAL_SLACK_MCP_URL) && isOfficialSlackRestDestination(destination, ref) ) && !isDataverseWebApiDestination(destination, binding, ref) && !isBusinessCentralApiDestination(destination, binding, ref) && !isFinanceOperationsDataDestination(destination, binding, ref)) ) { return false; } } else if (!destinationHostMatchesProvider(destination, cred.providerDomain)) { // Legacy/manual API-key rows may predate mcpUrl metadata. They are still // host-bound to their canonical provider domain, never usable as an // arbitrary bearer/header source for an unrelated MCP destination. return false; } if (cred.kind !== "oauth2") return true; const boundResource = stringValue(credential.resource) ?? stringValue(metadata.resource); if (ref.resource) { if (!boundResource) return false; if (canonicalResource(ref.resource) !== canonicalResource(boundResource)) return false; } return true; } /** Credential-free preflight only. Physical requests still resolve credentials * and enforce their binding, current status and accepted-use authority. */ export function connectionMetadataMatchesBinding( connection: ConnectionMetadata, ref: McpServerConnectionRef, destinationUrl: string, ): boolean { return ( connectionBindingMatches({ ...connection, credential: {} }, ref, destinationUrl) && missingRequestedScopes(ref.scopes, connection.grantedScopes, connection.providerDomain) .length === 0 ); } /** * The Business Central bridge runs a Business Central connection's tools * against the Business Central API. Every environment is the same Entra * resource on one host, so a person's grant reaches each environment they * connect, whichever of their Business Central connections is current. */ function isBusinessCentralApiDestination( destinationUrl: string, binding: string, ref: McpServerConnectionRef, ): boolean { if (!businessCentralApiBase(binding) || ref.kind !== "oauth2") return false; const url = new URL(destinationUrl); const root = new URL(BUSINESS_CENTRAL_API_ROOT); return ( url.origin === root.origin && ref.providerDomain.toLowerCase() === root.hostname && !url.username && !url.password && !url.hash && url.pathname.startsWith(root.pathname) && // The URL parser resolves literal dot segments; refuse encoded separators and // dots that a server could decode into a path outside the API root. !/%(?:2f|5c|2e)/iu.test(url.pathname) ); } /** * The Dataverse bridge runs a Dataverse MCP connection's tools against the same * environment's Web API: same origin as the bound MCP endpoint, under the Web * API root only. */ function isDataverseWebApiDestination( destinationUrl: string, binding: string, ref: McpServerConnectionRef, ): boolean { const base = dataverseWebApiBase(binding); if (!base || ref.kind !== "oauth2") return false; const url = new URL(destinationUrl); const root = new URL(base); return ( url.origin === root.origin && ref.providerDomain.toLowerCase() === root.hostname && !url.username && !url.password && !url.hash && url.pathname.startsWith(root.pathname) && // The URL parser resolves literal dot segments; refuse encoded separators and // dots that a server could decode into a path outside the Web API root. !/%(?:2f|5c|2e)/iu.test(url.pathname) ); } /** * The Finance and Operations bridge runs a Finance and Operations MCP * connection's tools against the same environment's OData data entities and * metadata service: same origin as the bound MCP endpoint, under those roots * only. */ function isFinanceOperationsDataDestination( destinationUrl: string, binding: string, ref: McpServerConnectionRef, ): boolean { const origin = financeOperationsOrigin(binding); if (!origin || ref.kind !== "oauth2") return false; const url = new URL(destinationUrl); // Destinations arrive canonicalized without a trailing slash, so a root // itself (`/data/`) reads as `/data`. const under = (root: string) => url.pathname === root.replace(/\/$/u, "") || url.pathname.startsWith(root); return ( url.origin === origin && ref.providerDomain.toLowerCase() === url.hostname && !url.username && !url.password && !url.hash && // Encoded separators or dots could climb out of the root on the server. !/%(?:2f|5c|2e)/iu.test(url.pathname) && (under(FINANCE_OPERATIONS_DATA_PATH) || under(FINANCE_OPERATIONS_METADATA_PATH)) ); } /** Only the reviewed Slack bridge methods may reuse the hosted resource grant. */ function isOfficialSlackRestDestination( destinationUrl: string, ref: McpServerConnectionRef, ): boolean { if ( ref.providerDomain.toLowerCase() !== "slack.com" || ref.kind !== "oauth2" || (ref.subjectScope !== undefined && ref.subjectScope !== "subject" && ref.subjectScope !== "workspace") ) return false; const url = new URL(destinationUrl); // Private file bytes for files.info results are a separate reviewed host. if (isSlackPrivateFileUrl(url)) return true; return ( url.origin === "https://slack.com" && !url.username && !url.password && [ "auth.test", "conversations.list", "conversations.info", "conversations.members", "users.list", "users.info", "conversations.history", "conversations.replies", "files.info", "conversations.open", "chat.postMessage", ].some((method) => url.pathname === `/api/${method}`) ); } function destinationHostMatchesProvider(destinationUrl: string, providerDomain: string): boolean { const destinationHost = new URL(destinationUrl).hostname.toLowerCase(); const provider = providerDomain .trim() .toLowerCase() .replace(/^\.+|\.+$/g, ""); return ( Boolean(provider) && (destinationHost === provider || destinationHost.endsWith(`.${provider}`)) ); } function canonicalHttpUrl(value: string): string | null { try { const url = new URL(value); if (url.protocol !== "http:" && url.protocol !== "https:") return null; url.hash = ""; url.hostname = url.hostname.toLowerCase(); if ( (url.protocol === "https:" && url.port === "443") || (url.protocol === "http:" && url.port === "80") ) { url.port = ""; } url.pathname = url.pathname.replace(/\/+$/, "") || "/"; return url.toString(); } catch { return null; } } function canonicalResource(value: string): string { return canonicalHttpUrl(value) ?? value.trim(); } export class ConnectionRefreshHttpError extends Error { readonly httpStatus: number; readonly oauthErrorCode: string | null; constructor(httpStatus: number, oauthErrorCode: string | null = null, message?: string) { super(message ?? `connection refresh failed with HTTP ${httpStatus}`); this.name = "ConnectionRefreshHttpError"; this.httpStatus = httpStatus; this.oauthErrorCode = oauthErrorCode; } } /** * The connection holds nothing to refresh with (no refresh token or token * endpoint, or an unusable endpoint). Retrying cannot help; a rejected access * token stays rejected until the person reconnects. The connection itself is * left as it is, since its access token may still work for other requests. */ export class ConnectionNotRefreshableError extends Error { constructor(message: string) { super(message); this.name = "ConnectionNotRefreshableError"; } } // The token endpoint rejecting the grant itself means re-auth is the only way // forward. 429 (throttling) and 408 are transient despite being 4xx; network // failures and AS 5xx are likewise retryable. function isPermanentRefreshError(error: unknown): error is ConnectionRefreshHttpError { return ( error instanceof ConnectionRefreshHttpError && error.httpStatus >= 400 && error.httpStatus < 500 && error.httpStatus !== 408 && error.httpStatus !== 429 ); } /** * An auto-connected login has no refresh token: a new ID-JAG is signed for * its owner and redeemed. The app refusing it is permanent, like a refused * refresh token; not reaching the app is not. */ async function refreshAutoConnectedCredential( db: Database, settings: Settings, cred: ConnectionCredentialForBroker, ref: McpServerConnectionRef, transport: RefreshTransportOptions | undefined, ): Promise<{ credential: Record; expiresAt: Date | null; grantedScopes?: string[]; metadata?: Record; }> { try { return await refreshIdJagConnectionCredential(db, settings, cred, ref, transport ?? {}); } catch (error) { if (error instanceof IdJagExchangeError) throw new ConnectionRefreshHttpError( error.httpStatus === 0 ? 503 : error.httpStatus, error.oauthErrorCode, error.message, ); throw error; } } function shouldRefresh(cred: ConnectionCredentialForBroker, force: boolean, now: Date): boolean { // Nango refreshes provider tokens itself; there is nothing to refresh here. if (cred.kind !== "oauth2" || isNangoProviderDomain(cred.providerDomain)) { return false; } if (force) { return true; } if (!cred.expiresAt) { return false; } return cred.expiresAt.getTime() <= now.getTime() + REFRESH_WINDOW_MS; } function authNeeded( ref: McpServerConnectionRef, reason: AuthNeededReason, connectionId?: string, ): ResolveConnectionCredentialResult { return { status: "auth_needed", reason, providerDomain: ref.providerDomain, ...(ref.provider ? { provider: ref.provider } : {}), ...(connectionId ? { connectionId } : {}), ...(ref.scopes ? { scopes: ref.scopes } : {}), ...(ref.resource ? { resource: ref.resource } : {}), ...(ref.selectedResources ? { selectedResources: copySelectedResources(ref.selectedResources) } : {}), }; } function authNeededForStatus( cred: ConnectionCredentialForBroker, ref: McpServerConnectionRef, ): ResolveConnectionCredentialResult { if (cred.status === "revoked") { return authNeeded(ref, "missing_connection", cred.id); } return authNeeded( ref, cred.expiresAt && cred.expiresAt.getTime() <= Date.now() ? "expired" : "refresh_failed", cred.id, ); } function missingRequestedScopes( requested: string[] | undefined, granted: string[], providerDomain: string, ): string[] { if (!requested?.length) { return []; } const actual = providerDomain.toLowerCase() === "slack.com" ? normalizeSlackScopes(granted) : granted; const grantedSet = new Set(actual.map((scope) => connectionScopeKey(providerDomain, scope))); return requested.filter((scope) => !grantedSet.has(connectionScopeKey(providerDomain, scope))); } /** * Normalizes an OAuth token_type into the Authorization scheme to send. RFC 6750 * says the scheme is case-insensitive, but some MCP servers (e.g. Linear) reject * a lowercase `bearer` — so a `bearer`/`BEARER` (or absent) token_type is sent as * the canonical `Bearer`. A non-bearer scheme is passed through unchanged. */ export function normalizeBearerScheme(tokenType: string | null | undefined): string { return !tokenType || /^bearer$/i.test(tokenType) ? "Bearer" : tokenType; } type ConnectionCredentialMaterial = | { status: "ok"; headers: Record; placements?: ConnectionCredentialPlacement[]; proxy?: NangoProxyTransport; } | { status: "invalid" | "unsupported" }; /** * A Nango connection binds to its integration's exact provider destinations * (Google bridges) or to its own synthetic tool-bridge identity (config-only * integrations). A native and a Nango connection never satisfy each other's * reference because their provider domains differ. */ function nangoConnectionBindingMatches( cred: Pick, ref: McpServerConnectionRef, destinationUrl: string, ): boolean { const key = nangoIntegrationKeyFromProviderDomain(cred.providerDomain); if (!key || cred.kind !== "oauth2" || ref.subjectScope !== "subject") return false; const destination = canonicalHttpUrl(destinationUrl); if (!destination) return false; const native = nativeNangoIntegrationByKey(key); if (native) { if (destination === canonicalHttpUrl(native.mcpUrl)) return true; if (!nangoDestinationAllowed(native.destinations, destination)) return false; // The same exact routes the native grant may reach, nothing broader. const nativeRef = { ...ref, providerDomain: native.nativeProviderDomain }; if (native.integrationKey === "gmail") return isOfficialGmailRestDestination(destination, nativeRef); if (native.integrationKey === "google-calendar") return isOfficialGoogleCalendarRestDestination(destination, nativeRef); return ( isOfficialDriveRestDestination(destination, nativeRef) || isNangoDriveReadDestination(destination) ); } return destination === canonicalHttpUrl(nangoToolsMcpUrl(key)); } /** * Under Nango, Drive reads cannot use Google's hosted Drive MCP server, so the * bridge serves them from these Drive REST routes (docs/nango.md). */ function isNangoDriveReadDestination(destinationUrl: string): boolean { const url = new URL(destinationUrl); return ( url.origin === "https://www.googleapis.com" && !url.username && !url.password && !url.hash && /^\/drive\/v3\/(?:files(?:\/[a-zA-Z0-9_-]+(?:\/export|\/permissions)?)?|about)$/u.test( url.pathname, ) ); } function nangoCredentialMaterial( cred: ConnectionCredentialForBroker, settings: Settings, acceptedTransports: readonly string[], ): ConnectionCredentialMaterial { // Fail closed: a caller that cannot route through the proxy, or a // deployment without the Nango key, gets no headers at all. if (!acceptedTransports.includes("nango_proxy") || !settings.nangoSecretKey) return { status: "unsupported" }; const credential = cred.credential; if ( !isNangoConnectionCredential(credential) || nangoIntegrationKeyFromProviderDomain(cred.providerDomain) !== credential.integrationKey ) return { status: "invalid" }; return { status: "ok", headers: nangoAuthHeaders({ secretKey: settings.nangoSecretKey, nangoConnectionId: credential.nangoConnectionId, providerConfigKey: credential.providerConfigKey, }), proxy: { kind: "nango_proxy", baseUrl: settings.nangoApiBaseUrl, integrationKey: credential.integrationKey, providerConfigKey: credential.providerConfigKey, nangoConnectionId: credential.nangoConnectionId, }, }; } function credentialMaterialForConnection( cred: ConnectionCredentialForBroker, target: "mcp" | "http_api", ): ConnectionCredentialMaterial { if (cred.kind === "oauth2") { const accessToken = stringValue((cred.credential as { access_token?: unknown }).access_token); if (!accessToken) { return { status: "invalid" }; } return { status: "ok", headers: { authorization: `${normalizeBearerScheme(stringValue((cred.credential as { token_type?: unknown }).token_type))} ${accessToken}`, }, }; } const rawPlacements = (cred.credential as { placements?: unknown }).placements; if (rawPlacements !== undefined) { let placements: ConnectionCredentialPlacement[]; try { placements = normalizedCredentialPlacements(rawPlacements); } catch { return { status: "invalid" }; } if (target !== "http_api" && placements.some((placement) => placement.carrier !== "header")) { return { status: "unsupported" }; } return { status: "ok", headers: headerMapForPlacements(placements), placements, }; } try { const headers = normalizedCredentialHeaders( stringRecord((cred.credential as { headers?: unknown }).headers) ?? {}, ); return { status: "ok", headers }; } catch { return { status: "invalid" }; } } export async function refreshOAuthConnectionCredential( cred: ConnectionCredentialForBroker, ref: McpServerConnectionRef, settings: Settings, transportOptions: RefreshTransportOptions = {}, ): Promise<{ credential: Record; expiresAt: Date | null; grantedScopes?: string[]; metadata?: Record; }> { if (cred.kind !== "oauth2") { return { credential: cred.credential, expiresAt: cred.expiresAt, grantedScopes: cred.grantedScopes, }; } const refreshToken = stringValue((cred.credential as { refresh_token?: unknown }).refresh_token); const personalGitHubMetadata = PersonalGitHubConnectionMetadata.safeParse(cred.metadata); const personalGitHub = cred.providerDomain.toLowerCase() === PERSONAL_GITHUB_PROVIDER_DOMAIN && personalGitHubMetadata.success; const storedTokenEndpoint = stringValue((cred.credential as { token_endpoint?: unknown }).token_endpoint) ?? stringValue((cred.metadata as { tokenEndpoint?: unknown }).tokenEndpoint) ?? stringValue((cred.metadata as { token_endpoint?: unknown }).token_endpoint); const tokenEndpoint = personalGitHub ? PERSONAL_GITHUB_TOKEN_URL : storedTokenEndpoint; if (!refreshToken || !tokenEndpoint) { throw new ConnectionNotRefreshableError("connection has no refresh token endpoint"); } if (personalGitHub && storedTokenEndpoint !== PERSONAL_GITHUB_TOKEN_URL) { throw new ConnectionRefreshHttpError(401, "client_unavailable"); } let validatedTokenEndpoint: string; try { validatedTokenEndpoint = validateHttpUrl(tokenEndpoint, { label: "OAuth refresh token endpoint", allowLoopbackHttp: settings.environment === "local" || settings.environment === "test", }); } catch { throw new ConnectionNotRefreshableError("connection has an invalid refresh token endpoint"); } const body = new URLSearchParams(); body.set("grant_type", "refresh_token"); body.set("refresh_token", refreshToken); // Public clients (token_endpoint_auth_method "none") must identify themselves // in the token request body (RFC 6749 §3.2.1); grant flows persist the // client_id they authorized with into the bundle/metadata. const clientId = stringValue((cred.credential as { client_id?: unknown }).client_id) ?? stringValue((cred.metadata as { clientId?: unknown }).clientId) ?? stringValue((cred.metadata as { client_id?: unknown }).client_id); const clientSecret = personalGitHub ? settings.githubPersonalOauthClientSecret : (deploymentClientSecret(settings, clientId) ?? stringValue((cred.credential as { client_secret?: unknown }).client_secret)); const authMethod = stringValue( (cred.credential as { token_endpoint_auth_method?: unknown }).token_endpoint_auth_method, ) ?? "none"; if ( personalGitHub && (!settings.githubPersonalOauthEnabled || !clientId || clientId !== settings.githubPersonalOauthClientId || personalGitHubMetadata.data.oauthEnvironment !== settings.environment || personalGitHubMetadata.data.oauthClientMarker !== createHash("sha256").update(clientId).digest("hex").slice(0, 32) || !clientSecret) ) { throw new ConnectionRefreshHttpError(401, "client_unavailable"); } if (clientId) { body.set("client_id", clientId); } const tokenRequestEncoding = stringValue( (cred.credential as { token_request_encoding?: unknown }).token_request_encoding, ) === "json" ? "json" : "form"; const headers: Record = { // GitHub (and other providers) answer form-encoded unless JSON is asked // for, which made every personal GitHub refresh unparseable and silent. accept: "application/json", "content-type": tokenRequestEncoding === "json" ? "application/json" : "application/x-www-form-urlencoded", }; if (clientSecret && authMethod === "client_secret_post") { body.set("client_secret", clientSecret); } else if (clientId && clientSecret && authMethod === "client_secret_basic") { headers.authorization = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`; } const resource = ref.resource ?? stringValue((cred.credential as { resource?: unknown }).resource); const resourceParameterSupported = (cred.credential as { resource_parameter_supported?: unknown }).resource_parameter_supported !== false; if (resource && resourceParameterSupported) { body.set("resource", resource); } const scopeParameterSupported = (cred.credential as { scope_parameter_supported?: unknown }).scope_parameter_supported !== false; // A grant whose provider needs the scope again on refresh (Microsoft Entra // ID refresh tokens span resources) recorded it when it was authorized. const refreshScope = stringValue((cred.credential as { refresh_scope?: unknown }).refresh_scope); if (ref.scopes?.length && scopeParameterSupported) { body.set("scope", ref.scopes.join(" ")); } else if (refreshScope && scopeParameterSupported) { body.set("scope", refreshScope); } const requestBody: BodyInit = tokenRequestEncoding === "json" ? JSON.stringify(Object.fromEntries(body.entries())) : body; const response = await pinnedFetch( validatedTokenEndpoint, { method: "POST", headers, body: requestBody, signal: AbortSignal.timeout(CONNECTION_REFRESH_TIMEOUT_MS), }, settings, { fetchImpl: transportOptions.fetchImpl ?? undiciFetch, ...(transportOptions.dnsLookup ? { dnsLookup: transportOptions.dnsLookup } : {}), label: "OAuth token endpoint", requireHttpsOutsideLocalTest: true, }, ); if (response.status >= 300 && response.status < 400) { await cancelResponseBody(response); throw new ConnectionRefreshHttpError(response.status); } if (!response.ok) { throw new ConnectionRefreshHttpError( response.status, await readOAuthRefreshErrorCode(response), ); } const payload = await readOAuthTokenResponse(response); const accessToken = stringValue(payload.access_token); if (!accessToken) { const oauthErrorCode = stringValue(payload.error); if (oauthErrorCode) throw refreshRefusedIn200(oauthErrorCode); throw new Error("connection refresh response did not include access_token"); } const expiresAt = expiresAtFromTokenResponse(payload, cred.expiresAt); const scopeText = stringValue(payload.scope); const returnedScopes = scopeText?.split(/[\s,]+/).filter(Boolean) ?? []; // A successful Microsoft refresh proves offline access, although Microsoft // reports only access-token permissions in the response's scope field. if ( scopeText && ref.providerDomain.toLowerCase() === "graph.microsoft.com" && !returnedScopes.some((scope) => scope.toLowerCase() === "offline_access") ) { returnedScopes.push("offline_access"); } const refreshTokenExpiresIn = typeof payload.refresh_token_expires_in === "number" ? payload.refresh_token_expires_in : undefined; const refreshTokenExpiresAt = personalGitHub && refreshTokenExpiresIn && refreshTokenExpiresIn > 0 ? new Date(Date.now() + refreshTokenExpiresIn * 1000).toISOString() : null; if ( personalGitHub && scopeText && (returnedScopes.length !== PERSONAL_GITHUB_REQUESTED_SCOPES.length || returnedScopes.some((scope) => !PERSONAL_GITHUB_REQUESTED_SCOPES.includes(scope as "repo"))) ) { throw new ConnectionRefreshHttpError(401, "scope_changed"); } const nextCredential = { ...cred.credential, access_token: accessToken, refresh_token: stringValue(payload.refresh_token) ?? refreshToken, token_type: stringValue(payload.token_type) ?? stringValue((cred.credential as { token_type?: unknown }).token_type) ?? "Bearer", ...(expiresAt ? { expires_at: expiresAt.toISOString() } : {}), ...(resource ? { resource } : {}), ...(scopeText ? { scope: ref.providerDomain.toLowerCase() === "graph.microsoft.com" ? returnedScopes.join(" ") : scopeText, } : {}), ...(refreshTokenExpiresAt ? { refresh_token_expires_at: refreshTokenExpiresAt } : {}), ...(clientSecret && !personalGitHub ? { client_secret: clientSecret, token_endpoint_auth_method: authMethod } : {}), }; return { credential: nextCredential, expiresAt, ...(personalGitHub ? { grantedScopes: [...PERSONAL_GITHUB_REQUESTED_SCOPES] } : scopeText ? { grantedScopes: returnedScopes } : {}), ...(refreshTokenExpiresAt ? { metadata: PersonalGitHubConnectionMetadata.parse({ ...personalGitHubMetadata.data, refreshTokenExpiresAt, }), } : {}), }; } /** * A token endpoint answer, JSON or form-encoded. We ask for JSON, but GitHub * answers form-encoded without that header (or if a proxy drops it), and an * unparseable success used to fail every refresh silently. */ async function readOAuthTokenResponse(response: Response): Promise> { const form = /application\/x-www-form-urlencoded/i.test( response.headers.get("content-type") ?? "", ); if (!form) { return await readResponseJsonBounded>( response, OAUTH_MAX_RESPONSE_BYTES, "OAuth refresh token response", ); } const text = await readResponseTextBounded( response, OAUTH_MAX_RESPONSE_BYTES, "OAuth refresh token response", ); const payload: Record = {}; for (const [key, value] of new URLSearchParams(text)) { const numeric = /^(expires_in|refresh_token_expires_in)$/.test(key) ? Number(value) : NaN; payload[key] = Number.isFinite(numeric) ? numeric : value; } return payload; } // OAuth error codes in a 200 answer that do not mean the person's grant is // gone: the provider is busy, or our own client credentials are wrong (a // deployment fault that reconnecting cannot fix). They stay transient. const TRANSIENT_OAUTH_REFRESH_ERRORS = new Set([ "slow_down", "temporarily_unavailable", "server_error", "incorrect_client_credentials", "invalid_client", ]); /** * GitHub reports a refused refresh (bad_refresh_token, unauthorized_client) as * HTTP 200 with an OAuth error field. That is the same permanent refusal as a * 400, so the connection asks the person to reconnect instead of failing every * use while it stays active. Unknown codes count as refusals too: a refusal * mistaken for a passing failure is the silent outage this guards against. */ function refreshRefusedIn200(code: string): ConnectionRefreshHttpError { const safe = /^[a-z0-9_.-]{1,64}$/i.test(code) ? code : null; const transient = safe !== null && TRANSIENT_OAUTH_REFRESH_ERRORS.has(safe); return new ConnectionRefreshHttpError( transient ? 503 : 400, safe, `connection refresh refused by the provider (${safe ?? "unknown error"})`, ); } async function readOAuthRefreshErrorCode(response: Response): Promise { try { const payload = await readResponseJsonBounded>( response, OAUTH_MAX_RESPONSE_BYTES, "OAuth refresh error response", ); const code = stringValue(payload.error); return code && /^[a-z0-9_.-]{1,64}$/i.test(code) ? code : null; } catch { await cancelResponseBody(response); return null; } } function expiresAtFromTokenResponse( payload: Record, fallback: Date | null, ): Date | null { const expiresAt = stringValue(payload.expires_at); if (expiresAt) { const parsed = new Date(expiresAt); return Number.isNaN(parsed.getTime()) ? fallback : parsed; } const expiresIn = typeof payload.expires_in === "number" ? payload.expires_in : undefined; if (expiresIn && Number.isFinite(expiresIn) && expiresIn > 0) { return new Date(Date.now() + expiresIn * 1000); } return fallback; } function stringRecord(value: unknown): Record | null { if (!value || typeof value !== "object" || Array.isArray(value)) { return null; } const out: Record = {}; for (const [key, raw] of Object.entries(value)) { if (typeof raw !== "string") { return null; } out[key] = raw; } return out; } /** * The current secret of a deployment-managed client this connection was * authorized with. Read at refresh time so a rotated secret takes effect for * every existing connection; Entra client secrets expire. */ function deploymentClientSecret(settings: Settings, clientId: string | undefined) { const secret = settings.microsoftDynamicsClientSecret?.trim(); return clientId && secret && clientId === settings.microsoftDynamicsClientId?.trim() ? secret : undefined; } function stringValue(value: unknown): string | undefined { return typeof value === "string" && value.length > 0 ? value : undefined; } async function cancelResponseBody(response: Response): Promise { await response.body?.cancel().catch(() => undefined); }