@tangle-network/agent-integrations 0.76.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{hub-Cl8phyJ9.js → hub-BjCYNJWr.js} +3 -3
- package/dist/hub-BjCYNJWr.js.map +1 -0
- package/dist/hub.js +1 -1
- package/dist/index.js +2 -2
- package/dist/mcp.js +2 -2
- package/dist/registry.js +1 -1
- package/dist/{src-VFvRn2yV.js → src-DM3qkMTB.js} +2 -2
- package/dist/{src-VFvRn2yV.js.map → src-DM3qkMTB.js.map} +1 -1
- package/package.json +1 -1
- package/dist/hub-Cl8phyJ9.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-integrations",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Vendor-neutral integration contracts and runtime helpers for sandbox and agent apps.",
|
|
5
5
|
"homepage": "https://github.com/tangle-network/agent-integrations#readme",
|
|
6
6
|
"repository": {
|
package/dist/hub-Cl8phyJ9.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hub-Cl8phyJ9.js","names":["base64UrlEncode"],"sources":["../src/core-error.ts","../src/adapter-provider.ts","../src/credentials.ts","../src/hub.ts"],"sourcesContent":["/**\n * IntegrationError — the runtime error class thrown by the hub, providers,\n * adapters, and runtime helpers. Lives in its own module so any source\n * file can import it without pulling the package barrel (`./index.ts`)\n * and forming a cycle.\n *\n * The richer {@link IntegrationRuntimeError} (in `./errors.ts`) is a\n * separate, structured error type used by consumers wiring custom\n * error → HTTP-status mappings. `IntegrationError` is the legacy/canonical\n * throw shape kept for back-compat with everything that already catches it.\n */\n\nexport type IntegrationErrorRuntimeCode =\n | 'provider_not_found'\n | 'connector_not_found'\n | 'connection_not_found'\n | 'connection_not_active'\n | 'auth_not_supported'\n | 'capability_invalid'\n | 'capability_expired'\n | 'scope_denied'\n | 'action_denied'\n | 'action_not_found'\n | 'trigger_not_found'\n | 'approval_required'\n | 'policy_denied'\n | 'config_missing'\n | 'provider_failure'\n | 'credential_invalid'\n | 'credential_scope_invalid'\n | 'credential_rate_limited'\n | 'credential_probe_unsupported'\n | 'credential_persistence_failure'\n | 'connection_metadata_invalid'\n | 'connection_parameters_missing'\n | 'connection_parameters_invalid'\n\nexport class IntegrationError extends Error {\n constructor(\n message: string,\n readonly code: IntegrationErrorRuntimeCode,\n ) {\n super(message)\n this.name = 'IntegrationError'\n }\n}\n","import type {\n CapabilityMutationResult,\n CapabilityReadResult,\n ConnectorAdapter,\n ConnectorCredentials,\n ConnectorInvocation,\n OAuth2UrlTemplateMetadataSpec,\n ResolvedDataSource,\n} from './connectors/types.js'\nimport type {\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationCatalogSource,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationProvider,\n IntegrationProviderKind,\n} from './core-types.js'\nimport { CredentialsExpired, ProviderRateLimited, ProviderConfigError } from './connectors/types.js'\nimport { IntegrationError } from './core-error.js'\nimport { buildOAuthAuthorizationUrl, exchangeAuthorizationCode, redactOAuthSensitiveText, oauthClientCredentialRedactionValues, createOAuthBasicAuthorizationHeader } from './connectors/oauth-protocol.js'\n\n/** OAuth client credentials the host resolves at start/exchange time.\n * The lib never reads env or any vault — kept edge-runtime-safe. */\nexport interface OAuthClientCredentials {\n clientId: string\n /** Omit for public clients whose manifest uses tokenClientAuthMethod=none. */\n clientSecret?: string\n /** Business-login configuration; replaces per-request scopes. */\n configId?: string\n}\n\nexport interface ConnectorAdapterProviderOptions {\n id?: string\n kind?: IntegrationProviderKind\n adapters: ConnectorAdapter[]\n resolveDataSource: (connection: IntegrationConnection) => Promise<ResolvedDataSource> | ResolvedDataSource\n /** Invoked when an adapter rotates credentials during executeRead /\n * executeMutation (e.g. an OAuth access token refreshed on expiry). The\n * host re-encrypts + persists the rotated envelope so the next expiry\n * does not force a reconnect. Carries the connection so the host can\n * resolve the secretRef. */\n onCredentialsRotated?: (event: {\n connection: IntegrationConnection\n credentials: ConnectorCredentials\n }) => Promise<void> | void\n /** Resolve OAuth client_id and, for confidential clients, client_secret at\n * start- and exchange-time. Host owns env, vault, and per-tenant\n * overrides. Return null to refuse the flow (lib will throw\n * `config_missing`). The lib never logs the secret nor includes it\n * in thrown error messages. */\n resolveOAuthClient?: (input: { connectorId: string }) =>\n | Promise<OAuthClientCredentials | null>\n | OAuthClientCredentials\n | null\n /** Fetch implementation forwarded to the OAuth token exchange. Default\n * is `globalThis.fetch`. Tests inject a mock. */\n fetchImpl?: typeof fetch\n now?: () => Date\n /** Initial encrypted credential commit. Return the canonical reconnect id and secretRef. */\n persistConnection?: (input: { connection: IntegrationConnection; credentials: ConnectorCredentials }) => Promise<IntegrationConnection>\n /** Bounds provider work, including adapters that ignore cancellation. */\n operationTimeoutMs?: number\n}\n\nexport function createConnectorAdapterProvider(options: ConnectorAdapterProviderOptions): IntegrationProvider {\n const providerId = options.id ?? 'first-party'\n const now = options.now ?? (() => new Date())\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch?.bind(globalThis) as typeof fetch | undefined)\n const adapters = new Map(options.adapters.filter((adapter) => !adapter.inboundOnly).map((adapter) => [adapter.manifest.kind, adapter]))\n const requireAdapter = (id: string) => {\n const adapter = adapters.get(id)\n if (!adapter) throw new IntegrationError(`Connector adapter ${id} not found.`, 'connector_not_found')\n if (adapter.catalogOnly) throw new IntegrationError(`Connector ${id} is not configured.`, 'config_missing')\n return adapter\n }\n const requireOAuth = (adapter: ConnectorAdapter) => {\n const auth = oauthManifestAuth(adapter.manifest.auth)\n if (!auth || (auth.grantType ?? 'authorization_code') !== 'authorization_code') {\n throw new IntegrationError(`Connector ${adapter.manifest.kind} does not support authorization-code OAuth.`, 'auth_not_supported')\n }\n return auth\n }\n const requireClient = async (connectorId: string, auth: NonNullable<ReturnType<typeof oauthManifestAuth>>) => {\n const client = await options.resolveOAuthClient?.({ connectorId })\n if (!client?.clientId || (auth.tokenClientAuthMethod !== 'none' && !client.clientSecret)) {\n throw new IntegrationError(`OAuth client credentials unavailable for ${connectorId}.`, 'config_missing')\n }\n if (auth.tokenClientAuthMethod && !['none', 'client_secret_post', 'client_secret_basic'].includes(auth.tokenClientAuthMethod)) {\n throw new IntegrationError('Unsupported OAuth token client authentication method.', 'config_missing')\n }\n return client\n }\n const commit = async (connection: IntegrationConnection, credentials: ConnectorCredentials) => {\n if (!options.persistConnection) throw new IntegrationError('An encrypted credential commit is required.', 'config_missing')\n try {\n const stored = await options.persistConnection({ connection, credentials })\n if (!stored.id || !stored.secretRef?.id || stored.owner.id !== connection.owner.id || stored.owner.type !== connection.owner.type\n || stored.providerId !== connection.providerId || stored.connectorId !== connection.connectorId) throw new Error('Invalid credential commit result.')\n return stored\n } catch (cause) { throw new IntegrationError('Credential commit rejected.', cause instanceof IntegrationError ? cause.code : 'credential_persistence_failure') }\n }\n const provider: IntegrationProvider = {\n id: providerId,\n kind: options.kind ?? 'first_party',\n listConnectors: () => [...adapters.values()].map((adapter) => manifestToConnector(providerId, adapter)),\n async startAuth(request) {\n const adapter = requireAdapter(request.connectorId)\n const auth = requireOAuth(adapter)\n const client = await requireClient(request.connectorId, auth)\n if (!auth.authorizationUrl) throw new IntegrationError('OAuth authorization URL missing.', 'config_missing')\n const metadata = resolveOAuthConnectionMetadata(auth, request.metadata, request.connectorId)\n resolveOAuthUrlTemplate(auth.tokenUrl, metadata, request.connectorId, auth.urlTemplateMetadata)\n const pkce = resolveOAuthPkceMode(auth.pkce, request.connectorId)\n const state = request.state ?? randomState()\n const requestedScopes = request.requestedScopes.length ? request.requestedScopes : auth.scopes\n return {\n providerId, connectorId: request.connectorId, state, requestedScopes,\n authUrl: buildOAuthAuthorizationUrl({\n ...auth, ...client, state, redirectUri: request.redirectUri,\n authorizationUrl: resolveOAuthUrlTemplate(auth.authorizationUrl, metadata, request.connectorId, auth.urlTemplateMetadata),\n scopes: requestedScopes,\n codeChallenge: pkce === 'unsupported' ? undefined : requirePkceChallenge(request.codeChallenge, request.connectorId),\n }),\n metadata,\n }\n },\n async completeAuth(request) {\n const adapter = requireAdapter(request.connectorId)\n const auth = requireOAuth(adapter)\n if (!request.code) throw new IntegrationError('OAuth authorization code missing.', 'config_missing')\n if (!options.persistConnection) throw new IntegrationError('An encrypted credential commit is required.', 'config_missing')\n const metadata = resolveOAuthConnectionMetadata(auth, request.metadata, request.connectorId)\n const codeVerifier = resolveOAuthPkceMode(auth.pkce, request.connectorId) === 'unsupported'\n ? undefined : requirePkceVerifier(request.codeVerifier, request.connectorId)\n // Validate both endpoints before an adapter can send the code elsewhere.\n resolveOAuthUrlTemplate(auth.tokenUrl, metadata, request.connectorId, auth.urlTemplateMetadata)\n const client = await requireClient(request.connectorId, auth)\n const exchanged = await boundedProviderCall(options.operationTimeoutMs, request.signal, async (signal) => {\n if (adapter.exchangeOAuth) return adapter.exchangeOAuth({ ...request, code: request.code!, codeVerifier, signal })\n try {\n const tokens = await exchangeAuthorizationCode({\n ...auth, ...client, code: request.code!, codeVerifier, redirectUri: request.redirectUri,\n tokenUrl: resolveOAuthUrlTemplate(auth.tokenUrl, metadata, request.connectorId, auth.urlTemplateMetadata),\n fetchImpl, signal,\n })\n return {\n credentials: { kind: 'oauth2' as const, accessToken: tokens.accessToken, refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn && tokens.expiresIn > 0 ? now().getTime() + tokens.expiresIn * 1000 : undefined },\n scopes: tokens.scope?.split(/[\\s,]+/).filter(Boolean) ?? [], metadata: tokens.metadata ?? {},\n }\n } catch (cause) {\n throw new IntegrationError(cause instanceof Error ? cause.message : 'OAuth exchange failed.', 'provider_failure')\n }\n }).catch((cause: unknown) => {\n const secrets = [request.code!, codeVerifier ?? '', ...oauthClientCredentialRedactionValues(client.clientId, client.clientSecret,\n client.clientSecret ? createOAuthBasicAuthorizationHeader(client.clientId, client.clientSecret) : undefined)]\n throw new IntegrationError(redactOAuthSensitiveText(cause instanceof Error ? cause.message : 'OAuth exchange failed.', secrets), 'provider_failure')\n })\n if (request.signal?.aborted) throw new IntegrationError('OAuth exchange aborted.', 'provider_failure')\n const credentials = exchanged.credentials\n if (credentials.kind !== 'oauth2' || !credentials.accessToken) throw new IntegrationError('OAuth exchange returned invalid credentials.', 'provider_failure')\n const issued = now().toISOString()\n return commit({\n id: randomConnectionId(), owner: request.owner, providerId, connectorId: request.connectorId,\n status: 'active', grantedScopes: exchanged.scopes.length ? exchanged.scopes : request.requestedScopes ?? [],\n createdAt: issued, updatedAt: issued,\n expiresAt: credentials.expiresAt ? new Date(credentials.expiresAt).toISOString() : undefined,\n metadata: { ...metadata, ...exchanged.metadata },\n }, credentials)\n },\n async testConnection(connection) {\n const adapter = requireAdapter(connection.connectorId)\n let source: ResolvedDataSource\n try { source = await options.resolveDataSource(connection) } catch { return 'credential_persistence_failure' }\n let observed = false\n const credentials = new Proxy(source.credentials, {\n get(target, key, receiver) { observed = true; return Reflect.get(target, key, receiver) },\n has(target, key) { observed = true; return Reflect.has(target, key) },\n ownKeys(target) { observed = true; return Reflect.ownKeys(target) },\n set(target, key, value, receiver) { observed = true; return Reflect.set(target, key, value, receiver) },\n })\n let acceptRotations = true\n let deadlineExpired = false\n let rotationFailed = false\n let persistence = Promise.resolve()\n const persistRotation = (next: ConnectorCredentials) => {\n if (!observed || !acceptRotations || deadlineExpired) return Promise.resolve()\n if (!options.onCredentialsRotated) { rotationFailed = true; return Promise.resolve() }\n persistence = persistence.then(async () => {\n if (deadlineExpired) return\n try { await options.onCredentialsRotated!({ connection, credentials: next }) }\n catch { rotationFailed = true }\n })\n return persistence\n }\n let status: import('./core-types.js').IntegrationConnectionTestStatus\n try {\n const result = await boundedProviderCall(options.operationTimeoutMs, undefined, () =>\n adapter.test({ ...source, credentials }, persistRotation),\n () => { deadlineExpired = true },\n )\n status = result.ok ? 'healthy' : classifyConnectionFailure(result.reason)\n } catch (cause) {\n if (cause instanceof ProviderOperationAborted) return 'network'\n status = classifyConnectionFailure(cause)\n } finally { acceptRotations = false }\n await persistence\n if (!observed) return 'unsupported'\n if (rotationFailed) return 'credential_persistence_failure'\n return status\n },\n async connectApiKey(request) {\n if (!request.apiKey || !options.persistConnection) throw new IntegrationError('API key and encrypted credential commit required.', 'config_missing')\n const adapter = requireAdapter(request.connectorId)\n const auth = adapter.manifest.auth.kind === 'one_of' ? adapter.manifest.auth.options : [adapter.manifest.auth]\n if (!auth.some((entry) => entry.kind === 'api-key')) throw new IntegrationError('Connector does not support API keys.', 'auth_not_supported')\n const metadata = adapter.validateConnectionMetadata ? adapter.validateConnectionMetadata(request.metadata ?? {})\n : !request.metadata || !Object.keys(request.metadata).length ? {} : null\n if (!metadata) throw new IntegrationError('Invalid connection metadata.', 'connection_metadata_invalid')\n const issued = now().toISOString()\n const connection: IntegrationConnection = {\n id: randomConnectionId(), owner: request.owner, providerId, connectorId: request.connectorId,\n status: 'active', grantedScopes: [], createdAt: issued, updatedAt: issued, metadata,\n }\n const credentials: ConnectorCredentials = { kind: 'api-key', apiKey: request.apiKey }\n const probe = createConnectorAdapterProvider({ ...options, onCredentialsRotated: undefined,\n resolveDataSource: () => ({ id: connection.id, projectId: request.owner.id, publishedAgentId: null,\n kind: request.connectorId, label: adapter.manifest.displayName, consistencyModel: adapter.manifest.defaultConsistencyModel,\n scopes: [], metadata, credentials, status: 'active' }),\n })\n const status = await probe.testConnection!(connection)\n if (status !== 'healthy') throw new IntegrationError(`Credential probe failed: ${status}.`, status === 'reconnect_required' ? 'credential_invalid'\n : status === 'rate_limited' ? 'credential_rate_limited' : status === 'unsupported' ? 'credential_probe_unsupported'\n : status === 'credential_persistence_failure' ? status : 'provider_failure')\n return commit(connection, credentials)\n },\n async invokeAction(connection, request) {\n const adapter = requireAdapter(connection.connectorId)\n const capability = adapter.manifest.capabilities.find((candidate) => candidate.name === request.action)\n if (!capability) {\n throw new IntegrationError(`Capability ${request.action} is not defined by ${connection.connectorId}.`, 'action_not_found')\n }\n const source = await options.resolveDataSource(connection)\n let rotationPersistence = Promise.resolve()\n const persistRotation = (credentials: ConnectorCredentials): Promise<void> => {\n if (!options.onCredentialsRotated) return Promise.resolve()\n rotationPersistence = rotationPersistence.then(() =>\n options.onCredentialsRotated!({ connection, credentials }),\n )\n // Some third-party adapters do not await this callback. Attach a\n // rejection observer immediately, then let the original promise keep\n // its rejection for the adapter or the provider's finally block.\n void rotationPersistence.catch(() => {})\n return rotationPersistence\n }\n const invocation: ConnectorInvocation = {\n source,\n capabilityName: request.action,\n args: toRecord(request.input),\n idempotencyKey: request.idempotencyKey ?? `idem_${connection.id}_${request.action}_${now().getTime()}`,\n expectedEtag: typeof request.metadata?.expectedEtag === 'string' ? request.metadata.expectedEtag : undefined,\n callSessionId: typeof request.metadata?.callSessionId === 'string' ? request.metadata.callSessionId : undefined,\n onCredentialsRotated: options.onCredentialsRotated\n ? persistRotation\n : undefined,\n }\n try {\n if (capability.class === 'read') {\n if (!adapter.executeRead) {\n throw new IntegrationError(`Connector ${connection.connectorId} does not implement reads.`, 'action_not_found')\n }\n const result = await adapter.executeRead(invocation)\n return readResultToAction(request, result)\n }\n if (capability.class === 'mutation') {\n if (!adapter.executeMutation) {\n throw new IntegrationError(`Connector ${connection.connectorId} does not implement mutations.`, 'action_not_found')\n }\n const result = await adapter.executeMutation(invocation)\n return mutationResultToAction(request, result)\n }\n throw new IntegrationError(`Capability ${request.action} is not invokable as an action.`, 'action_not_found')\n } finally {\n // A provider can rotate a refresh token before the requested action\n // fails. Persist that full envelope regardless of the action outcome.\n await rotationPersistence\n }\n },\n }\n return provider\n}\n\nexport function adapterManifestsToConnectors(\n adapters: ConnectorAdapter[],\n providerId = 'first-party',\n): IntegrationConnector[] {\n return adapters.map((adapter) => manifestToConnector(providerId, adapter))\n}\n\nexport function createConnectorAdapterCatalogSource(options: {\n id?: string\n providerId?: string\n adapters: ConnectorAdapter[]\n precedence?: number\n}): IntegrationCatalogSource {\n const sourceId = options.id ?? 'first-party'\n return {\n id: sourceId,\n precedence: options.precedence,\n connectors: adapterManifestsToConnectors(options.adapters, options.providerId ?? sourceId),\n }\n}\n\nexport function manifestToConnector(providerId: string, adapter: ConnectorAdapter): IntegrationConnector {\n const manifest = adapter.manifest\n const primaryAuth = primaryManifestAuth(manifest.auth)\n const oauthAuth = oauthManifestAuth(manifest.auth)\n return {\n id: manifest.kind,\n providerId,\n title: manifest.displayName,\n category: mapCategory(manifest.category),\n auth: mapAuth(primaryAuth.kind),\n scopes: primaryAuth.kind === 'oauth2' ? primaryAuth.scopes : [],\n actions: manifest.capabilities\n .filter((capability) => capability.class === 'read' || capability.class === 'mutation')\n .map((capability) => ({\n id: capability.name,\n title: titleFromName(capability.name),\n risk: capability.class === 'read' ? 'read' : capability.externalEffect ? 'destructive' : 'write',\n requiredScopes: capability.requiredScopes ?? [],\n dataClass: inferDataClass(manifest.category),\n ...(capability.consistencyModel ? { consistencyModel: capability.consistencyModel } : {}),\n description: capability.description,\n approvalRequired: capability.class === 'mutation',\n inputSchema: capability.parameters,\n })),\n metadata: {\n source: 'first-party-adapter',\n supportTier: 'firstPartyExecutable',\n executable: !adapter.catalogOnly,\n oauthPkce: oauthAuth\n ? resolveOAuthPkceMode(oauthAuth.pkce, manifest.kind)\n : undefined,\n authOptions: manifest.auth.kind === 'one_of' ? manifest.auth.options.map((auth) => auth.kind) : [manifest.auth.kind],\n preferredAuth: manifest.auth.kind === 'one_of' ? manifest.auth.preferred : manifest.auth.kind,\n oauthConnectionParameters: oauthAuth ? oauthConnectionParameters(oauthAuth) : [],\n },\n }\n}\n\nfunction readResultToAction(request: IntegrationActionRequest, result: CapabilityReadResult): IntegrationActionResult {\n return {\n ok: true,\n action: request.action,\n output: result.data,\n metadata: {\n etag: result.etag,\n fetchedAt: result.fetchedAt,\n },\n }\n}\n\nfunction mutationResultToAction(request: IntegrationActionRequest, result: CapabilityMutationResult): IntegrationActionResult {\n if (result.status === 'committed') {\n return {\n ok: true,\n action: request.action,\n output: result.data,\n metadata: {\n etagAfter: result.etagAfter,\n committedAt: result.committedAt,\n idempotentReplay: result.idempotentReplay,\n },\n }\n }\n if (result.status === 'conflict') {\n return {\n ok: false,\n action: request.action,\n output: {\n conflict: true,\n message: result.message,\n alternatives: result.alternatives,\n currentState: result.currentState,\n },\n }\n }\n return {\n ok: false,\n action: request.action,\n output: {\n rateLimited: true,\n retryAfterMs: result.retryAfterMs,\n message: result.message,\n },\n }\n}\n\nfunction mapAuth(kind: ConnectorAdapter['manifest']['auth']['kind']): IntegrationConnector['auth'] {\n if (kind === 'one_of') return 'custom'\n if (kind === 'oauth2') return 'oauth2'\n if (kind === 'api-key') return 'api_key'\n if (kind === 'none') return 'none'\n return 'custom'\n}\n\nfunction primaryManifestAuth(auth: ConnectorAdapter['manifest']['auth']): Exclude<ConnectorAdapter['manifest']['auth'], { kind: 'one_of' }> {\n if (auth.kind !== 'one_of') return auth\n return auth.options.find((option) => option.kind === auth.preferred) ?? auth.options[0]\n}\n\nfunction oauthManifestAuth(auth: ConnectorAdapter['manifest']['auth']): Extract<Exclude<ConnectorAdapter['manifest']['auth'], { kind: 'one_of' }>, { kind: 'oauth2' }> | undefined {\n if (auth.kind === 'oauth2') return auth\n if (auth.kind !== 'one_of') return undefined\n return auth.options.find((option): option is Extract<typeof option, { kind: 'oauth2' }> => option.kind === 'oauth2')\n}\n\n/** Resolve the manifest value at the last possible point before an OAuth\n * request. The runtime check matters because adapters can enter through JS or\n * an `any` cast without first passing the static manifest validator. */\nfunction resolveOAuthPkceMode(\n value: unknown,\n connectorId: string,\n): 'required' | 'supported' | 'unsupported' {\n if (value === undefined || value === 'required') return 'required'\n if (value === 'supported' || value === 'unsupported') return value\n throw new IntegrationError(\n `Connector ${connectorId} has an invalid OAuth PKCE posture.`,\n 'config_missing',\n )\n}\n\nfunction requirePkceChallenge(value: string | undefined, connectorId: string): string {\n if (!value || !/^[A-Za-z0-9_-]{43}$/.test(value)) {\n throw new IntegrationError(\n `OAuth PKCE S256 challenge missing or invalid for ${connectorId}.`,\n 'config_missing',\n )\n }\n return value\n}\n\nfunction requirePkceVerifier(value: string | undefined, connectorId: string): string {\n if (!value || !/^[A-Za-z0-9._~-]{43,128}$/.test(value)) {\n throw new IntegrationError(\n `OAuth PKCE verifier missing or invalid for ${connectorId}.`,\n 'config_missing',\n )\n }\n return value\n}\n\n/** Resolve provider-owned tenant labels embedded in OAuth URLs.\n *\n * Shopify and Gorgias put the merchant name in the hostname. Only one DNS\n * label is accepted for each placeholder, so connection metadata cannot turn\n * a provider URL into an arbitrary credential destination.\n */\nfunction resolveOAuthUrlTemplate(\n template: string,\n metadata: Record<string, unknown> | undefined,\n connectorId: string,\n metadataSpecs?: Readonly<Record<string, OAuth2UrlTemplateMetadataSpec>>,\n): string {\n const placeholders = [...template.matchAll(/\\{([A-Za-z][A-Za-z0-9_]*)\\}/g)]\n let resolved = template\n for (const match of placeholders) {\n const key = match[1]\n const raw = metadata?.[key]\n const metadataSpec = metadataSpecs?.[key]\n if (metadataSpec?.kind === 'base-url') {\n if (typeof raw !== 'string') {\n throw new IntegrationError(\n `OAuth URL for ${connectorId} requires metadata.${key} as a provider base URL.`,\n raw === undefined ? 'connection_parameters_missing' : 'connection_parameters_invalid',\n )\n }\n resolved = resolved.replaceAll(\n match[0],\n resolveOAuthMetadataBaseUrl(raw, metadataSpec, connectorId, key),\n )\n continue\n }\n if (metadataSpec?.kind === 'path-segment') {\n if (!isOAuthPathSegmentPlaceholder(template, match.index ?? -1, match[0])) {\n throw new IntegrationError(\n `OAuth URL for ${connectorId} declares metadata.${key} outside a complete path segment.`,\n 'config_missing',\n )\n }\n if (typeof raw !== 'string' || !isOAuthPathSegment(raw.trim())) {\n throw new IntegrationError(\n `OAuth URL for ${connectorId} requires metadata.${key} as a valid path segment.`,\n raw === undefined ? 'connection_parameters_missing' : 'connection_parameters_invalid',\n )\n }\n resolved = resolved.replaceAll(match[0], encodeURIComponent(raw.trim()))\n continue\n }\n if (typeof raw !== 'string' || !isDnsLabel(raw.trim())) {\n throw new IntegrationError(\n `OAuth URL for ${connectorId} requires metadata.${key} as a valid tenant label.`,\n raw === undefined ? 'connection_parameters_missing' : 'connection_parameters_invalid',\n )\n }\n resolved = resolved.replaceAll(match[0], raw.trim().toLowerCase())\n }\n\n let url: URL\n try {\n url = new URL(resolved)\n } catch {\n throw new IntegrationError(\n `OAuth URL for ${connectorId} is invalid.`,\n 'config_missing',\n )\n }\n if (url.protocol !== 'https:' || url.username || url.password || !isPublicDnsHostname(url.hostname)) {\n throw new IntegrationError(\n `OAuth URL for ${connectorId} must be HTTPS without embedded credentials.`,\n 'config_missing',\n )\n }\n return url.toString()\n}\n\nfunction isOAuthPathSegment(value: string): boolean {\n return (\n value !== '.' &&\n value !== '..' &&\n /^[A-Za-z0-9._~-]{1,128}$/.test(value)\n )\n}\n\nfunction isOAuthPathSegmentPlaceholder(\n template: string,\n index: number,\n placeholder: string,\n): boolean {\n if (index < 0) return false\n const schemeIndex = template.indexOf('://')\n const rootEnd = schemeIndex >= 0\n ? schemeIndex + 3\n : template.startsWith('{')\n ? template.indexOf('}') + 1\n : 0\n const pathStart = template.indexOf('/', rootEnd)\n const end = index + placeholder.length\n const queryStart = template.search(/[?#]/)\n return (\n pathStart >= 0 &&\n index >= pathStart &&\n (queryStart < 0 || index < queryStart) &&\n template[index - 1] === '/' &&\n (end === template.length || template[end] === '/' || template[end] === '?' || template[end] === '#')\n )\n}\n\nfunction resolveOAuthMetadataBaseUrl(\n value: string,\n spec: Extract<OAuth2UrlTemplateMetadataSpec, { kind: 'base-url' }>,\n connectorId: string,\n metadataKey: string,\n): string {\n let url: URL\n try {\n url = new URL(value.trim())\n } catch {\n throw invalidOAuthMetadataBaseUrl(connectorId, metadataKey)\n }\n if (\n url.protocol !== 'https:' ||\n url.username ||\n url.password ||\n url.pathname !== '/' ||\n url.search ||\n url.hash\n ) {\n throw invalidOAuthMetadataBaseUrl(connectorId, metadataKey)\n }\n const exactAllowed = spec.allowedBaseUrls?.some((candidate) => sameOrigin(candidate, url)) ?? false\n const suffixAllowed = spec.allowedBaseUrlSuffixes?.some((suffix) =>\n !url.port &&\n suffix.startsWith('.') &&\n url.hostname.toLowerCase().endsWith(suffix.toLowerCase())\n ) ?? false\n const hasExplicitAllowlist = Boolean(\n spec.allowedBaseUrls?.length || spec.allowedBaseUrlSuffixes?.length,\n )\n if (hasExplicitAllowlist && !exactAllowed && !suffixAllowed) {\n throw invalidOAuthMetadataBaseUrl(connectorId, metadataKey)\n }\n if (spec.requirePublicHttps && !isPublicDnsHostname(url.hostname)) {\n throw invalidOAuthMetadataBaseUrl(connectorId, metadataKey)\n }\n return url.origin\n}\n\nfunction invalidOAuthMetadataBaseUrl(connectorId: string, metadataKey: string): IntegrationError {\n return new IntegrationError(\n `OAuth URL for ${connectorId} requires metadata.${metadataKey} as an allowed HTTPS provider root.`,\n 'connection_parameters_invalid',\n )\n}\n\nfunction sameOrigin(candidate: string, actual: URL): boolean {\n try {\n const allowed = new URL(candidate)\n return (\n allowed.protocol === 'https:' &&\n !allowed.username &&\n !allowed.password &&\n allowed.pathname === '/' &&\n !allowed.search &&\n !allowed.hash &&\n allowed.origin === actual.origin\n )\n } catch {\n return false\n }\n}\n\nfunction isPublicDnsHostname(hostname: string): boolean {\n const normalized = hostname.toLowerCase().replace(/^\\[|\\]$/g, '')\n if (\n normalized === 'localhost' ||\n normalized.endsWith('.localhost') ||\n normalized.endsWith('.local') ||\n normalized.endsWith('.internal') ||\n normalized.endsWith('.home.arpa')\n ) {\n return false\n }\n // OAuth redirects to self-hosted instances require a DNS name. Reject\n // literal IP addresses because fetch cannot pin DNS against rebinding.\n if (/^[0-9.]+$/.test(normalized) || normalized.includes(':')) return false\n return normalized.includes('.') && normalized.split('.').every(isDnsLabel)\n}\n\nfunction isDnsLabel(value: string): boolean {\n return value.length > 0 && value.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(value)\n}\n\nfunction mapCategory(category: ConnectorAdapter['manifest']['category']): IntegrationConnector['category'] {\n if (category === 'comms') return 'chat'\n if (category === 'spreadsheet') return 'database'\n if (category === 'doc') return 'docs'\n if (category === 'commerce') return 'workflow'\n // The manifest taxonomy is richer than the hub-facade taxonomy. Sales/market\n // intelligence and HR/payroll connectors collapse to the nearest hub bucket:\n // contact/company intelligence reads like CRM; the rest have no closer fit.\n if (category === 'sales-intelligence') return 'crm'\n if (category === 'market-intelligence' || category === 'hr') return 'other'\n return category === 'other' ? 'other' : category\n}\n\nfunction inferDataClass(category: ConnectorAdapter['manifest']['category']): 'public' | 'internal' | 'private' | 'sensitive' {\n if (category === 'commerce') return 'sensitive'\n if (category === 'webhook') return 'internal'\n return 'private'\n}\n\nfunction titleFromName(name: string): string {\n return name\n .split(/[._-]/g)\n .filter(Boolean)\n .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))\n .join(' ')\n}\n\nfunction toRecord(input: unknown): Record<string, unknown> {\n if (input && typeof input === 'object' && !Array.isArray(input)) return input as Record<string, unknown>\n return {}\n}\n\nfunction randomState(): string {\n // 192 bits of entropy — comfortable CSRF margin and stays URL-safe.\n const bytes = new Uint8Array(24)\n globalThis.crypto.getRandomValues(bytes)\n return base64UrlEncode(bytes)\n}\n\nfunction randomConnectionId(): string {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return `conn_${globalThis.crypto.randomUUID().replace(/-/g, '')}`\n }\n const bytes = new Uint8Array(16)\n globalThis.crypto.getRandomValues(bytes)\n return `conn_${base64UrlEncode(bytes)}`\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let bin = ''\n for (const b of bytes) bin += String.fromCharCode(b)\n // btoa is defined in browsers, workers, and Node ≥ 16.\n const b64 = typeof btoa === 'function' ? btoa(bin) : Buffer.from(bin, 'binary').toString('base64')\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nclass ProviderOperationAborted extends Error {}\n\n/** The losing promise remains observed; only an on-time result reaches a credential commit. */\nasync function boundedProviderCall<T>(timeoutMs: number | undefined, parent: AbortSignal | undefined, start: (signal: AbortSignal) => Promise<T>, onAbort?: () => void): Promise<T> {\n const budget = timeoutMs ?? 10_000\n if (!Number.isFinite(budget) || budget <= 0) throw new IntegrationError('Invalid provider timeout.', 'config_missing')\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n let rejectAbort: (reason: Error) => void = () => {}\n const abort = () => { onAbort?.(); controller.abort(); rejectAbort(new ProviderOperationAborted('Provider operation aborted or timed out.')) }\n try {\n return await Promise.race([\n new Promise<never>((_, reject) => {\n rejectAbort = reject\n timer = setTimeout(abort, budget)\n parent?.addEventListener('abort', abort, { once: true })\n if (parent?.aborted) abort()\n }),\n Promise.resolve().then(() => {\n if (controller.signal.aborted) throw new Error('Provider operation aborted.')\n return start(controller.signal)\n }),\n ])\n } finally {\n clearTimeout(timer)\n parent?.removeEventListener('abort', abort)\n controller.abort()\n }\n}\n\nfunction classifyConnectionFailure(raw: unknown): import('./core-types.js').IntegrationConnectionTestStatus {\n if (raw instanceof ProviderRateLimited) return 'rate_limited'\n if (raw instanceof CredentialsExpired) return 'reconnect_required'\n if (raw instanceof ProviderConfigError) return 'provider_failure'\n const message = raw instanceof Error ? raw.message : typeof raw === 'string' ? raw : ''\n if (/\\b429\\b|rate.?limit|too many requests|\\bthrottl|(?:quota|daily limit).*(?:exceed|exhaust)/i.test(message)) return 'rate_limited'\n if (/rejected credentials|credentials?.*(?:expired|invalid|revoked)|(?:access|refresh|oauth|bearer)?\\s*token.*(?:expired|invalid|revoked)|invalid[_\\s-]?grant|\\bunauthori[sz]ed\\b|authentication failed|\\bhttp\\s*401\\b|\\(401\\)/i.test(message)) return 'reconnect_required'\n if (/network|fetch failed|\\bECONN[A-Z]+\\b|\\bENOTFOUND\\b|\\bEAI_AGAIN\\b|\\bETIMEDOUT\\b|socket hang up|timed?\\s*out|abort(?:ed)?/i.test(message)) return 'network'\n return 'provider_failure'\n}\n\nfunction oauthConnectionParameters(auth: NonNullable<ReturnType<typeof oauthManifestAuth>>) {\n const placeholders = new Set([...`${auth.authorizationUrl ?? ''} ${auth.tokenUrl}`.matchAll(/\\{([A-Za-z][A-Za-z0-9_]*)\\}/g)].map((match) => match[1]))\n return [...placeholders].map((key) => ({ key, required: true, kind: auth.urlTemplateMetadata?.[key]?.kind ?? 'dns-label',\n ...auth.urlTemplateMetadata?.[key] }))\n}\n\nfunction resolveOAuthConnectionMetadata(auth: NonNullable<ReturnType<typeof oauthManifestAuth>>, raw: Record<string, unknown> | undefined, id: string): Record<string, unknown> {\n const metadata = { ...raw }\n for (const parameter of oauthConnectionParameters(auth)) {\n const spec = auth.urlTemplateMetadata?.[parameter.key]\n if (parameter.kind !== 'dns-label') continue\n let value = metadata[parameter.key]\n if (typeof value === 'string' && /^https:\\/\\//i.test(value.trim())) {\n try {\n const url = new URL(value.trim())\n const template = spec?.kind === 'dns-label' ? spec.connectionMetadata?.template : undefined\n const expected = template ? new URL(template.replaceAll(`{${parameter.key}}`, 'oauth-tenant')) : undefined\n const suffix = expected?.hostname.startsWith('oauth-tenant.') ? expected.hostname.slice('oauth-tenant'.length) : undefined\n if (!suffix || !url.hostname.endsWith(suffix) || url.username || url.password || url.port\n || url.pathname !== '/' || url.search || url.hash) throw new Error('Invalid tenant origin')\n value = url.hostname.slice(0, -suffix.length)\n } catch { throw new IntegrationError(`Invalid tenant origin ${parameter.key}.`, 'connection_parameters_invalid') }\n }\n if (typeof value !== 'string' || !isDnsLabel(value.trim())) throw new IntegrationError(`Invalid tenant label ${parameter.key}.`, value === undefined ? 'connection_parameters_missing' : 'connection_parameters_invalid')\n metadata[parameter.key] = value.trim().toLowerCase()\n if (spec?.kind === 'dns-label' && spec.connectionMetadata) {\n metadata[spec.connectionMetadata.key] = resolveOAuthUrlTemplate(spec.connectionMetadata.template, metadata, id, auth.urlTemplateMetadata)\n }\n }\n return metadata\n}\n","import { createConnectorAdapterProvider, type ConnectorAdapterProviderOptions } from './adapter-provider.js'\nimport type {\n ConnectorAdapter,\n ConnectorCredentials,\n ResolvedDataSource,\n} from './connectors/types.js'\nimport type {\n IntegrationConnection,\n IntegrationConnectionStore,\n IntegrationCredentialsRotatedEvent,\n IntegrationOAuthState,\n IntegrationOAuthStateOutcome,\n IntegrationOAuthStateStore,\n IntegrationProvider,\n IntegrationSecretStore,\n SecretRef,\n} from './core-types.js'\n\nexport type {\n IntegrationOAuthState,\n IntegrationOAuthStateOutcome,\n IntegrationOAuthStateStore,\n IntegrationSecretStore,\n}\n\nexport interface ConnectionCredentialResolverOptions {\n secrets: IntegrationSecretStore\n connections?: IntegrationConnectionStore\n adapters?: ConnectorAdapter[]\n now?: () => Date\n markConnectionError?: (connection: IntegrationConnection, error: Error) => Promise<void> | void\n}\n\ninterface CredentialRefreshFlight {\n promise: Promise<ConnectorCredentials>\n cancelled: boolean\n settled: boolean\n waiters: number\n}\n\ninterface CredentialPersistenceLease {\n cancelled: boolean\n}\n\nclass CredentialRefreshRevokedError extends Error {\n constructor() {\n super('Connection was revoked during credential refresh.')\n this.name = 'CredentialRefreshRevokedError'\n }\n}\n\nconst credentialRefreshes = new WeakMap<\n IntegrationSecretStore,\n Map<string, CredentialRefreshFlight>\n>()\nconst credentialPersistences = new WeakMap<\n IntegrationSecretStore,\n Map<string, Set<CredentialPersistenceLease>>\n>()\nconst credentialRevocations = new WeakMap<IntegrationSecretStore, Map<string, number>>()\n\nexport class InMemoryIntegrationSecretStore implements IntegrationSecretStore {\n private readonly secrets = new Map<string, ConnectorCredentials>()\n\n get(ref: SecretRef): ConnectorCredentials | undefined {\n return this.secrets.get(secretKey(ref))\n }\n\n put(ref: SecretRef, credentials: ConnectorCredentials): void {\n this.secrets.set(secretKey(ref), credentials)\n }\n\n delete(ref: SecretRef): void {\n this.secrets.delete(secretKey(ref))\n }\n}\n\n/** Test/dev double for {@link IntegrationOAuthStateStore}. Production hubs\n * inject a durable implementation; this one keeps records in a Map and\n * enforces the single-use + expiry contract. */\nexport class InMemoryIntegrationOAuthStateStore implements IntegrationOAuthStateStore {\n private readonly states = new Map<string, IntegrationOAuthState>()\n\n put(state: IntegrationOAuthState): void {\n this.states.set(state.state, state)\n }\n\n consume(state: string): IntegrationOAuthStateOutcome {\n const record = this.states.get(state)\n this.states.delete(state)\n if (!record) return { ok: false, reason: 'unknown' }\n if (record.expiresAt <= Date.now()) return { ok: false, reason: 'expired' }\n return { ok: true, state: record }\n }\n\n sweep(now: number): void {\n for (const [key, record] of this.states) {\n if (record.expiresAt <= now) this.states.delete(key)\n }\n }\n}\n\nexport function createConnectionCredentialResolver(options: ConnectionCredentialResolverOptions) {\n const now = options.now ?? (() => new Date())\n return async function resolveDataSource(connection: IntegrationConnection): Promise<ResolvedDataSource> {\n const credentials = await resolveConnectionCredentials(connection, {\n secrets: options.secrets,\n connections: options.connections,\n adapters: options.adapters,\n now,\n markConnectionError: options.markConnectionError,\n })\n return {\n id: connection.id,\n projectId: String(connection.metadata?.projectId ?? connection.owner.id),\n publishedAgentId: typeof connection.metadata?.publishedAgentId === 'string' ? connection.metadata.publishedAgentId : null,\n kind: connection.connectorId,\n label: connection.account?.displayName ?? connection.account?.email ?? connection.connectorId,\n consistencyModel: typeof connection.metadata?.consistencyModel === 'string' ? connection.metadata.consistencyModel as never : 'authoritative',\n scopes: connection.grantedScopes,\n metadata: connection.metadata ?? {},\n credentials,\n status: connection.status === 'active' ? 'active' : connection.status === 'revoked' ? 'revoked' : 'error',\n }\n }\n}\n\nexport async function resolveConnectionCredentials(input: IntegrationConnection, options: ConnectionCredentialResolverOptions): Promise<ConnectorCredentials> {\n if (input.status !== 'active') throw new Error(`Connection ${input.id} is ${input.status}.`)\n if (!input.secretRef) return { kind: 'none' }\n const now = options.now ?? (() => new Date())\n const current = await options.secrets.get(input.secretRef)\n if (!current) throw new Error(`Secret ${input.secretRef.provider}/${input.secretRef.id} not found.`)\n if (!isExpiredOauth(current, now)) return current\n\n const adapter = options.adapters?.find((candidate) => candidate.manifest.kind === input.connectorId)\n if (!adapter?.refreshToken) return current\n let refresh: CredentialRefreshFlight | undefined\n try {\n await assertCredentialRefreshActive(input, options, now)\n refresh = acquireCredentialRefresh({\n connectorId: input.connectorId,\n secretRef: input.secretRef,\n secrets: options.secrets,\n now,\n refreshToken: adapter.refreshToken.bind(adapter),\n })\n const refreshed = await refresh.promise\n await assertCredentialRefreshActive(input, options, now, refresh)\n if (options.connections) {\n await options.connections.put({\n ...input,\n status: 'active',\n updatedAt: now().toISOString(),\n expiresAt: refreshed.kind === 'oauth2' && refreshed.expiresAt ? new Date(refreshed.expiresAt).toISOString() : input.expiresAt,\n })\n await assertCredentialRefreshActive(input, options, now, refresh)\n }\n return refreshed\n } catch (error) {\n const err = error instanceof Error ? error : new Error('Credential refresh failed.')\n if (err instanceof CredentialRefreshRevokedError) throw err\n await options.markConnectionError?.(input, err)\n if (options.connections) {\n await options.connections.put({\n ...input,\n status: 'expired',\n updatedAt: now().toISOString(),\n })\n }\n throw err\n } finally {\n if (refresh) {\n releaseCredentialRefresh(\n options.secrets,\n input.connectorId,\n input.secretRef,\n refresh,\n )\n }\n }\n}\n\nfunction acquireCredentialRefresh(input: {\n connectorId: string\n secretRef: SecretRef\n secrets: IntegrationSecretStore\n now: () => Date\n refreshToken: (credentials: ConnectorCredentials) => Promise<ConnectorCredentials>\n}): CredentialRefreshFlight {\n let refreshes = credentialRefreshes.get(input.secrets)\n if (!refreshes) {\n refreshes = new Map()\n credentialRefreshes.set(input.secrets, refreshes)\n }\n const key = credentialRefreshKey(input.connectorId, input.secretRef)\n if (credentialRevocations.get(input.secrets)?.has(key)) {\n throw new CredentialRefreshRevokedError()\n }\n const existing = refreshes.get(key)\n if (existing) {\n existing.waiters += 1\n return existing\n }\n\n let flight: CredentialRefreshFlight\n const promise = Promise.resolve().then(async () => {\n // A prior refresh can settle between the caller's first read and this\n // flight. Re-read before redeeming a provider's rotating refresh token.\n const latest = await input.secrets.get(input.secretRef)\n if (!latest) {\n throw new Error(\n `Secret ${input.secretRef.provider}/${input.secretRef.id} not found.`,\n )\n }\n if (!isExpiredOauth(latest, input.now)) return latest\n const refreshed = await input.refreshToken(latest)\n if (flight.cancelled) throw new CredentialRefreshRevokedError()\n await input.secrets.put(input.secretRef, refreshed)\n if (flight.cancelled) {\n await input.secrets.delete?.(input.secretRef)\n throw new CredentialRefreshRevokedError()\n }\n return refreshed\n })\n flight = {\n promise,\n cancelled: false,\n settled: false,\n waiters: 1,\n }\n refreshes.set(key, flight)\n\n const settle = () => {\n flight.settled = true\n clearCredentialRefresh(input.secrets, key, flight)\n }\n // Observe rejection immediately. Every caller still receives the original\n // rejected promise and applies its connection-specific error transition.\n void promise.then(settle, settle)\n return flight\n}\n\nfunction releaseCredentialRefresh(\n secrets: IntegrationSecretStore,\n connectorId: string,\n secretRef: SecretRef,\n flight: CredentialRefreshFlight,\n): void {\n flight.waiters -= 1\n clearCredentialRefresh(\n secrets,\n credentialRefreshKey(connectorId, secretRef),\n flight,\n )\n}\n\nfunction clearCredentialRefresh(\n secrets: IntegrationSecretStore,\n key: string,\n flight: CredentialRefreshFlight,\n): void {\n if (!flight.settled || flight.waiters !== 0) return\n const refreshes = credentialRefreshes.get(secrets)\n if (refreshes?.get(key) !== flight) return\n refreshes.delete(key)\n if (refreshes.size === 0) credentialRefreshes.delete(secrets)\n}\n\nasync function assertCredentialRefreshActive(\n input: IntegrationConnection,\n options: ConnectionCredentialResolverOptions,\n now: () => Date,\n operation?: CredentialPersistenceLease,\n): Promise<void> {\n const key = input.secretRef\n ? credentialRefreshKey(input.connectorId, input.secretRef)\n : undefined\n let revoked = operation?.cancelled === true\n || (key !== undefined\n && credentialRevocations.get(options.secrets)?.has(key) === true)\n let stored: IntegrationConnection | undefined\n if (options.connections) {\n stored = await options.connections.get(input.id)\n revoked ||= stored?.status === 'revoked'\n }\n if (!revoked && input.secretRef) {\n revoked = await options.secrets.get(input.secretRef) === undefined\n }\n if (!revoked) return\n\n if (operation) operation.cancelled = true\n if (input.secretRef) await options.secrets.delete?.(input.secretRef)\n if (options.connections && stored?.status !== 'revoked') {\n await options.connections.put({\n ...(stored ?? input),\n status: 'revoked',\n updatedAt: now().toISOString(),\n })\n }\n throw new CredentialRefreshRevokedError()\n}\n\nexport type CredentialBackedAdapterProviderOptions =\n Omit<ConnectorAdapterProviderOptions, 'resolveDataSource' | 'onCredentialsRotated'>\n & ConnectionCredentialResolverOptions\n & {\n /** Fired after the provider re-persists rotated credentials to the\n * secret + connection stores. Receives the hub-shaped event including\n * the resolved secretRef so the host can drive external re-encryption\n * or telemetry. */\n onCredentialsRotated?: (event: IntegrationCredentialsRotatedEvent) => Promise<void> | void\n }\n\nexport function createCredentialBackedAdapterProvider(options: CredentialBackedAdapterProviderOptions): IntegrationProvider {\n const now = options.now ?? (() => new Date())\n return createConnectorAdapterProvider({\n ...options,\n resolveDataSource: createConnectionCredentialResolver(options),\n onCredentialsRotated: async ({ connection, credentials }) => {\n const persistence = connection.secretRef\n ? acquireCredentialPersistence(\n options.secrets,\n connection.connectorId,\n connection.secretRef,\n )\n : undefined\n try {\n await assertCredentialRefreshActive(connection, options, now, persistence)\n if (connection.secretRef) {\n await options.secrets.put(connection.secretRef, credentials)\n }\n await assertCredentialRefreshActive(connection, options, now, persistence)\n if (options.connections) {\n await options.connections.put({\n ...connection,\n status: 'active',\n updatedAt: now().toISOString(),\n expiresAt: credentials.kind === 'oauth2' && credentials.expiresAt\n ? new Date(credentials.expiresAt).toISOString()\n : connection.expiresAt,\n })\n await assertCredentialRefreshActive(connection, options, now, persistence)\n }\n await options.onCredentialsRotated?.({ connection, secretRef: connection.secretRef, credentials })\n await assertCredentialRefreshActive(connection, options, now, persistence)\n } finally {\n if (persistence && connection.secretRef) {\n releaseCredentialPersistence(\n options.secrets,\n connection.connectorId,\n connection.secretRef,\n persistence,\n )\n }\n }\n },\n })\n}\n\nfunction acquireCredentialPersistence(\n secrets: IntegrationSecretStore,\n connectorId: string,\n secretRef: SecretRef,\n): CredentialPersistenceLease {\n let persistences = credentialPersistences.get(secrets)\n if (!persistences) {\n persistences = new Map()\n credentialPersistences.set(secrets, persistences)\n }\n const key = credentialRefreshKey(connectorId, secretRef)\n let leases = persistences.get(key)\n if (!leases) {\n leases = new Set()\n persistences.set(key, leases)\n }\n const lease = {\n cancelled: credentialRevocations.get(secrets)?.has(key) === true,\n }\n leases.add(lease)\n return lease\n}\n\nfunction releaseCredentialPersistence(\n secrets: IntegrationSecretStore,\n connectorId: string,\n secretRef: SecretRef,\n lease: CredentialPersistenceLease,\n): void {\n const persistences = credentialPersistences.get(secrets)\n if (!persistences) return\n const key = credentialRefreshKey(connectorId, secretRef)\n const leases = persistences.get(key)\n leases?.delete(lease)\n if (leases?.size === 0) persistences.delete(key)\n if (persistences.size === 0) credentialPersistences.delete(secrets)\n}\n\nexport async function revokeConnection(input: {\n connection: IntegrationConnection\n connections?: IntegrationConnectionStore\n secrets?: IntegrationSecretStore\n now?: () => Date\n}): Promise<IntegrationConnection> {\n const finishRevocation = input.connection.secretRef && input.secrets\n ? beginCredentialRevocation(\n input.secrets,\n input.connection.connectorId,\n input.connection.secretRef,\n )\n : undefined\n try {\n if (input.connection.secretRef) await input.secrets?.delete?.(input.connection.secretRef)\n const revoked: IntegrationConnection = {\n ...input.connection,\n status: 'revoked',\n updatedAt: (input.now?.() ?? new Date()).toISOString(),\n }\n await input.connections?.put(revoked)\n return revoked\n } finally {\n finishRevocation?.()\n }\n}\n\nfunction beginCredentialRevocation(\n secrets: IntegrationSecretStore,\n connectorId: string,\n secretRef: SecretRef,\n): () => void {\n const key = credentialRefreshKey(connectorId, secretRef)\n let revocations = credentialRevocations.get(secrets)\n if (!revocations) {\n revocations = new Map()\n credentialRevocations.set(secrets, revocations)\n }\n revocations.set(key, (revocations.get(key) ?? 0) + 1)\n const flight = credentialRefreshes.get(secrets)?.get(key)\n if (flight) flight.cancelled = true\n for (const persistence of credentialPersistences.get(secrets)?.get(key) ?? []) {\n persistence.cancelled = true\n }\n\n return () => {\n const remaining = (revocations?.get(key) ?? 1) - 1\n if (remaining > 0) revocations?.set(key, remaining)\n else revocations?.delete(key)\n if (revocations?.size === 0) credentialRevocations.delete(secrets)\n }\n}\n\nfunction isExpiredOauth(credentials: ConnectorCredentials, now: () => Date): boolean {\n return credentials.kind === 'oauth2'\n && typeof credentials.expiresAt === 'number'\n && credentials.expiresAt <= now().getTime()\n && Boolean(credentials.refreshToken)\n}\n\nfunction secretKey(ref: SecretRef): string {\n return `${ref.provider}:${ref.id}`\n}\n\nfunction credentialRefreshKey(connectorId: string, ref: SecretRef): string {\n return JSON.stringify([connectorId, ref.provider, ref.id])\n}\n","import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'\nimport {\n composeIntegrationRegistry,\n type ComposeIntegrationRegistryOptions,\n type IntegrationRegistry,\n} from './registry-core.js'\nimport {\n InMemoryIntegrationOAuthStateStore,\n InMemoryIntegrationSecretStore,\n type IntegrationOAuthState,\n} from './credentials.js'\nimport { IntegrationError } from './core-error.js'\nimport type {\n CompleteAuthRequest,\n ConnectApiKeyRequest,\n IntegrationActionGuard,\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationActor,\n IntegrationCapability,\n IntegrationConnection,\n IntegrationConnectionStore,\n IntegrationConnector,\n IntegrationHubOptions,\n IntegrationPolicyEngine,\n IntegrationProvider,\n IntegrationTriggerEvent,\n IntegrationTriggerSubscription,\n InvokeWithCapabilityRequest,\n IssueCapabilityRequest,\n IssuedIntegrationCapability,\n StartAuthRequest,\n StartAuthResult,\n} from './core-types.js'\n\nexport class IntegrationHub {\n private readonly providers = new Map<string, IntegrationProvider>()\n private readonly store: IntegrationConnectionStore\n private readonly capabilitySecret: string\n private readonly guard: IntegrationActionGuard | undefined\n private readonly policy: IntegrationPolicyEngine | undefined\n /** Host-injected (or in-memory default) secret store. The hub re-persists\n * rotated credentials here when a connection carries a secretRef. */\n readonly secretStore: IntegrationHubOptions['secretStore']\n private readonly oauthStateStore: NonNullable<IntegrationHubOptions['oauthStateStore']>\n private readonly oauthStateTtlMs: number\n private readonly credentialsRotated: IntegrationHubOptions['credentialsRotated']\n private readonly now: () => Date\n\n constructor(options: IntegrationHubOptions) {\n if (!options.capabilitySecret) {\n throw new IntegrationError('capabilitySecret is required.', 'capability_invalid')\n }\n for (const provider of options.providers) this.providers.set(provider.id, provider)\n this.store = options.store\n this.capabilitySecret = options.capabilitySecret\n this.guard = options.guard\n this.policy = options.policy\n this.secretStore = options.secretStore ?? new InMemoryIntegrationSecretStore()\n this.oauthStateStore = options.oauthStateStore ?? new InMemoryIntegrationOAuthStateStore()\n this.oauthStateTtlMs = options.oauthStateTtlMs ?? 10 * 60 * 1000\n this.credentialsRotated = options.credentialsRotated\n this.now = options.now ?? (() => new Date())\n }\n\n async listConnectors(): Promise<IntegrationConnector[]> {\n const catalogs = await Promise.all([...this.providers.values()].map((provider) => provider.listConnectors()))\n return catalogs.flat()\n }\n\n async listRegistry(options: ComposeIntegrationRegistryOptions = {}): Promise<IntegrationRegistry> {\n const sources = await Promise.all([...this.providers.values()].map(async (provider) => ({\n id: provider.id,\n connectors: await provider.listConnectors(),\n })))\n return composeIntegrationRegistry(sources, options)\n }\n\n async startAuth(providerId: string, request: StartAuthRequest): Promise<StartAuthResult> {\n const provider = this.requireProvider(providerId)\n if (!provider.startAuth) throw new IntegrationError(`Provider ${providerId} does not support auth start.`, 'auth_not_supported')\n const connector = await this.requireConnector(provider, request.connectorId)\n const pkce = connectorOAuthPkceMode(connector)\n const pkcePair = pkce === 'unsupported' ? undefined : createPkcePair()\n const result = await provider.startAuth({\n ...request,\n codeChallenge: pkcePair?.challenge,\n })\n const record: IntegrationOAuthState = {\n state: result.state,\n providerId,\n connectorId: request.connectorId,\n owner: request.owner,\n requestedScopes: result.requestedScopes ?? request.requestedScopes,\n redirectUri: request.redirectUri,\n codeVerifier: pkcePair?.verifier,\n expiresAt: this.now().getTime() + this.oauthStateTtlMs,\n metadata: result.metadata ?? request.metadata,\n }\n await this.oauthStateStore.put(record)\n return result\n }\n\n async completeAuth(providerId: string, request: CompleteAuthRequest): Promise<IntegrationConnection> {\n const provider = this.requireProvider(providerId)\n if (!provider.completeAuth) throw new IntegrationError(`Provider ${providerId} does not support auth completion.`, 'auth_not_supported')\n const outcome = await this.oauthStateStore.consume(request.state)\n if (!outcome.ok) {\n throw new IntegrationError(`Integration OAuth state ${outcome.reason}: possible CSRF, replay, or stale flow.`, 'capability_invalid')\n }\n if (outcome.state.providerId !== providerId || outcome.state.connectorId !== request.connectorId) {\n throw new IntegrationError('Integration OAuth state does not match completion request.', 'capability_invalid')\n }\n if (outcome.state.redirectUri !== request.redirectUri) {\n throw new IntegrationError('Integration OAuth redirect URI does not match the start request.', 'capability_invalid')\n }\n const pinnedMetadata = request.metadata || outcome.state.metadata\n ? { ...request.metadata, ...outcome.state.metadata }\n : undefined\n const connection = await provider.completeAuth({\n ...request,\n connectorId: outcome.state.connectorId,\n owner: outcome.state.owner,\n state: outcome.state.state,\n redirectUri: outcome.state.redirectUri,\n codeVerifier: outcome.state.codeVerifier,\n requestedScopes: outcome.state.requestedScopes,\n metadata: pinnedMetadata,\n })\n await this.store.put(connection)\n return connection\n }\n\n async connectApiKey(providerId: string, request: ConnectApiKeyRequest): Promise<IntegrationConnection> {\n const provider = this.requireProvider(providerId)\n if (!provider.connectApiKey) throw new IntegrationError('Provider does not support API-key connections.', 'auth_not_supported')\n const connection = await provider.connectApiKey(request)\n await this.store.put(connection)\n return connection\n }\n\n async testConnection(connectionId: string) {\n const connection = await this.requireConnection(connectionId)\n this.assertConnectionActive(connection)\n const provider = this.requireProvider(connection.providerId)\n return provider.testConnection ? provider.testConnection(connection) : 'unsupported' as const\n }\n\n async upsertConnection(connection: IntegrationConnection): Promise<IntegrationConnection> {\n await this.store.put(connection)\n return connection\n }\n\n async listConnections(owner: IntegrationActor): Promise<IntegrationConnection[]> {\n return this.store.listByOwner(owner)\n }\n\n async getConnection(connectionId: string): Promise<IntegrationConnection | undefined> {\n return this.store.get(connectionId)\n }\n\n async issueCapability(request: IssueCapabilityRequest): Promise<IssuedIntegrationCapability> {\n const connection = await this.requireConnection(request.connectionId)\n this.assertConnectionActive(connection)\n assertScopes(connection, request.scopes)\n const now = this.now()\n const capability: IntegrationCapability = {\n id: `cap_${randomUUID()}`,\n subject: request.subject,\n connectionId: request.connectionId,\n scopes: unique(request.scopes),\n allowedActions: unique(request.allowedActions),\n issuedAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + request.ttlMs).toISOString(),\n metadata: request.metadata,\n }\n return { capability, token: signCapability(capability, this.capabilitySecret) }\n }\n\n verifyCapability(token: string): IntegrationCapability {\n const capability = verifyCapabilityToken(token, this.capabilitySecret)\n if (Date.parse(capability.expiresAt) <= this.now().getTime()) {\n throw new IntegrationError('Integration capability expired.', 'capability_expired')\n }\n return capability\n }\n\n async invokeWithCapability(token: string, request: InvokeWithCapabilityRequest): Promise<IntegrationActionResult> {\n const capability = this.verifyCapability(token)\n if (!capability.allowedActions.includes(request.action)) {\n throw new IntegrationError(`Capability does not allow action ${request.action}.`, 'action_denied')\n }\n const connection = await this.requireConnection(capability.connectionId)\n this.assertConnectionActive(connection)\n const provider = this.requireProvider(connection.providerId)\n const connector = await this.requireConnector(provider, connection.connectorId)\n const action = connector.actions.find((candidate) => candidate.id === request.action)\n if (!action) throw new IntegrationError(`Action ${request.action} is not defined by connector ${connector.id}.`, 'action_not_found')\n assertScopes(connection, action.requiredScopes)\n assertScopes({ ...connection, grantedScopes: capability.scopes }, action.requiredScopes)\n const fullRequest: IntegrationActionRequest = { ...request, connectionId: connection.id }\n const proceed = async () => {\n if (!this.policy) return provider.invokeAction(connection, fullRequest)\n const decision = await this.policy.decide({\n connection,\n request: fullRequest,\n action,\n subject: capability.subject,\n })\n if (decision.decision === 'deny') {\n throw new IntegrationError(decision.reason, 'policy_denied')\n }\n if (decision.decision === 'require_approval') {\n return {\n ok: false,\n action: request.action,\n output: { approvalRequired: true, approval: decision.approval },\n metadata: { policyDecision: decision.decision, reason: decision.reason, ...decision.metadata },\n }\n }\n return provider.invokeAction(connection, fullRequest)\n }\n if (this.guard) {\n return this.guard.invokeAction({ connection, request: fullRequest, action }, proceed)\n }\n return proceed()\n }\n\n async subscribeTrigger(connectionId: string, trigger: string, targetUrl?: string): Promise<IntegrationTriggerSubscription> {\n const connection = await this.requireConnection(connectionId)\n this.assertConnectionActive(connection)\n const provider = this.requireProvider(connection.providerId)\n const connector = await this.requireConnector(provider, connection.connectorId)\n const spec = connector.triggers?.find((candidate) => candidate.id === trigger)\n if (!spec) throw new IntegrationError(`Trigger ${trigger} is not defined by connector ${connector.id}.`, 'trigger_not_found')\n assertScopes(connection, spec.requiredScopes)\n if (!provider.subscribeTrigger) {\n throw new IntegrationError(`Provider ${provider.id} does not support triggers.`, 'auth_not_supported')\n }\n return provider.subscribeTrigger(connection, trigger, targetUrl)\n }\n\n private requireProvider(providerId: string): IntegrationProvider {\n const provider = this.providers.get(providerId)\n if (!provider) throw new IntegrationError(`Provider ${providerId} not found.`, 'provider_not_found')\n return provider\n }\n\n private async requireConnector(provider: IntegrationProvider, connectorId: string): Promise<IntegrationConnector> {\n const connector = (await provider.listConnectors()).find((candidate) => candidate.id === connectorId)\n if (!connector) throw new IntegrationError(`Connector ${connectorId} not found.`, 'connector_not_found')\n return connector\n }\n\n private async requireConnection(connectionId: string): Promise<IntegrationConnection> {\n const connection = await this.store.get(connectionId)\n if (!connection) throw new IntegrationError(`Connection ${connectionId} not found.`, 'connection_not_found')\n return connection\n }\n\n private assertConnectionActive(connection: IntegrationConnection): void {\n if (connection.status !== 'active') {\n throw new IntegrationError(`Connection ${connection.id} is ${connection.status}.`, 'connection_not_active')\n }\n if (connection.expiresAt && Date.parse(connection.expiresAt) <= this.now().getTime()) {\n throw new IntegrationError(`Connection ${connection.id} is expired.`, 'connection_not_active')\n }\n }\n}\n\n\nexport function signCapability(capability: IntegrationCapability, secret: string): string {\n const payload = base64UrlEncode(JSON.stringify(capability))\n const signature = hmac(payload, secret)\n return `${payload}.${signature}`\n}\n\nexport function verifyCapabilityToken(token: string, secret: string): IntegrationCapability {\n const [payload, signature] = token.split('.')\n if (!payload || !signature) throw new IntegrationError('Malformed integration capability.', 'capability_invalid')\n const expected = hmac(payload, secret)\n if (!constantTimeEqual(signature, expected)) throw new IntegrationError('Invalid integration capability signature.', 'capability_invalid')\n let parsed: IntegrationCapability\n try {\n parsed = JSON.parse(base64UrlDecode(payload)) as IntegrationCapability\n } catch {\n throw new IntegrationError('Invalid integration capability payload.', 'capability_invalid')\n }\n if (!parsed.id || !parsed.connectionId || !Array.isArray(parsed.scopes) || !Array.isArray(parsed.allowedActions)) {\n throw new IntegrationError('Invalid integration capability payload.', 'capability_invalid')\n }\n return parsed\n}\n\n\nfunction assertScopes(connection: Pick<IntegrationConnection, 'grantedScopes'>, requiredScopes: string[]): void {\n const missing = requiredScopes.filter((scope) => !connection.grantedScopes.includes(scope))\n if (missing.length > 0) throw new IntegrationError(`Missing integration scopes: ${missing.join(', ')}`, 'scope_denied')\n}\n\n\ntype IntegrationOAuthPkceMode = 'required' | 'supported' | 'unsupported'\n\nfunction connectorOAuthPkceMode(connector: IntegrationConnector): IntegrationOAuthPkceMode {\n const value = connector.metadata?.oauthPkce\n if (value === undefined) return 'required'\n if (value === 'required' || value === 'supported' || value === 'unsupported') return value\n throw new IntegrationError(\n `Connector ${connector.id} declares an invalid OAuth PKCE posture.`,\n 'config_missing',\n )\n}\n\nfunction createPkcePair(): { verifier: string; challenge: string } {\n const verifier = randomBytes(48).toString('base64url')\n const challenge = createHash('sha256').update(verifier).digest('base64url')\n return { verifier, challenge }\n}\n\nfunction hmac(payload: string, secret: string): string {\n return createHmac('sha256', secret).update(payload).digest('base64url')\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n const left = Buffer.from(a)\n const right = Buffer.from(b)\n return left.length === right.length && timingSafeEqual(left, right)\n}\n\nfunction base64UrlEncode(value: string): string {\n return Buffer.from(value, 'utf8').toString('base64url')\n}\n\nfunction base64UrlDecode(value: string): string {\n return Buffer.from(value, 'base64url').toString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