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 { MCP_DESTINATION_CONNECTION_ERRORS } from "@opengeni/contracts"; import { type NangoProxyTransport } from "@opengeni/contracts/nango"; import { type DnsLookup, type FetchLike } from "@opengeni/network"; export { isPrivateAddress } from "@opengeni/network"; import { encryptEnvironmentValue } from "./environment-crypto.js"; import type { Database } from "./database.js"; import { withConnectionRefreshLock } from "./connection-refresh-lock.js"; import type { AcceptedConnectionUseContext, AcceptedConnectionUseResolution } from "./connection-authority.js"; 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; }; 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"[]; }; export declare function normalizedCredentialHeaders(headers: Record, allowEmpty?: boolean): Record; export declare 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 declare function brokeredCredentialBundleProblem(credential: Record): string | null; 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; }; export declare function buildConnectionTokenResolver(db: Database, settings: Settings, deps: ConnectionBrokerDeps, options?: ConnectionTokenResolverOptions): (input: ResolveConnectionCredentialInput) => Promise; /** Credential-free preflight only. Physical requests still resolve credentials * and enforce their binding, current status and accepted-use authority. */ export declare function connectionMetadataMatchesBinding(connection: ConnectionMetadata, ref: McpServerConnectionRef, destinationUrl: string): boolean; export declare class ConnectionRefreshHttpError extends Error { readonly httpStatus: number; readonly oauthErrorCode: string | null; constructor(httpStatus: number, oauthErrorCode?: string | null, message?: string); } /** * 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 declare class ConnectionNotRefreshableError extends Error { constructor(message: string); } /** * 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 declare function normalizeBearerScheme(tokenType: string | null | undefined): string; export declare function refreshOAuthConnectionCredential(cred: ConnectionCredentialForBroker, ref: McpServerConnectionRef, settings: Settings, transportOptions?: RefreshTransportOptions): Promise<{ credential: Record; expiresAt: Date | null; grantedScopes?: string[]; metadata?: Record; }>;