@tangle-network/agent-integrations 0.49.0 → 0.51.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/catalog.js +5 -4
- package/dist/{chunk-IA5GCKM6.js → chunk-BS6LGM3V.js} +84 -38
- package/dist/chunk-BS6LGM3V.js.map +1 -0
- package/dist/{chunk-XECSOZRL.js → chunk-DRBW2FXU.js} +17 -4
- package/dist/{chunk-XECSOZRL.js.map → chunk-DRBW2FXU.js.map} +1 -1
- package/dist/chunk-P4FFI752.js +1 -0
- package/dist/chunk-PUXYDSXI.js +109 -0
- package/dist/chunk-PUXYDSXI.js.map +1 -0
- package/dist/{chunk-EV7PFUCM.js → chunk-XEJKVCXB.js} +33793 -33343
- package/dist/{chunk-EV7PFUCM.js.map → chunk-XEJKVCXB.js.map} +1 -1
- package/dist/connectors/adapters/index.d.ts +16 -1
- package/dist/connectors/adapters/index.js +5 -1
- package/dist/connectors/index.d.ts +44 -3
- package/dist/connectors/index.js +22 -2
- package/dist/conversation-events/index.d.ts +101 -0
- package/dist/conversation-events/index.js +432 -0
- package/dist/conversation-events/index.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +24 -4
- package/dist/mcp.js +5 -4
- package/dist/mcp.js.map +1 -1
- package/dist/registry.js +5 -4
- package/dist/runtime.js +5 -4
- package/dist/specs.d.ts +13 -2
- package/dist/specs.js +5 -1
- package/dist/webhooks/index.d.ts +2 -28
- package/dist/webhooks/index.js.map +1 -1
- package/docs/integration-execution-audit.md +21 -21
- package/docs/integration-execution-matrix.json +1684 -72
- package/package.json +13 -5
- package/dist/chunk-376UBTNB.js +0 -1
- package/dist/chunk-IA5GCKM6.js.map +0 -1
- /package/dist/{chunk-376UBTNB.js.map → chunk-P4FFI752.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -119,7 +119,7 @@ import {
|
|
|
119
119
|
validateIntegrationManifest,
|
|
120
120
|
validateProviderPassthroughRequest,
|
|
121
121
|
verifyCapabilityToken
|
|
122
|
-
} from "./chunk-
|
|
122
|
+
} from "./chunk-DRBW2FXU.js";
|
|
123
123
|
import {
|
|
124
124
|
InMemoryConnectStateStore,
|
|
125
125
|
finishConnectFlow,
|
|
@@ -160,14 +160,24 @@ import {
|
|
|
160
160
|
validateCredentialFormat,
|
|
161
161
|
validateCredentialSet,
|
|
162
162
|
validateIntegrationSpec
|
|
163
|
-
} from "./chunk-
|
|
163
|
+
} from "./chunk-BS6LGM3V.js";
|
|
164
164
|
import {
|
|
165
165
|
buildIntegrationCoverageConnectors,
|
|
166
166
|
integrationCoverageChecklistMarkdown,
|
|
167
167
|
listIntegrationCoverageSpecs
|
|
168
168
|
} from "./chunk-7P2LN4VT.js";
|
|
169
|
-
import "./chunk-
|
|
169
|
+
import "./chunk-P4FFI752.js";
|
|
170
170
|
import {
|
|
171
|
+
bundledApiKeyHint,
|
|
172
|
+
bundledAuthMode,
|
|
173
|
+
bundledOAuth2Auth,
|
|
174
|
+
getBundledAdapterManifest,
|
|
175
|
+
hasBundledAdapter,
|
|
176
|
+
listBundledAdapterKinds,
|
|
177
|
+
listBundledAdapterManifests
|
|
178
|
+
} from "./chunk-PUXYDSXI.js";
|
|
179
|
+
import {
|
|
180
|
+
CONNECTOR_ADAPTER_FACTORIES,
|
|
171
181
|
InMemoryOAuthFlowStore,
|
|
172
182
|
TELEGRAM_FILE_DOWNLOAD_ROOT,
|
|
173
183
|
_resetPendingFlowsForTests,
|
|
@@ -582,6 +592,7 @@ import {
|
|
|
582
592
|
refreshAccessToken,
|
|
583
593
|
reoonVerifierConnector,
|
|
584
594
|
replyIoConnector,
|
|
595
|
+
resolveConnectorAdapterFactoryOptions,
|
|
585
596
|
retableConnector,
|
|
586
597
|
retellAiConnector,
|
|
587
598
|
ringcentralConnector,
|
|
@@ -714,7 +725,7 @@ import {
|
|
|
714
725
|
zohoDeskConnector,
|
|
715
726
|
zoominfoConnector,
|
|
716
727
|
zuoraConnector
|
|
717
|
-
} from "./chunk-
|
|
728
|
+
} from "./chunk-XEJKVCXB.js";
|
|
718
729
|
import {
|
|
719
730
|
DEFAULT_SIGNATURE_TOLERANCE_SECONDS,
|
|
720
731
|
firstHeader,
|
|
@@ -745,6 +756,7 @@ export {
|
|
|
745
756
|
ACTIVEPIECES_PUBLIC_CATALOG_URL,
|
|
746
757
|
ApprovalBackedPolicyEngine,
|
|
747
758
|
CANONICAL_INTEGRATION_ACTIONS,
|
|
759
|
+
CONNECTOR_ADAPTER_FACTORIES,
|
|
748
760
|
CredentialsExpired,
|
|
749
761
|
DEFAULT_INTEGRATION_BRIDGE_ENV,
|
|
750
762
|
DEFAULT_SIGNATURE_TOLERANCE_SECONDS,
|
|
@@ -871,6 +883,9 @@ export {
|
|
|
871
883
|
buildTangleCatalogRuntimePackageManifest,
|
|
872
884
|
buildTangleIntegrationCatalogConnectors,
|
|
873
885
|
builtwithConnector,
|
|
886
|
+
bundledApiKeyHint,
|
|
887
|
+
bundledAuthMode,
|
|
888
|
+
bundledOAuth2Auth,
|
|
874
889
|
calComConnector,
|
|
875
890
|
calendarExercisePlannerManifest,
|
|
876
891
|
calendlyConnector,
|
|
@@ -1030,6 +1045,7 @@ export {
|
|
|
1030
1045
|
gameballConnector,
|
|
1031
1046
|
geminiConnector,
|
|
1032
1047
|
getActivepiecesOverride,
|
|
1048
|
+
getBundledAdapterManifest,
|
|
1033
1049
|
getIntegrationFamily,
|
|
1034
1050
|
getIntegrationSpec,
|
|
1035
1051
|
getresponseConnector,
|
|
@@ -1074,6 +1090,7 @@ export {
|
|
|
1074
1090
|
guideliteConnector,
|
|
1075
1091
|
gustoConnector,
|
|
1076
1092
|
harvestConnector,
|
|
1093
|
+
hasBundledAdapter,
|
|
1077
1094
|
hashiCorpVaultConnector,
|
|
1078
1095
|
hastewireConnector,
|
|
1079
1096
|
healthcheckRequest,
|
|
@@ -1149,6 +1166,8 @@ export {
|
|
|
1149
1166
|
linkaConnector,
|
|
1150
1167
|
linkupConnector,
|
|
1151
1168
|
listActivepiecesCatalogEntries,
|
|
1169
|
+
listBundledAdapterKinds,
|
|
1170
|
+
listBundledAdapterManifests,
|
|
1152
1171
|
listExecutableIntegrationSpecs,
|
|
1153
1172
|
listIntegrationCoverageSpecs,
|
|
1154
1173
|
listIntegrationSpecs,
|
|
@@ -1299,6 +1318,7 @@ export {
|
|
|
1299
1318
|
replyIoConnector,
|
|
1300
1319
|
requireTangleAuth,
|
|
1301
1320
|
resolveConnectionCredentials,
|
|
1321
|
+
resolveConnectorAdapterFactoryOptions,
|
|
1302
1322
|
resolveConnectorAuthSpec,
|
|
1303
1323
|
resolveIntegrationApproval,
|
|
1304
1324
|
retableConnector,
|
package/dist/mcp.js
CHANGED
|
@@ -2,15 +2,16 @@ import {
|
|
|
2
2
|
IntegrationError,
|
|
3
3
|
createCatalogExecutorProvider,
|
|
4
4
|
importMcpConnector
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-DRBW2FXU.js";
|
|
6
6
|
import "./chunk-S2BUASSV.js";
|
|
7
7
|
import "./chunk-LA76XB7M.js";
|
|
8
8
|
import "./chunk-H4XYLS7T.js";
|
|
9
9
|
import "./chunk-VLVSP7SP.js";
|
|
10
|
-
import "./chunk-
|
|
10
|
+
import "./chunk-BS6LGM3V.js";
|
|
11
11
|
import "./chunk-7P2LN4VT.js";
|
|
12
|
-
import "./chunk-
|
|
13
|
-
import "./chunk-
|
|
12
|
+
import "./chunk-P4FFI752.js";
|
|
13
|
+
import "./chunk-PUXYDSXI.js";
|
|
14
|
+
import "./chunk-XEJKVCXB.js";
|
|
14
15
|
import "./chunk-XC54EOUQ.js";
|
|
15
16
|
import "./chunk-UWF33ESC.js";
|
|
16
17
|
import "./chunk-PZ5AY32C.js";
|
package/dist/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp.ts"],"sourcesContent":["/**\n * Live MCP connector — attach a remote MCP (Model Context Protocol) server\n * as an {@link IntegrationProvider}, so its tools flow through the same\n * catalog / grants / approvals machinery as every other connector instead of\n * forming a parallel, ungoverned tool path.\n *\n * Transport is Streamable HTTP only (single POST endpoint, JSON or SSE\n * response framing) — this package runs in edge workers, so stdio servers are\n * out of scope; front them with any HTTP-bridging MCP host.\n *\n * Discovery reuses {@link importMcpConnector}: `tools/list` output becomes an\n * `IntegrationConnector` whose per-action risk comes from MCP tool\n * annotations (readOnlyHint / destructiveHint) with a text-heuristic\n * fallback, so non-read MCP tools default to `approvalRequired` — fail-closed\n * against servers that don't annotate.\n *\n * Credentials: the server's auth header is supplied at construction by the\n * product (which owns secret storage) and held in memory only. Connection\n * rows carry no MCP secrets.\n */\n\nimport { IntegrationError } from './core-error.js'\nimport type {\n IntegrationActionResult,\n IntegrationActionRisk,\n IntegrationConnector,\n IntegrationConnectorCategory,\n IntegrationDataClass,\n IntegrationProvider,\n} from './core-types.js'\nimport { createCatalogExecutorProvider } from './catalog-executor.js'\nimport { importMcpConnector, type McpCatalogTool } from './importers.js'\n\n/** Protocol revision sent on `initialize` and the `MCP-Protocol-Version`\n * header. Servers negotiate down from this. */\nexport const MCP_PROTOCOL_VERSION = '2025-06-18'\n\nexport interface McpServerConfig {\n /** The server's single Streamable-HTTP endpoint. */\n url: string\n /** Static request headers — typically `{ Authorization: 'Bearer …' }`.\n * Held in memory only; never persisted by this module. */\n headers?: Record<string, string>\n protocolVersion?: string\n clientInfo?: { name: string; version: string }\n /** Injectable for tests / custom egress policies (SSRF pinning). */\n fetchImpl?: typeof fetch\n}\n\nexport interface McpToolCallResult {\n /** MCP content blocks (text, image, resource, …) verbatim. */\n content: unknown[]\n isError: boolean\n /** `structuredContent` from servers that return it. */\n structured?: unknown\n}\n\ninterface JsonRpcResponse {\n jsonrpc: '2.0'\n id?: number | string | null\n result?: unknown\n error?: { code: number; message: string; data?: unknown }\n}\n\n/**\n * Minimal Streamable-HTTP MCP client: `initialize` handshake (capturing the\n * server's `Mcp-Session-Id`), paginated `tools/list`, and `tools/call`.\n * Lazily initializes on first use; safe to share across calls within an\n * isolate.\n */\nexport class McpHttpClient {\n private nextId = 1\n private sessionId: string | undefined\n private negotiatedVersion: string | undefined\n private initializing: Promise<void> | undefined\n\n constructor(private readonly config: McpServerConfig) {}\n\n private get fetchImpl(): typeof fetch {\n return this.config.fetchImpl ?? fetch\n }\n\n private async post(body: Record<string, unknown>): Promise<JsonRpcResponse | undefined> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json, text/event-stream',\n ...(this.config.headers ?? {}),\n }\n const version = this.negotiatedVersion ?? this.config.protocolVersion ?? MCP_PROTOCOL_VERSION\n headers['MCP-Protocol-Version'] = version\n if (this.sessionId) headers['Mcp-Session-Id'] = this.sessionId\n\n let response: Response\n try {\n response = await this.fetchImpl(this.config.url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n } catch (error) {\n throw new IntegrationError(\n `MCP server unreachable: ${error instanceof Error ? error.message : String(error)}`,\n 'provider_failure',\n )\n }\n const session = response.headers.get('mcp-session-id')\n if (session) this.sessionId = session\n\n if (!response.ok) {\n throw new IntegrationError(`MCP server returned HTTP ${response.status}`, 'provider_failure')\n }\n // Notifications get 202/204 with no body.\n if (body.id === undefined) return undefined\n const contentType = response.headers.get('content-type') ?? ''\n const text = await response.text()\n const message = contentType.includes('text/event-stream')\n ? findSseResponse(text, body.id as number)\n : (JSON.parse(text) as JsonRpcResponse)\n if (!message) {\n throw new IntegrationError('MCP server response missing a result for the request', 'provider_failure')\n }\n if (message.error) {\n throw new IntegrationError(`MCP error ${message.error.code}: ${message.error.message}`, 'provider_failure')\n }\n return message\n }\n\n private async request(method: string, params?: Record<string, unknown>): Promise<unknown> {\n const response = await this.post({ jsonrpc: '2.0', id: this.nextId++, method, ...(params ? { params } : {}) })\n return response?.result\n }\n\n /** Idempotent handshake; concurrent callers share one in-flight init. */\n async initialize(): Promise<void> {\n if (this.negotiatedVersion) return\n this.initializing ??= (async () => {\n const result = (await this.request('initialize', {\n protocolVersion: this.config.protocolVersion ?? MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: this.config.clientInfo ?? { name: 'tangle-agent-integrations', version: '1' },\n })) as { protocolVersion?: string } | undefined\n this.negotiatedVersion = result?.protocolVersion ?? this.config.protocolVersion ?? MCP_PROTOCOL_VERSION\n await this.post({ jsonrpc: '2.0', method: 'notifications/initialized' })\n })().catch((error) => {\n this.initializing = undefined\n throw error\n })\n await this.initializing\n }\n\n /** Full tool catalog, following `nextCursor` pagination. */\n async listTools(): Promise<McpCatalogTool[]> {\n await this.initialize()\n const tools: McpCatalogTool[] = []\n let cursor: string | undefined\n do {\n const result = (await this.request('tools/list', cursor ? { cursor } : {})) as\n | { tools?: McpCatalogTool[]; nextCursor?: string }\n | undefined\n tools.push(...(result?.tools ?? []))\n cursor = result?.nextCursor\n } while (cursor)\n return tools\n }\n\n async callTool(name: string, args: unknown): Promise<McpToolCallResult> {\n await this.initialize()\n const result = (await this.request('tools/call', { name, arguments: args ?? {} })) as\n | { content?: unknown[]; isError?: boolean; structuredContent?: unknown }\n | undefined\n return {\n content: result?.content ?? [],\n isError: result?.isError === true,\n structured: result?.structuredContent,\n }\n }\n}\n\nexport interface CreateMcpProviderOptions {\n /** Provider id, unique within the hub (e.g. `mcp:linear`). */\n id: string\n server: McpServerConfig\n connectorId: string\n connectorTitle: string\n category?: IntegrationConnectorCategory\n scopes?: string[]\n dataClass?: IntegrationDataClass\n /** Risk for tools whose annotations/name don't classify them. Defaults to\n * 'write' (⇒ approvalRequired) — fail-closed. */\n defaultRisk?: IntegrationActionRisk\n}\n\n/** Discover a live MCP server's tools as an {@link IntegrationConnector}. */\nexport async function discoverMcpConnector(\n client: McpHttpClient,\n options: CreateMcpProviderOptions,\n): Promise<IntegrationConnector> {\n const tools = await client.listTools()\n return importMcpConnector(\n { tools },\n {\n providerId: options.id,\n connectorId: options.connectorId,\n connectorTitle: options.connectorTitle,\n category: options.category,\n auth: 'custom',\n scopes: options.scopes,\n dataClass: options.dataClass,\n defaultRisk: options.defaultRisk ?? 'write',\n },\n )\n}\n\n/**\n * Build an {@link IntegrationProvider} over one remote MCP server: live\n * `tools/list` discovery at construction, `tools/call` on invoke. A tool\n * result with `isError` maps to `{ ok: false }` (the model sees the failure\n * content); transport and JSON-RPC failures throw {@link IntegrationError}.\n */\nexport async function createMcpProvider(options: CreateMcpProviderOptions): Promise<IntegrationProvider> {\n const client = new McpHttpClient(options.server)\n const connector = await discoverMcpConnector(client, options)\n return createCatalogExecutorProvider({\n id: options.id,\n kind: 'mcp',\n connectors: [connector],\n async executeAction({ request, action }): Promise<IntegrationActionResult> {\n const result = await client.callTool(action.id, request.input)\n return {\n ok: !result.isError,\n action: action.id,\n output: result.structured ?? result.content,\n metadata: { mcp: true, ...(result.isError ? { isError: true } : {}) },\n }\n },\n })\n}\n\nfunction findSseResponse(body: string, id: number): JsonRpcResponse | undefined {\n for (const event of body.split(/\\n\\n/)) {\n const data = event\n .split('\\n')\n .filter((line) => line.startsWith('data:'))\n .map((line) => line.slice(5).trim())\n .join('')\n if (!data) continue\n try {\n const parsed = JSON.parse(data) as JsonRpcResponse\n if (parsed.id === id) return parsed\n } catch {\n // non-JSON SSE frame (keepalive/comment) — skip\n }\n }\n return undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmCO,IAAM,uBAAuB;AAmC7B,IAAM,gBAAN,MAAoB;AAAA,EAMzB,YAA6B,QAAyB;AAAzB;AAAA,EAA0B;AAAA,EAA1B;AAAA,EALrB,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EAIR,IAAY,YAA0B;AACpC,WAAO,KAAK,OAAO,aAAa;AAAA,EAClC;AAAA,EAEA,MAAc,KAAK,MAAqE;AACtF,UAAM,UAAkC;AAAA,MACtC,gBAAgB;AAAA,MAChB,QAAQ;AAAA,MACR,GAAI,KAAK,OAAO,WAAW,CAAC;AAAA,IAC9B;AACA,UAAM,UAAU,KAAK,qBAAqB,KAAK,OAAO,mBAAm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Context Protocol) server\n * as an {@link IntegrationProvider}, so its tools flow through the same\n * catalog / grants / approvals machinery as every other connector instead of\n * forming a parallel, ungoverned tool path.\n *\n * Transport is Streamable HTTP only (single POST endpoint, JSON or SSE\n * response framing) — this package runs in edge workers, so stdio servers are\n * out of scope; front them with any HTTP-bridging MCP host.\n *\n * Discovery reuses {@link importMcpConnector}: `tools/list` output becomes an\n * `IntegrationConnector` whose per-action risk comes from MCP tool\n * annotations (readOnlyHint / destructiveHint) with a text-heuristic\n * fallback, so non-read MCP tools default to `approvalRequired` — fail-closed\n * against servers that don't annotate.\n *\n * Credentials: the server's auth header is supplied at construction by the\n * product (which owns secret storage) and held in memory only. Connection\n * rows carry no MCP secrets.\n */\n\nimport { IntegrationError } from './core-error.js'\nimport type {\n IntegrationActionResult,\n IntegrationActionRisk,\n IntegrationConnector,\n IntegrationConnectorCategory,\n IntegrationDataClass,\n IntegrationProvider,\n} from './core-types.js'\nimport { createCatalogExecutorProvider } from './catalog-executor.js'\nimport { importMcpConnector, type McpCatalogTool } from './importers.js'\n\n/** Protocol revision sent on `initialize` and the `MCP-Protocol-Version`\n * header. Servers negotiate down from this. */\nexport const MCP_PROTOCOL_VERSION = '2025-06-18'\n\nexport interface McpServerConfig {\n /** The server's single Streamable-HTTP endpoint. */\n url: string\n /** Static request headers — typically `{ Authorization: 'Bearer …' }`.\n * Held in memory only; never persisted by this module. */\n headers?: Record<string, string>\n protocolVersion?: string\n clientInfo?: { name: string; version: string }\n /** Injectable for tests / custom egress policies (SSRF pinning). */\n fetchImpl?: typeof fetch\n}\n\nexport interface McpToolCallResult {\n /** MCP content blocks (text, image, resource, …) verbatim. */\n content: unknown[]\n isError: boolean\n /** `structuredContent` from servers that return it. */\n structured?: unknown\n}\n\ninterface JsonRpcResponse {\n jsonrpc: '2.0'\n id?: number | string | null\n result?: unknown\n error?: { code: number; message: string; data?: unknown }\n}\n\n/**\n * Minimal Streamable-HTTP MCP client: `initialize` handshake (capturing the\n * server's `Mcp-Session-Id`), paginated `tools/list`, and `tools/call`.\n * Lazily initializes on first use; safe to share across calls within an\n * isolate.\n */\nexport class McpHttpClient {\n private nextId = 1\n private sessionId: string | undefined\n private negotiatedVersion: string | undefined\n private initializing: Promise<void> | undefined\n\n constructor(private readonly config: McpServerConfig) {}\n\n private get fetchImpl(): typeof fetch {\n return this.config.fetchImpl ?? fetch\n }\n\n private async post(body: Record<string, unknown>): Promise<JsonRpcResponse | undefined> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json, text/event-stream',\n ...(this.config.headers ?? {}),\n }\n const version = this.negotiatedVersion ?? this.config.protocolVersion ?? MCP_PROTOCOL_VERSION\n headers['MCP-Protocol-Version'] = version\n if (this.sessionId) headers['Mcp-Session-Id'] = this.sessionId\n\n let response: Response\n try {\n response = await this.fetchImpl(this.config.url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n } catch (error) {\n throw new IntegrationError(\n `MCP server unreachable: ${error instanceof Error ? error.message : String(error)}`,\n 'provider_failure',\n )\n }\n const session = response.headers.get('mcp-session-id')\n if (session) this.sessionId = session\n\n if (!response.ok) {\n throw new IntegrationError(`MCP server returned HTTP ${response.status}`, 'provider_failure')\n }\n // Notifications get 202/204 with no body.\n if (body.id === undefined) return undefined\n const contentType = response.headers.get('content-type') ?? ''\n const text = await response.text()\n const message = contentType.includes('text/event-stream')\n ? findSseResponse(text, body.id as number)\n : (JSON.parse(text) as JsonRpcResponse)\n if (!message) {\n throw new IntegrationError('MCP server response missing a result for the request', 'provider_failure')\n }\n if (message.error) {\n throw new IntegrationError(`MCP error ${message.error.code}: ${message.error.message}`, 'provider_failure')\n }\n return message\n }\n\n private async request(method: string, params?: Record<string, unknown>): Promise<unknown> {\n const response = await this.post({ jsonrpc: '2.0', id: this.nextId++, method, ...(params ? { params } : {}) })\n return response?.result\n }\n\n /** Idempotent handshake; concurrent callers share one in-flight init. */\n async initialize(): Promise<void> {\n if (this.negotiatedVersion) return\n this.initializing ??= (async () => {\n const result = (await this.request('initialize', {\n protocolVersion: this.config.protocolVersion ?? MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: this.config.clientInfo ?? { name: 'tangle-agent-integrations', version: '1' },\n })) as { protocolVersion?: string } | undefined\n this.negotiatedVersion = result?.protocolVersion ?? this.config.protocolVersion ?? MCP_PROTOCOL_VERSION\n await this.post({ jsonrpc: '2.0', method: 'notifications/initialized' })\n })().catch((error) => {\n this.initializing = undefined\n throw error\n })\n await this.initializing\n }\n\n /** Full tool catalog, following `nextCursor` pagination. */\n async listTools(): Promise<McpCatalogTool[]> {\n await this.initialize()\n const tools: McpCatalogTool[] = []\n let cursor: string | undefined\n do {\n const result = (await this.request('tools/list', cursor ? { cursor } : {})) as\n | { tools?: McpCatalogTool[]; nextCursor?: string }\n | undefined\n tools.push(...(result?.tools ?? []))\n cursor = result?.nextCursor\n } while (cursor)\n return tools\n }\n\n async callTool(name: string, args: unknown): Promise<McpToolCallResult> {\n await this.initialize()\n const result = (await this.request('tools/call', { name, arguments: args ?? {} })) as\n | { content?: unknown[]; isError?: boolean; structuredContent?: unknown }\n | undefined\n return {\n content: result?.content ?? [],\n isError: result?.isError === true,\n structured: result?.structuredContent,\n }\n }\n}\n\nexport interface CreateMcpProviderOptions {\n /** Provider id, unique within the hub (e.g. `mcp:linear`). */\n id: string\n server: McpServerConfig\n connectorId: string\n connectorTitle: string\n category?: IntegrationConnectorCategory\n scopes?: string[]\n dataClass?: IntegrationDataClass\n /** Risk for tools whose annotations/name don't classify them. Defaults to\n * 'write' (⇒ approvalRequired) — fail-closed. */\n defaultRisk?: IntegrationActionRisk\n}\n\n/** Discover a live MCP server's tools as an {@link IntegrationConnector}. */\nexport async function discoverMcpConnector(\n client: McpHttpClient,\n options: CreateMcpProviderOptions,\n): Promise<IntegrationConnector> {\n const tools = await client.listTools()\n return importMcpConnector(\n { tools },\n {\n providerId: options.id,\n connectorId: options.connectorId,\n connectorTitle: options.connectorTitle,\n category: options.category,\n auth: 'custom',\n scopes: options.scopes,\n dataClass: options.dataClass,\n defaultRisk: options.defaultRisk ?? 'write',\n },\n )\n}\n\n/**\n * Build an {@link IntegrationProvider} over one remote MCP server: live\n * `tools/list` discovery at construction, `tools/call` on invoke. A tool\n * result with `isError` maps to `{ ok: false }` (the model sees the failure\n * content); transport and JSON-RPC failures throw {@link IntegrationError}.\n */\nexport async function createMcpProvider(options: CreateMcpProviderOptions): Promise<IntegrationProvider> {\n const client = new McpHttpClient(options.server)\n const connector = await discoverMcpConnector(client, options)\n return createCatalogExecutorProvider({\n id: options.id,\n kind: 'mcp',\n connectors: [connector],\n async executeAction({ request, action }): Promise<IntegrationActionResult> {\n const result = await client.callTool(action.id, request.input)\n return {\n ok: !result.isError,\n action: action.id,\n output: result.structured ?? result.content,\n metadata: { mcp: true, ...(result.isError ? { isError: true } : {}) },\n }\n },\n })\n}\n\nfunction findSseResponse(body: string, id: number): JsonRpcResponse | undefined {\n for (const event of body.split(/\\n\\n/)) {\n const data = event\n .split('\\n')\n .filter((line) => line.startsWith('data:'))\n .map((line) => line.slice(5).trim())\n .join('')\n if (!data) continue\n try {\n const parsed = JSON.parse(data) as JsonRpcResponse\n if (parsed.id === id) return parsed\n } catch {\n // non-JSON SSE frame (keepalive/comment) — skip\n }\n }\n return undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCO,IAAM,uBAAuB;AAmC7B,IAAM,gBAAN,MAAoB;AAAA,EAMzB,YAA6B,QAAyB;AAAzB;AAAA,EAA0B;AAAA,EAA1B;AAAA,EALrB,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EAIR,IAAY,YAA0B;AACpC,WAAO,KAAK,OAAO,aAAa;AAAA,EAClC;AAAA,EAEA,MAAc,KAAK,MAAqE;AACtF,UAAM,UAAkC;AAAA,MACtC,gBAAgB;AAAA,MAChB,QAAQ;AAAA,MACR,GAAI,KAAK,OAAO,WAAW,CAAC;AAAA,IAC9B;AACA,UAAM,UAAU,KAAK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
|
5
5
|
composeIntegrationRegistry,
|
|
6
6
|
inferIntegrationSupportTier,
|
|
7
7
|
summarizeIntegrationRegistry
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-DRBW2FXU.js";
|
|
9
9
|
import "./chunk-S2BUASSV.js";
|
|
10
10
|
import "./chunk-LA76XB7M.js";
|
|
11
11
|
import "./chunk-H4XYLS7T.js";
|
|
12
12
|
import "./chunk-VLVSP7SP.js";
|
|
13
|
-
import "./chunk-
|
|
13
|
+
import "./chunk-BS6LGM3V.js";
|
|
14
14
|
import "./chunk-7P2LN4VT.js";
|
|
15
|
-
import "./chunk-
|
|
16
|
-
import "./chunk-
|
|
15
|
+
import "./chunk-P4FFI752.js";
|
|
16
|
+
import "./chunk-PUXYDSXI.js";
|
|
17
|
+
import "./chunk-XEJKVCXB.js";
|
|
17
18
|
import "./chunk-XC54EOUQ.js";
|
|
18
19
|
import "./chunk-UWF33ESC.js";
|
|
19
20
|
import "./chunk-PZ5AY32C.js";
|
package/dist/runtime.js
CHANGED
|
@@ -2,15 +2,16 @@ import {
|
|
|
2
2
|
InMemoryIntegrationGrantStore,
|
|
3
3
|
IntegrationRuntime,
|
|
4
4
|
createIntegrationRuntime
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-DRBW2FXU.js";
|
|
6
6
|
import "./chunk-S2BUASSV.js";
|
|
7
7
|
import "./chunk-LA76XB7M.js";
|
|
8
8
|
import "./chunk-H4XYLS7T.js";
|
|
9
9
|
import "./chunk-VLVSP7SP.js";
|
|
10
|
-
import "./chunk-
|
|
10
|
+
import "./chunk-BS6LGM3V.js";
|
|
11
11
|
import "./chunk-7P2LN4VT.js";
|
|
12
|
-
import "./chunk-
|
|
13
|
-
import "./chunk-
|
|
12
|
+
import "./chunk-P4FFI752.js";
|
|
13
|
+
import "./chunk-PUXYDSXI.js";
|
|
14
|
+
import "./chunk-XEJKVCXB.js";
|
|
14
15
|
import "./chunk-XC54EOUQ.js";
|
|
15
16
|
import "./chunk-UWF33ESC.js";
|
|
16
17
|
import "./chunk-PZ5AY32C.js";
|
package/dist/specs.d.ts
CHANGED
|
@@ -23,8 +23,19 @@ interface IntegrationSpec {
|
|
|
23
23
|
type IntegrationAuthSpec = OAuth2AuthSpec | ApiKeyAuthSpec | HmacAuthSpec | NoneAuthSpec | CustomAuthSpec;
|
|
24
24
|
interface OAuth2AuthSpec {
|
|
25
25
|
mode: 'oauth2';
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
/** Authorization endpoint the connect flow sends the user to.
|
|
27
|
+
*
|
|
28
|
+
* UNDEFINED when no shipped adapter and no family default supplies one —
|
|
29
|
+
* i.e. the catalog knows the integration exists but nothing can currently
|
|
30
|
+
* authenticate it. Callers must treat undefined as "not connectable" and
|
|
31
|
+
* say so; this field was previously filled with
|
|
32
|
+
* `https://example.invalid/<kind>/authorize`, a reserved TLD that can
|
|
33
|
+
* never resolve, which made unconnectable integrations indistinguishable
|
|
34
|
+
* from working ones. */
|
|
35
|
+
authorizationUrl?: string;
|
|
36
|
+
/** Token endpoint. Undefined under the same condition as
|
|
37
|
+
* {@link authorizationUrl}. */
|
|
38
|
+
tokenUrl?: string;
|
|
28
39
|
clientIdEnv?: string;
|
|
29
40
|
clientSecretEnv?: string;
|
|
30
41
|
scopes: ScopeDescriptor[];
|
package/dist/specs.js
CHANGED
|
@@ -16,8 +16,12 @@ import {
|
|
|
16
16
|
validateCredentialFormat,
|
|
17
17
|
validateCredentialSet,
|
|
18
18
|
validateIntegrationSpec
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-BS6LGM3V.js";
|
|
20
20
|
import "./chunk-7P2LN4VT.js";
|
|
21
|
+
import "./chunk-PUXYDSXI.js";
|
|
22
|
+
import "./chunk-XEJKVCXB.js";
|
|
23
|
+
import "./chunk-XC54EOUQ.js";
|
|
24
|
+
import "./chunk-UWF33ESC.js";
|
|
21
25
|
import "./chunk-PZ5AY32C.js";
|
|
22
26
|
export {
|
|
23
27
|
INTEGRATION_FAMILIES,
|
package/dist/webhooks/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { W as WebhookProvider } from '../router-ddcgTV2y.js';
|
|
2
2
|
export { S as SignatureVerification, T as TriggerEventCatalog, a as TriggerEventDescriptor, b as WebhookEnvelope, c as WebhookHeaders, d as WebhookIdempotencyStore, e as WebhookRouter, f as WebhookRouterOptions, g as WebhookRouterRequest, h as WebhookRouterResponse } from '../router-ddcgTV2y.js';
|
|
3
|
+
export { InboundEmailPayload } from '../conversation-events/index.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Pre-built `WebhookProvider` implementations for the inbound surfaces
|
|
@@ -21,33 +22,6 @@ declare const stripeWebhookProvider: WebhookProvider;
|
|
|
21
22
|
declare const slackWebhookProvider: WebhookProvider;
|
|
22
23
|
/** DocuSeal webhook provider. Signature header `X-Docuseal-Signature`. */
|
|
23
24
|
declare const docusealWebhookProvider: WebhookProvider;
|
|
24
|
-
/** The normalized inbound-email payload the Tangle email edge posts and this
|
|
25
|
-
* provider surfaces on `WebhookEnvelope.payload`. `to` is the owner-resolution
|
|
26
|
-
* key — the platform matches it to a connection's provisioned inbound address;
|
|
27
|
-
* `messageId` is the idempotency key. */
|
|
28
|
-
interface InboundEmailPayload {
|
|
29
|
-
/** RFC5322 Message-ID. */
|
|
30
|
-
messageId?: string;
|
|
31
|
-
/** Envelope sender — the firm/customer that emailed in. */
|
|
32
|
-
from: string;
|
|
33
|
-
/** The provisioned inbound address the message was delivered to (owner key). */
|
|
34
|
-
to: string;
|
|
35
|
-
subject?: string;
|
|
36
|
-
text?: string;
|
|
37
|
-
html?: string;
|
|
38
|
-
/** Selected headers the edge forwards (Reply-To, In-Reply-To, References…). */
|
|
39
|
-
headers?: Record<string, string>;
|
|
40
|
-
attachments?: Array<{
|
|
41
|
-
filename?: string;
|
|
42
|
-
contentType?: string;
|
|
43
|
-
/** Bytes as base64, OR a `url`/path the edge staged them at (large files). */
|
|
44
|
-
contentBase64?: string;
|
|
45
|
-
url?: string;
|
|
46
|
-
size?: number;
|
|
47
|
-
}>;
|
|
48
|
-
/** Epoch ms the edge received the message. */
|
|
49
|
-
receivedAt?: number;
|
|
50
|
-
}
|
|
51
25
|
/** Tangle inbound-email provider. Our own Cloudflare Email Routing worker parses
|
|
52
26
|
* the MIME, JSON-serializes it, timestamped-HMAC signs it with the
|
|
53
27
|
* per-connection secret, and POSTs it here — there is no upstream mail-vendor
|
|
@@ -99,4 +73,4 @@ declare function genericHmacWebhookProvider(options: {
|
|
|
99
73
|
parse?: WebhookProvider['parse'];
|
|
100
74
|
}): WebhookProvider;
|
|
101
75
|
|
|
102
|
-
export {
|
|
76
|
+
export { WebhookProvider, clayWebhookProvider, docusealWebhookProvider, emailWebhookProvider, gdriveWebhookProvider, genericHmacWebhookProvider, gmailWebhookProvider, hellosignWebhookProvider, slackWebhookProvider, stripeWebhookProvider, telegramWebhookProvider };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/webhooks/router.ts","../../src/webhooks/providers.ts"],"sourcesContent":["/**\n * @stable Provider-agnostic inbound webhook router.\n *\n * Consumer hooks a single HTTP handler at `/webhook/:provider/:event`\n * (or whatever pathing they prefer) and forwards the request through\n * `WebhookRouter.handle()`. The router:\n *\n * 1. Resolves the registered provider entry.\n * 2. Calls the provider's `verifySignature(rawBody, headers, secrets)`.\n * Failure → 401 fast, no downstream work.\n * 3. Calls the provider's `parse(rawBody, headers)` to extract zero or\n * more normalized events.\n * 4. Enqueues each event for async processing via the consumer-supplied\n * `deliver(event)` callback (best-effort fire-and-forget — the\n * router does NOT block the HTTP response on the consumer's work).\n * 5. Returns 200 fast with `{received: events.length}`.\n *\n * Replay protection: providers that sign timestamps (Stripe, Slack)\n * already reject stale signatures inside `verifySignature`. For providers\n * that don't (DocuSeal, GDrive push), the router exposes a pluggable\n * `idempotency` hook: if `idempotency.seen(providerEventId)` returns\n * true, the router 200s without invoking `deliver()`. Consumers wire\n * this to a durable kv (D1 / Redis / Postgres unique-index).\n *\n * Why a router and not a per-provider express app: the runtime contract\n * a product cares about is \"an inbound event came in, here's the\n * normalized envelope\". Verification, parsing, and idempotency-dedup\n * are mechanical and provider-specific — the router owns them. The\n * consumer's `deliver()` is the only place product logic runs.\n *\n * Stability: `@stable` — additions to `WebhookEnvelope` must be\n * additive; the router's HTTP contract (paths, status codes) is frozen\n * at 200 (ok), 400 (bad request), 401 (bad signature), 404 (unknown\n * provider), 405 (provider has no inbound surface).\n */\n\nexport interface WebhookHeaders {\n [name: string]: string | string[] | undefined\n}\n\n/** Normalized inbound event the router emits after parsing. */\nexport interface WebhookEnvelope<TPayload = unknown> {\n /** Provider id (matches the `:provider` path segment). */\n provider: string\n /** Optional event class — e.g., 'customer.subscription.deleted'. The\n * provider's parser decides. Used for routing inside `deliver()`. */\n eventType: string\n /** Provider-emitted event id, when present. Used for the idempotency\n * short-circuit. */\n providerEventId?: string\n /** Wall-clock receive time. */\n receivedAt: number\n /** Provider payload, normalized to the provider's documented event\n * shape. The router does NOT reshape this — `parse()` is the contract. */\n payload: TPayload\n /** Headers passed through for downstream handlers that want them\n * (e.g., to extract custom routing metadata). Always lowercased keys. */\n headers: Record<string, string>\n}\n\nexport type SignatureVerification =\n | { valid: true }\n | { valid: false; reason: string }\n\n/** One declared triggerable event, in the runtime `eventType` namespace a\n * provider's `parse` emits. */\nexport interface TriggerEventDescriptor {\n /** The `eventType` a workflow `provider_event` trigger matches on\n * (`slack.app_mention`, `charge.succeeded`). */\n id: string\n /** Short human label for authoring surfaces; optional. */\n title?: string\n}\n\n/** The set of events a provider can deliver, for author-time validation of\n * workflow `provider_event` triggers. Co-located with the provider's `parse`\n * (the source of the runtime namespace) so the two cannot drift — see the\n * per-provider drift tests. Consumers validate an authored event with two\n * checks: it must carry `namespace` (a prefix-less event on a namespaced\n * provider can never be delivered), and — only when `closed` — be one of\n * `events` (an exhaustive set makes an unlisted event an authoring error). */\nexport interface TriggerEventCatalog {\n /** Required prefix every `parse`-emitted `eventType` carries (`slack.`,\n * `telegram.`), or `null` when the provider emits raw event names (stripe). */\n namespace: string | null\n /** Declared events. Exhaustive iff `closed`; otherwise authoring hints for an\n * open, provider-owned vocabulary. */\n events: readonly TriggerEventDescriptor[]\n /** True when `events` is the COMPLETE deliverable set, so an event outside it\n * is rejected. False when the provider owns an open-ended vocabulary it keeps\n * adding to (Stripe's ~250 types, Slack's Events API) and only `namespace`\n * can be authoritatively enforced. */\n closed: boolean\n}\n\n/** Per-provider plug-in. Stateless — the router calls `verifySignature`\n * then `parse` on every request. The provider's HTTP-shape concerns\n * (e.g., raw body required) are documented per provider. */\nexport interface WebhookProvider {\n /** Stable provider id (`stripe`, `docuseal`, `gdrive`, ...). */\n id: string\n /** Verify the inbound signature. Receives the EXACT raw body string —\n * consumers MUST preserve raw bytes through their HTTP server (do not\n * parse JSON before forwarding here). */\n verifySignature(input: {\n rawBody: string\n headers: WebhookHeaders\n secret: string\n }): SignatureVerification\n /** Parse the validated raw body into zero or more normalized events.\n * A single push payload may carry multiple events (e.g., Slack bulk\n * delivery). Return [] to ack the push as a no-op. */\n parse(input: {\n rawBody: string\n headers: WebhookHeaders\n now?: number\n }): WebhookEnvelope[] | Promise<WebhookEnvelope[]>\n /** Optional provider-specific 200 ACK the router returns on a verified\n * delivery, in place of the default `{ received, total }` JSON. Dropbox Sign\n * acknowledges a delivery only when the body is exactly\n * 'Hello API Event Received' and retries otherwise; this lets such a\n * provider declare the body/headers it needs. The frozen status contract is\n * unchanged — only the 200 body/headers are customized. */\n successResponse?: { body: string; headers?: Record<string, string> }\n /** Declared triggerable-event catalog, for author-time validation of workflow\n * `provider_event` triggers. Optional: a provider without one is left\n * unvalidated by consumers (the trigger still installs). */\n eventCatalog?: TriggerEventCatalog\n}\n\nexport interface WebhookIdempotencyStore {\n /** Returns true if this providerEventId has been processed already.\n * Implementations should be O(1) (Redis SETNX, D1 UNIQUE constraint). */\n seen(providerEventId: string): Promise<boolean> | boolean\n /** Marks a providerEventId as processed. Called AFTER `deliver()` has\n * been invoked. */\n remember(providerEventId: string, ttlMs: number): Promise<void> | void\n}\n\nexport interface WebhookRouterOptions {\n /** Provider registry. Pass any number of providers; routing is by id. */\n providers: WebhookProvider[]\n /** Async callback invoked with every accepted event. Fire-and-forget\n * from the router's perspective — the HTTP response is sent before\n * this resolves. Throws are caught and reported via `onError`. */\n deliver(event: WebhookEnvelope): Promise<void> | void\n /** Resolve the signing secret for a provider id at request time. The\n * router never holds secrets — the consumer's vault resolves them. */\n resolveSecret(providerId: string, headers: WebhookHeaders): Promise<string | null> | string | null\n /** Optional idempotency-dedup hook. Required for providers that don't\n * sign timestamps in their signature scheme (DocuSeal, Drive push). */\n idempotency?: WebhookIdempotencyStore\n /** TTL on idempotency entries. Default 7 days — long enough that a\n * provider's normal retry-window can't re-deliver. */\n idempotencyTtlMs?: number\n /** Surface delivery errors. Default: console.error. */\n onError?(err: unknown, context: { provider: string; eventType?: string; providerEventId?: string }): void\n /** Override `now()` for tests. */\n now?(): number\n}\n\nexport interface WebhookRouterRequest {\n providerId: string\n rawBody: string\n headers: WebhookHeaders\n}\n\nexport interface WebhookRouterResponse {\n status: number\n body: unknown\n headers?: Record<string, string>\n}\n\n/**\n * Router instance. Stateless aside from the provider registry — safe to\n * share across requests; build once per process.\n */\nexport class WebhookRouter {\n private readonly providers: Map<string, WebhookProvider>\n private readonly deliver: WebhookRouterOptions['deliver']\n private readonly resolveSecret: WebhookRouterOptions['resolveSecret']\n private readonly idempotency?: WebhookIdempotencyStore\n private readonly idempotencyTtlMs: number\n private readonly onError: NonNullable<WebhookRouterOptions['onError']>\n private readonly nowFn: () => number\n\n constructor(opts: WebhookRouterOptions) {\n this.providers = new Map(opts.providers.map((p) => [p.id, p]))\n this.deliver = opts.deliver\n this.resolveSecret = opts.resolveSecret\n this.idempotency = opts.idempotency\n this.idempotencyTtlMs = opts.idempotencyTtlMs ?? 7 * 24 * 60 * 60 * 1000\n this.onError = opts.onError ?? defaultOnError\n this.nowFn = opts.now ?? Date.now\n }\n\n /** Process one inbound webhook request. Pure with respect to side-\n * effects on the router instance — safe to call concurrently. */\n async handle(request: WebhookRouterRequest): Promise<WebhookRouterResponse> {\n const provider = this.providers.get(request.providerId)\n if (!provider) {\n return { status: 404, body: { error: 'unknown_provider', provider: request.providerId } }\n }\n const secret = await this.resolveSecret(provider.id, request.headers)\n if (!secret) {\n return { status: 401, body: { error: 'missing_secret', provider: provider.id } }\n }\n const verification = provider.verifySignature({\n rawBody: request.rawBody,\n headers: request.headers,\n secret,\n })\n if (!verification.valid) {\n return { status: 401, body: { error: 'invalid_signature', reason: verification.reason } }\n }\n\n let events: WebhookEnvelope[]\n try {\n events = await provider.parse({ rawBody: request.rawBody, headers: request.headers, now: this.nowFn() })\n } catch (err) {\n this.onError(err, { provider: provider.id })\n return { status: 400, body: { error: 'parse_error', message: errMessage(err) } }\n }\n\n const accepted: WebhookEnvelope[] = []\n for (const event of events) {\n if (event.providerEventId && this.idempotency) {\n const already = await this.idempotency.seen(event.providerEventId)\n if (already) continue\n }\n accepted.push(event)\n }\n\n // Deliver async — do NOT block the HTTP response. Errors land in\n // `onError`; the provider already got its 200 by then so it will\n // not retry.\n queueMicrotask(() => {\n void this.deliverEach(accepted)\n })\n\n if (provider.successResponse) {\n return {\n status: 200,\n body: provider.successResponse.body,\n headers: provider.successResponse.headers,\n }\n }\n return { status: 200, body: { received: accepted.length, total: events.length } }\n }\n\n private async deliverEach(events: WebhookEnvelope[]): Promise<void> {\n for (const event of events) {\n try {\n await this.deliver(event)\n if (event.providerEventId && this.idempotency) {\n await this.idempotency.remember(event.providerEventId, this.idempotencyTtlMs)\n }\n } catch (err) {\n this.onError(err, {\n provider: event.provider,\n eventType: event.eventType,\n providerEventId: event.providerEventId,\n })\n }\n }\n }\n}\n\nfunction defaultOnError(err: unknown, context: { provider: string; eventType?: string; providerEventId?: string }): void {\n // eslint-disable-next-line no-console\n console.error('[WebhookRouter]', context, err)\n}\n\nfunction errMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * Pre-built `WebhookProvider` implementations for the inbound surfaces\n * the substrate ships first-party verifiers for.\n *\n * Each provider implementation is intentionally thin: it delegates\n * signature verification to the corresponding pure function in\n * `connectors/webhooks.ts` and parses the body into one or more\n * normalized `WebhookEnvelope` rows. Anything provider-specific that\n * doesn't fit cleanly (Slack URL-verification handshake, etc.) is\n * surfaced via the envelope `eventType` so the consumer's `deliver()`\n * can branch.\n */\n\nimport {\n firstHeader,\n verifyEmailSignature,\n verifyHmacSignature,\n verifySlackSignature,\n verifyStripeSignature,\n} from '../connectors/webhooks.js'\nimport type { WebhookEnvelope, WebhookHeaders, WebhookProvider, SignatureVerification } from './router.js'\nimport { createHash, createHmac, timingSafeEqual } from 'node:crypto'\n\n/** Stripe webhook provider. Signature header `Stripe-Signature`. */\nexport const stripeWebhookProvider: WebhookProvider = {\n id: 'stripe',\n verifySignature({ rawBody, headers, secret }): SignatureVerification {\n const sig = firstHeader(headers, 'stripe-signature')\n if (!sig) return { valid: false, reason: 'missing_stripe_signature' }\n return verifyStripeSignature(rawBody, sig, secret)\n ? { valid: true }\n : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody)\n if (!evt || typeof evt !== 'object') return []\n const e = evt as { id?: unknown; type?: unknown }\n return [\n {\n provider: 'stripe',\n eventType: typeof e.type === 'string' ? e.type : 'stripe.unknown',\n providerEventId: typeof e.id === 'string' ? e.id : undefined,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n },\n ]\n },\n eventCatalog: {\n // Stripe emits the raw event `type` (`charge.succeeded`) — no namespace, and\n // an OPEN, versioned vocabulary (~250 types), so these are authoring hints,\n // not a gate.\n namespace: null,\n closed: false,\n events: [\n { id: 'checkout.session.completed' },\n { id: 'checkout.session.expired' },\n { id: 'customer.subscription.created' },\n { id: 'customer.subscription.updated' },\n { id: 'customer.subscription.deleted' },\n { id: 'invoice.paid' },\n { id: 'invoice.payment_failed' },\n { id: 'payment_intent.succeeded' },\n { id: 'payment_intent.payment_failed' },\n { id: 'charge.succeeded' },\n { id: 'charge.refunded' },\n ],\n },\n}\n\n/** Slack Events API provider. Handles the `url_verification` handshake\n * by emitting a synthetic event the consumer's `deliver()` can echo. */\nexport const slackWebhookProvider: WebhookProvider = {\n id: 'slack',\n verifySignature({ rawBody, headers, secret }): SignatureVerification {\n const sig = firstHeader(headers, 'x-slack-signature')\n const ts = firstHeader(headers, 'x-slack-request-timestamp')\n if (!sig || !ts) return { valid: false, reason: 'missing_slack_signature_or_timestamp' }\n return verifySlackSignature(rawBody, sig, ts, secret)\n ? { valid: true }\n : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody) as { type?: string; event_id?: string; event?: { type?: string } } | null\n if (!evt || typeof evt !== 'object') return []\n if (evt.type === 'url_verification') {\n return [{\n provider: 'slack',\n eventType: 'slack.url_verification',\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n }\n const eventType = `slack.${evt.event?.type ?? evt.type ?? 'unknown'}`\n return [{\n provider: 'slack',\n eventType,\n providerEventId: typeof evt.event_id === 'string' ? evt.event_id : undefined,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // Slack namespaces every event `slack.<events-api-type>`, so a prefix-less\n // event is provably dead. The Events API vocabulary is open (Slack adds\n // types), so `events` are hints, not a gate. `slack.url_verification` (the\n // config handshake) is intentionally excluded — it carries no workflow\n // meaning and is answered before dispatch.\n namespace: 'slack.',\n closed: false,\n events: [\n { id: 'slack.message' },\n { id: 'slack.app_mention' },\n { id: 'slack.reaction_added' },\n { id: 'slack.reaction_removed' },\n { id: 'slack.channel_created' },\n { id: 'slack.member_joined_channel' },\n { id: 'slack.team_join' },\n { id: 'slack.app_home_opened' },\n { id: 'slack.file_shared' },\n ],\n },\n}\n\n/** DocuSeal webhook provider. Signature header `X-Docuseal-Signature`. */\nexport const docusealWebhookProvider: WebhookProvider = {\n id: 'docuseal',\n verifySignature({ rawBody, headers, secret }): SignatureVerification {\n const sig = firstHeader(headers, 'x-docuseal-signature')\n if (!sig) return { valid: false, reason: 'missing_docuseal_signature' }\n const expected = createHmac('sha256', secret).update(rawBody).digest('hex')\n const a = Buffer.from(sig.toLowerCase(), 'utf-8')\n const b = Buffer.from(expected, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody) as { event_type?: string; event_id?: string } | null\n if (!evt || typeof evt !== 'object') return []\n return [{\n provider: 'docuseal',\n eventType: `docuseal.${evt.event_type ?? 'unknown'}`,\n providerEventId: typeof evt.event_id === 'string' ? evt.event_id : undefined,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // DocuSeal namespaces every event `docuseal.<event_type>`. The documented\n // set is small but not derivable from `parse`, so it stays open (namespace\n // is the authoritative gate) with the documented types as hints.\n namespace: 'docuseal.',\n closed: false,\n events: [\n { id: 'docuseal.form.viewed' },\n { id: 'docuseal.form.started' },\n { id: 'docuseal.form.completed' },\n { id: 'docuseal.form.declined' },\n { id: 'docuseal.submission.created' },\n { id: 'docuseal.submission.completed' },\n { id: 'docuseal.submission.expired' },\n { id: 'docuseal.submission.archived' },\n ],\n },\n}\n\n/** The normalized inbound-email payload the Tangle email edge posts and this\n * provider surfaces on `WebhookEnvelope.payload`. `to` is the owner-resolution\n * key — the platform matches it to a connection's provisioned inbound address;\n * `messageId` is the idempotency key. */\nexport interface InboundEmailPayload {\n /** RFC5322 Message-ID. */\n messageId?: string\n /** Envelope sender — the firm/customer that emailed in. */\n from: string\n /** The provisioned inbound address the message was delivered to (owner key). */\n to: string\n subject?: string\n text?: string\n html?: string\n /** Selected headers the edge forwards (Reply-To, In-Reply-To, References…). */\n headers?: Record<string, string>\n attachments?: Array<{\n filename?: string\n contentType?: string\n /** Bytes as base64, OR a `url`/path the edge staged them at (large files). */\n contentBase64?: string\n url?: string\n size?: number\n }>\n /** Epoch ms the edge received the message. */\n receivedAt?: number\n}\n\n/** Tangle inbound-email provider. Our own Cloudflare Email Routing worker parses\n * the MIME, JSON-serializes it, timestamped-HMAC signs it with the\n * per-connection secret, and POSTs it here — there is no upstream mail-vendor\n * signature, we are both signer and verifier. One inbound message → one\n * `email.received` envelope; `payload.to` carries the owner-resolution address. */\nexport const emailWebhookProvider: WebhookProvider = {\n id: 'email',\n verifySignature({ rawBody, headers, secret }): SignatureVerification {\n const sig = firstHeader(headers, 'x-tangle-email-signature')\n if (!sig) return { valid: false, reason: 'missing_email_signature' }\n const ts = firstHeader(headers, 'x-tangle-email-timestamp')\n if (!ts) return { valid: false, reason: 'missing_email_timestamp' }\n return verifyEmailSignature(rawBody, sig, ts, secret)\n ? { valid: true }\n : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const msg = safeJson(rawBody) as Partial<InboundEmailPayload> | null\n if (!msg || typeof msg !== 'object') return []\n // `from` + `to` are load-bearing (owner resolution keys off `to`); a body\n // missing either is a malformed edge post — ack as a no-op rather than\n // dispatch an unroutable event.\n if (typeof msg.from !== 'string' || typeof msg.to !== 'string') return []\n return [{\n provider: 'email',\n eventType: 'email.received',\n providerEventId: typeof msg.messageId === 'string' ? msg.messageId : undefined,\n receivedAt: now ?? Date.now(),\n payload: msg as InboundEmailPayload,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // We own the edge, so the inbound surface is exactly one closed event.\n namespace: 'email.',\n closed: true,\n events: [{ id: 'email.received' }],\n },\n}\n\n/** Gmail push provider. Cloud Pub/Sub posts a JWT-signed envelope; the\n * *payload* is base64 JSON describing the changed history range. The\n * signature scheme here is the Pub/Sub JWT auth header — when supplied,\n * consumers SHOULD verify the JWT against Google's well-known\n * certificates. We accept the simpler \"Bearer <pubsub-shared-secret>\"\n * variant by default (matching `verifyHmacSignature`). */\nexport const gmailWebhookProvider: WebhookProvider = {\n id: 'gmail',\n verifySignature({ headers, secret }): SignatureVerification {\n const auth = firstHeader(headers, 'authorization')\n if (!auth) return { valid: false, reason: 'missing_authorization' }\n // Accept either \"Bearer <secret>\" or \"Token <secret>\" formats. This\n // is the simple per-tenant shared-secret path; JWT verification is\n // left to the consumer's `deliver()` when they need full Google JWT\n // chain validation.\n const m = /^(?:Bearer|Token)\\s+(.+)$/i.exec(auth)\n if (!m) return { valid: false, reason: 'invalid_authorization_format' }\n const a = Buffer.from(m[1]!, 'utf-8')\n const b = Buffer.from(secret, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const envelope = safeJson(rawBody) as { message?: { data?: string; messageId?: string; publishTime?: string } } | null\n if (!envelope?.message?.data) return []\n let payload: unknown\n try {\n payload = JSON.parse(Buffer.from(envelope.message.data, 'base64').toString('utf-8'))\n } catch {\n return []\n }\n const inner = payload as { historyId?: number | string; emailAddress?: string }\n return [{\n provider: 'gmail',\n eventType: 'gmail.history_changed',\n providerEventId: envelope.message.messageId,\n receivedAt: now ?? Date.now(),\n payload: { ...inner, publishTime: envelope.message.publishTime },\n headers: normalizeHeaders(headers),\n }]\n },\n}\n\n/** Google Drive push provider. Drive does NOT sign the body — it uses\n * the per-channel token (`X-Goog-Channel-Token`) as the shared secret.\n * The router compares it constant-time against the resolved secret. */\nexport const gdriveWebhookProvider: WebhookProvider = {\n id: 'gdrive',\n verifySignature({ headers, secret }): SignatureVerification {\n const token = firstHeader(headers, 'x-goog-channel-token')\n if (!token) return { valid: false, reason: 'missing_channel_token' }\n const a = Buffer.from(token, 'utf-8')\n const b = Buffer.from(secret, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ headers, now }): WebhookEnvelope[] {\n const resourceId = firstHeader(headers, 'x-goog-resource-id')\n const resourceState = firstHeader(headers, 'x-goog-resource-state') ?? 'unknown'\n const channelId = firstHeader(headers, 'x-goog-channel-id')\n const messageNumber = firstHeader(headers, 'x-goog-message-number')\n if (resourceState === 'sync') {\n return [{\n provider: 'gdrive',\n eventType: 'gdrive.channel.sync',\n providerEventId: messageNumber ? `${channelId}-${messageNumber}` : undefined,\n receivedAt: now ?? Date.now(),\n payload: { channelId, resourceId, resourceState },\n headers: normalizeHeaders(headers),\n }]\n }\n return [{\n provider: 'gdrive',\n eventType: `gdrive.resource.${resourceState}`,\n providerEventId: messageNumber ? `${channelId}-${messageNumber}` : undefined,\n receivedAt: now ?? Date.now(),\n payload: { channelId, resourceId, resourceState },\n headers: normalizeHeaders(headers),\n }]\n },\n}\n\n/** The Telegram update keys, in resolution order — the first present key names\n * the update kind (`telegram.message`, `telegram.callback_query`, …). */\nconst TELEGRAM_UPDATE_KEYS = [\n 'message',\n 'edited_message',\n 'channel_post',\n 'edited_channel_post',\n 'business_connection',\n 'business_message',\n 'edited_business_message',\n 'deleted_business_messages',\n 'message_reaction',\n 'message_reaction_count',\n 'inline_query',\n 'chosen_inline_result',\n 'callback_query',\n 'shipping_query',\n 'pre_checkout_query',\n 'purchased_paid_media',\n 'poll',\n 'poll_answer',\n 'my_chat_member',\n 'chat_member',\n 'chat_join_request',\n 'chat_boost',\n 'removed_chat_boost',\n] as const\n\n/** Telegram Bot API webhook provider. Telegram does NOT sign the body — it\n * authenticates by echoing the `secret_token` set at `setWebhook` time in the\n * `X-Telegram-Bot-Api-Secret-Token` header. We compare it constant-time to the\n * per-connection secret. `update_id` is the idempotency anchor. */\nexport const telegramWebhookProvider: WebhookProvider = {\n id: 'telegram',\n verifySignature({ headers, secret }): SignatureVerification {\n const token = firstHeader(headers, 'x-telegram-bot-api-secret-token')\n if (!token) return { valid: false, reason: 'missing_telegram_secret_token' }\n const a = Buffer.from(token, 'utf-8')\n const b = Buffer.from(secret, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_secret_token' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_secret_token' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody) as ({ update_id?: number } & Record<string, unknown>) | null\n if (!evt || typeof evt !== 'object') return []\n const kind = TELEGRAM_UPDATE_KEYS.find((k) => k in evt) ?? 'unknown'\n return [{\n provider: 'telegram',\n eventType: `telegram.${kind}`,\n providerEventId: typeof evt.update_id === 'number' ? String(evt.update_id) : undefined,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // Derived from the SAME TELEGRAM_UPDATE_KEYS `parse` matches on, so the\n // catalog is exhaustive and cannot drift — hence `closed`. (`telegram.unknown`,\n // parse's fallback for an update with no recognized key, is intentionally\n // excluded: it is not a triggerable event.)\n namespace: 'telegram.',\n closed: true,\n events: TELEGRAM_UPDATE_KEYS.map((k) => ({ id: `telegram.${k}` })),\n },\n}\n\n/** Dropbox Sign (HelloSign) webhook provider. There is NO signature header:\n * the body carries `event.event_hash = HMAC_SHA256(apiKey, event_time +\n * event_type)` (hex), so the `secret` here is the account's API key (the\n * caller resolves it from the connection credential). The body is JSON, or a\n * `json=`/multipart `name=\"json\"` form field on older apps. */\nexport const hellosignWebhookProvider: WebhookProvider = {\n id: 'hellosign',\n // Dropbox Sign acknowledges a delivery only when the response body is exactly\n // 'Hello API Event Received'; any other body makes it retry the event.\n successResponse: { body: 'Hello API Event Received', headers: { 'content-type': 'text/plain' } },\n verifySignature({ rawBody, secret }): SignatureVerification {\n const body = parseHelloSignBody(rawBody)\n const event = body?.event\n if (\n !event ||\n typeof event.event_time !== 'string' ||\n typeof event.event_type !== 'string' ||\n typeof event.event_hash !== 'string'\n ) {\n return { valid: false, reason: 'missing_event_fields' }\n }\n const expected = createHmac('sha256', secret)\n .update(`${event.event_time}${event.event_type}`)\n .digest('hex')\n const a = Buffer.from(event.event_hash.toLowerCase(), 'utf-8')\n const b = Buffer.from(expected.toLowerCase(), 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const body = parseHelloSignBody(rawBody)\n const event = body?.event\n if (!event) return []\n return [{\n provider: 'hellosign',\n eventType: `hellosign.${event.event_type ?? 'unknown'}`,\n // Prefer Dropbox Sign's canonical `event.event_id` (stable across\n // redeliveries, correlates with the provider). Fall back to a digest of\n // the parsed body when it's absent: `event_hash` = HMAC(apiKey,\n // event_time + event_type), so two distinct same-type events in the same\n // second share it — the body digest stays distinct across differing\n // events and identical across redeliveries of one event.\n providerEventId:\n typeof event.event_id === 'string' && event.event_id.length > 0\n ? event.event_id\n : createHash('sha256').update(JSON.stringify(body)).digest('hex'),\n receivedAt: now ?? Date.now(),\n payload: body,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // Dropbox Sign namespaces every event `hellosign.<event_type>`. Documented\n // set as hints; namespace is the authoritative gate. `callback_test` (the\n // app-config ping) is intentionally excluded — it is not a workflow event.\n namespace: 'hellosign.',\n closed: false,\n events: [\n { id: 'hellosign.signature_request_sent' },\n { id: 'hellosign.signature_request_viewed' },\n { id: 'hellosign.signature_request_signed' },\n { id: 'hellosign.signature_request_all_signed' },\n { id: 'hellosign.signature_request_declined' },\n { id: 'hellosign.signature_request_reassigned' },\n { id: 'hellosign.signature_request_remind' },\n { id: 'hellosign.signature_request_canceled' },\n { id: 'hellosign.signature_request_expired' },\n ],\n },\n}\n\n/** Keys Clay HTTP-API-action payloads commonly carry that can anchor\n * idempotency, in resolution order. Clay bodies are operator-defined, so we\n * fall back to a digest of the raw body when none is present. */\nconst CLAY_EVENT_ID_KEYS = ['id', 'rowId', 'recordId', 'clayRowId', 'eventId'] as const\n\n/** Clay webhook provider — receives rows Clay delivers via its outbound \"HTTP\n * API\" action. Clay does NOT sign its requests and adds no proprietary\n * headers (the `x-clay-signature: sha256=...` header seen in some third-party\n * code is unverified inference, not in Clay's docs). Authentication is\n * therefore a pre-shared secret the operator adds as a header on the Clay\n * action; we compare it constant-time against the per-connection secret.\n * Header: `x-clay-webhook-secret`. The body is whatever columns the operator\n * mapped (free-form JSON with no canonical event id), so idempotency anchors\n * on a common id field when present, else a sha256 of the raw body. */\nexport const clayWebhookProvider: WebhookProvider = {\n id: 'clay',\n verifySignature({ headers, secret }): SignatureVerification {\n const token = firstHeader(headers, 'x-clay-webhook-secret')\n if (!token) return { valid: false, reason: 'missing_clay_webhook_secret' }\n const a = Buffer.from(token, 'utf-8')\n const b = Buffer.from(secret, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody)\n if (!evt || typeof evt !== 'object') return []\n const record = evt as Record<string, unknown>\n const idKey = CLAY_EVENT_ID_KEYS.find(\n (k) => typeof record[k] === 'string' || typeof record[k] === 'number',\n )\n const providerEventId = idKey\n ? String(record[idKey])\n : createHash('sha256').update(rawBody).digest('hex')\n const eventType =\n typeof record.event === 'string'\n ? `clay.${record.event}`\n : typeof record.type === 'string'\n ? `clay.${record.type}`\n : 'clay.row'\n return [{\n provider: 'clay',\n eventType,\n providerEventId,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n },\n}\n\ninterface HelloSignInboundBody {\n event?: {\n event_time?: string\n event_type?: string\n event_hash?: string\n event_id?: string\n }\n}\n\n/** Dropbox Sign posts JSON, a form-urlencoded `json=` field, or a\n * multipart `name=\"json\"` part depending on app vintage. Mirrors the\n * connector adapter's body extraction. */\nfunction parseHelloSignBody(rawBody: string): HelloSignInboundBody | null {\n try {\n const json = JSON.parse(rawBody) as HelloSignInboundBody\n if (json && typeof json === 'object') return json\n } catch {\n // fall through to form-data extraction\n }\n // application/x-www-form-urlencoded `json=` field. URLSearchParams decodes\n // `+` as a space (decodeURIComponent leaves it literal) and resolves\n // percent-escapes, so space-bearing string fields aren't corrupted.\n const formJson = new URLSearchParams(rawBody).get('json')\n if (formJson) {\n try {\n return JSON.parse(formJson) as HelloSignInboundBody\n } catch {\n return null\n }\n }\n // multipart/form-data with a `name=\"json\"` part. Extract linearly (indexOf +\n // fixed-shape separator probes, no unbounded lazy regex) so a hostile body\n // can't drive quadratic backtracking on this public ingress.\n return extractMultipartJsonField(rawBody)\n}\n\n/** Pull the `json` part out of a multipart/form-data body without an\n * unbounded backtracking regex. Returns null if the part isn't present or\n * isn't valid JSON. The separator probes (`\\r?\\n\\r?\\n`, `\\r?\\n--`) are\n * fixed-shape (no `*`/`+`), so each runs in a single linear scan. */\nfunction extractMultipartJsonField(rawBody: string): HelloSignInboundBody | null {\n const nameIdx = rawBody.indexOf('name=\"json\"')\n if (nameIdx === -1) return null\n const afterName = rawBody.slice(nameIdx)\n const sep = /\\r?\\n\\r?\\n/.exec(afterName)\n if (!sep) return null\n const partBody = afterName.slice(sep.index + sep[0].length)\n const end = /\\r?\\n--/.exec(partBody)\n if (!end) return null\n try {\n return JSON.parse(partBody.slice(0, end.index)) as HelloSignInboundBody\n } catch {\n return null\n }\n}\n\n/** Generic HMAC provider — for the long-tail webhook source where the\n * caller has standardised on a single sha256-of-body scheme. Header\n * `X-Signature` by default; override at provider-build time if needed. */\nexport function genericHmacWebhookProvider(options: {\n id: string\n signatureHeader?: string\n algorithm?: 'sha256' | 'sha1' | 'sha512'\n signaturePrefix?: string\n /** Parser to convert the raw body into envelopes. Defaults to\n * \"one event with eventType=<provider>.event and payload=JSON\". */\n parse?: WebhookProvider['parse']\n}): WebhookProvider {\n const header = options.signatureHeader ?? 'x-signature'\n return {\n id: options.id,\n verifySignature({ rawBody, headers, secret }) {\n const sig = firstHeader(headers, header)\n if (!sig) return { valid: false, reason: `missing_${header}` }\n return verifyHmacSignature(rawBody, sig, secret, {\n algorithm: options.algorithm ?? 'sha256',\n signaturePrefix: options.signaturePrefix,\n })\n ? { valid: true }\n : { valid: false, reason: 'invalid_signature' }\n },\n parse:\n options.parse ??\n (({ rawBody, headers, now }) => {\n const evt = safeJson(rawBody) ?? rawBody\n return [{\n provider: options.id,\n eventType: `${options.id}.event`,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n }),\n }\n}\n\nfunction safeJson(s: string): unknown {\n try {\n return JSON.parse(s)\n } catch {\n return null\n }\n}\n\nfunction normalizeHeaders(headers: WebhookHeaders): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(headers)) {\n if (v === undefined) continue\n const value = Array.isArray(v) ? v[0] : v\n if (typeof value === 'string') out[k.toLowerCase()] = value\n }\n return out\n}\n"],"mappings":";;;;;;;;;;AAiLO,IAAM,gBAAN,MAAoB;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,MAA4B;AACtC,SAAK,YAAY,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;AAC7D,SAAK,UAAU,KAAK;AACpB,SAAK,gBAAgB,KAAK;AAC1B,SAAK,cAAc,KAAK;AACxB,SAAK,mBAAmB,KAAK,oBAAoB,IAAI,KAAK,KAAK,KAAK;AACpE,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,QAAQ,KAAK,OAAO,KAAK;AAAA,EAChC;AAAA;AAAA;AAAA,EAIA,MAAM,OAAO,S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AA,IAClD;AAAA,IACA,OACE,QAAQ,UACP,CAAC,EAAE,SAAS,SAAS,IAAI,MAAM;AAC9B,YAAM,MAAM,SAAS,OAAO,KAAK;AACjC,aAAO,CAAC;AAAA,QACN,UAAU,QAAQ;AAAA,QAClB,WAAW,GAAG,QAAQ,EAAE;AAAA,QACxB,YAAY,OAAO,KAAK,IAAI;AAAA,QAC5B,SAAS;AAAA,QACT,SAAS,iBAAiB,OAAO;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,EACJ;AACF;AAEA,SAAS,SAAS,GAAoB;AACpC,MAAI;AACF,WAAO,KAAK,MAAM,CAAC;AAAA,EACrB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,iBAAiB,SAAiD;AACzE,QAAM,MAA8B,CAAC;AACrC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,OAAO,GAAG;AAC5C,QAAI,MAAM,OAAW;AACrB,UAAM,QAAQ,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI;AACxC,QAAI,OAAO,UAAU,SAAU,KAAI,EAAE,YAAY,CAAC,IAAI;AAAA,EACxD;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/webhooks/router.ts","../../src/webhooks/providers.ts"],"sourcesContent":["/**\n * @stable Provider-agnostic inbound webhook router.\n *\n * Consumer hooks a single HTTP handler at `/webhook/:provider/:event`\n * (or whatever pathing they prefer) and forwards the request through\n * `WebhookRouter.handle()`. The router:\n *\n * 1. Resolves the registered provider entry.\n * 2. Calls the provider's `verifySignature(rawBody, headers, secrets)`.\n * Failure → 401 fast, no downstream work.\n * 3. Calls the provider's `parse(rawBody, headers)` to extract zero or\n * more normalized events.\n * 4. Enqueues each event for async processing via the consumer-supplied\n * `deliver(event)` callback (best-effort fire-and-forget — the\n * router does NOT block the HTTP response on the consumer's work).\n * 5. Returns 200 fast with `{received: events.length}`.\n *\n * Replay protection: providers that sign timestamps (Stripe, Slack)\n * already reject stale signatures inside `verifySignature`. For providers\n * that don't (DocuSeal, GDrive push), the router exposes a pluggable\n * `idempotency` hook: if `idempotency.seen(providerEventId)` returns\n * true, the router 200s without invoking `deliver()`. Consumers wire\n * this to a durable kv (D1 / Redis / Postgres unique-index).\n *\n * Why a router and not a per-provider express app: the runtime contract\n * a product cares about is \"an inbound event came in, here's the\n * normalized envelope\". Verification, parsing, and idempotency-dedup\n * are mechanical and provider-specific — the router owns them. The\n * consumer's `deliver()` is the only place product logic runs.\n *\n * Stability: `@stable` — additions to `WebhookEnvelope` must be\n * additive; the router's HTTP contract (paths, status codes) is frozen\n * at 200 (ok), 400 (bad request), 401 (bad signature), 404 (unknown\n * provider), 405 (provider has no inbound surface).\n */\n\nexport interface WebhookHeaders {\n [name: string]: string | string[] | undefined\n}\n\n/** Normalized inbound event the router emits after parsing. */\nexport interface WebhookEnvelope<TPayload = unknown> {\n /** Provider id (matches the `:provider` path segment). */\n provider: string\n /** Optional event class — e.g., 'customer.subscription.deleted'. The\n * provider's parser decides. Used for routing inside `deliver()`. */\n eventType: string\n /** Provider-emitted event id, when present. Used for the idempotency\n * short-circuit. */\n providerEventId?: string\n /** Wall-clock receive time. */\n receivedAt: number\n /** Provider payload, normalized to the provider's documented event\n * shape. The router does NOT reshape this — `parse()` is the contract. */\n payload: TPayload\n /** Headers passed through for downstream handlers that want them\n * (e.g., to extract custom routing metadata). Always lowercased keys. */\n headers: Record<string, string>\n}\n\nexport type SignatureVerification =\n | { valid: true }\n | { valid: false; reason: string }\n\n/** One declared triggerable event, in the runtime `eventType` namespace a\n * provider's `parse` emits. */\nexport interface TriggerEventDescriptor {\n /** The `eventType` a workflow `provider_event` trigger matches on\n * (`slack.app_mention`, `charge.succeeded`). */\n id: string\n /** Short human label for authoring surfaces; optional. */\n title?: string\n}\n\n/** The set of events a provider can deliver, for author-time validation of\n * workflow `provider_event` triggers. Co-located with the provider's `parse`\n * (the source of the runtime namespace) so the two cannot drift — see the\n * per-provider drift tests. Consumers validate an authored event with two\n * checks: it must carry `namespace` (a prefix-less event on a namespaced\n * provider can never be delivered), and — only when `closed` — be one of\n * `events` (an exhaustive set makes an unlisted event an authoring error). */\nexport interface TriggerEventCatalog {\n /** Required prefix every `parse`-emitted `eventType` carries (`slack.`,\n * `telegram.`), or `null` when the provider emits raw event names (stripe). */\n namespace: string | null\n /** Declared events. Exhaustive iff `closed`; otherwise authoring hints for an\n * open, provider-owned vocabulary. */\n events: readonly TriggerEventDescriptor[]\n /** True when `events` is the COMPLETE deliverable set, so an event outside it\n * is rejected. False when the provider owns an open-ended vocabulary it keeps\n * adding to (Stripe's ~250 types, Slack's Events API) and only `namespace`\n * can be authoritatively enforced. */\n closed: boolean\n}\n\n/** Per-provider plug-in. Stateless — the router calls `verifySignature`\n * then `parse` on every request. The provider's HTTP-shape concerns\n * (e.g., raw body required) are documented per provider. */\nexport interface WebhookProvider {\n /** Stable provider id (`stripe`, `docuseal`, `gdrive`, ...). */\n id: string\n /** Verify the inbound signature. Receives the EXACT raw body string —\n * consumers MUST preserve raw bytes through their HTTP server (do not\n * parse JSON before forwarding here). */\n verifySignature(input: {\n rawBody: string\n headers: WebhookHeaders\n secret: string\n }): SignatureVerification\n /** Parse the validated raw body into zero or more normalized events.\n * A single push payload may carry multiple events (e.g., Slack bulk\n * delivery). Return [] to ack the push as a no-op. */\n parse(input: {\n rawBody: string\n headers: WebhookHeaders\n now?: number\n }): WebhookEnvelope[] | Promise<WebhookEnvelope[]>\n /** Optional provider-specific 200 ACK the router returns on a verified\n * delivery, in place of the default `{ received, total }` JSON. Dropbox Sign\n * acknowledges a delivery only when the body is exactly\n * 'Hello API Event Received' and retries otherwise; this lets such a\n * provider declare the body/headers it needs. The frozen status contract is\n * unchanged — only the 200 body/headers are customized. */\n successResponse?: { body: string; headers?: Record<string, string> }\n /** Declared triggerable-event catalog, for author-time validation of workflow\n * `provider_event` triggers. Optional: a provider without one is left\n * unvalidated by consumers (the trigger still installs). */\n eventCatalog?: TriggerEventCatalog\n}\n\nexport interface WebhookIdempotencyStore {\n /** Returns true if this providerEventId has been processed already.\n * Implementations should be O(1) (Redis SETNX, D1 UNIQUE constraint). */\n seen(providerEventId: string): Promise<boolean> | boolean\n /** Marks a providerEventId as processed. Called AFTER `deliver()` has\n * been invoked. */\n remember(providerEventId: string, ttlMs: number): Promise<void> | void\n}\n\nexport interface WebhookRouterOptions {\n /** Provider registry. Pass any number of providers; routing is by id. */\n providers: WebhookProvider[]\n /** Async callback invoked with every accepted event. Fire-and-forget\n * from the router's perspective — the HTTP response is sent before\n * this resolves. Throws are caught and reported via `onError`. */\n deliver(event: WebhookEnvelope): Promise<void> | void\n /** Resolve the signing secret for a provider id at request time. The\n * router never holds secrets — the consumer's vault resolves them. */\n resolveSecret(providerId: string, headers: WebhookHeaders): Promise<string | null> | string | null\n /** Optional idempotency-dedup hook. Required for providers that don't\n * sign timestamps in their signature scheme (DocuSeal, Drive push). */\n idempotency?: WebhookIdempotencyStore\n /** TTL on idempotency entries. Default 7 days — long enough that a\n * provider's normal retry-window can't re-deliver. */\n idempotencyTtlMs?: number\n /** Surface delivery errors. Default: console.error. */\n onError?(err: unknown, context: { provider: string; eventType?: string; providerEventId?: string }): void\n /** Override `now()` for tests. */\n now?(): number\n}\n\nexport interface WebhookRouterRequest {\n providerId: string\n rawBody: string\n headers: WebhookHeaders\n}\n\nexport interface WebhookRouterResponse {\n status: number\n body: unknown\n headers?: Record<string, string>\n}\n\n/**\n * Router instance. Stateless aside from the provider registry — safe to\n * share across requests; build once per process.\n */\nexport class WebhookRouter {\n private readonly providers: Map<string, WebhookProvider>\n private readonly deliver: WebhookRouterOptions['deliver']\n private readonly resolveSecret: WebhookRouterOptions['resolveSecret']\n private readonly idempotency?: WebhookIdempotencyStore\n private readonly idempotencyTtlMs: number\n private readonly onError: NonNullable<WebhookRouterOptions['onError']>\n private readonly nowFn: () => number\n\n constructor(opts: WebhookRouterOptions) {\n this.providers = new Map(opts.providers.map((p) => [p.id, p]))\n this.deliver = opts.deliver\n this.resolveSecret = opts.resolveSecret\n this.idempotency = opts.idempotency\n this.idempotencyTtlMs = opts.idempotencyTtlMs ?? 7 * 24 * 60 * 60 * 1000\n this.onError = opts.onError ?? defaultOnError\n this.nowFn = opts.now ?? Date.now\n }\n\n /** Process one inbound webhook request. Pure with respect to side-\n * effects on the router instance — safe to call concurrently. */\n async handle(request: WebhookRouterRequest): Promise<WebhookRouterResponse> {\n const provider = this.providers.get(request.providerId)\n if (!provider) {\n return { status: 404, body: { error: 'unknown_provider', provider: request.providerId } }\n }\n const secret = await this.resolveSecret(provider.id, request.headers)\n if (!secret) {\n return { status: 401, body: { error: 'missing_secret', provider: provider.id } }\n }\n const verification = provider.verifySignature({\n rawBody: request.rawBody,\n headers: request.headers,\n secret,\n })\n if (!verification.valid) {\n return { status: 401, body: { error: 'invalid_signature', reason: verification.reason } }\n }\n\n let events: WebhookEnvelope[]\n try {\n events = await provider.parse({ rawBody: request.rawBody, headers: request.headers, now: this.nowFn() })\n } catch (err) {\n this.onError(err, { provider: provider.id })\n return { status: 400, body: { error: 'parse_error', message: errMessage(err) } }\n }\n\n const accepted: WebhookEnvelope[] = []\n for (const event of events) {\n if (event.providerEventId && this.idempotency) {\n const already = await this.idempotency.seen(event.providerEventId)\n if (already) continue\n }\n accepted.push(event)\n }\n\n // Deliver async — do NOT block the HTTP response. Errors land in\n // `onError`; the provider already got its 200 by then so it will\n // not retry.\n queueMicrotask(() => {\n void this.deliverEach(accepted)\n })\n\n if (provider.successResponse) {\n return {\n status: 200,\n body: provider.successResponse.body,\n headers: provider.successResponse.headers,\n }\n }\n return { status: 200, body: { received: accepted.length, total: events.length } }\n }\n\n private async deliverEach(events: WebhookEnvelope[]): Promise<void> {\n for (const event of events) {\n try {\n await this.deliver(event)\n if (event.providerEventId && this.idempotency) {\n await this.idempotency.remember(event.providerEventId, this.idempotencyTtlMs)\n }\n } catch (err) {\n this.onError(err, {\n provider: event.provider,\n eventType: event.eventType,\n providerEventId: event.providerEventId,\n })\n }\n }\n }\n}\n\nfunction defaultOnError(err: unknown, context: { provider: string; eventType?: string; providerEventId?: string }): void {\n // eslint-disable-next-line no-console\n console.error('[WebhookRouter]', context, err)\n}\n\nfunction errMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * Pre-built `WebhookProvider` implementations for the inbound surfaces\n * the substrate ships first-party verifiers for.\n *\n * Each provider implementation is intentionally thin: it delegates\n * signature verification to the corresponding pure function in\n * `connectors/webhooks.ts` and parses the body into one or more\n * normalized `WebhookEnvelope` rows. Anything provider-specific that\n * doesn't fit cleanly (Slack URL-verification handshake, etc.) is\n * surfaced via the envelope `eventType` so the consumer's `deliver()`\n * can branch.\n */\n\nimport {\n firstHeader,\n verifyEmailSignature,\n verifyHmacSignature,\n verifySlackSignature,\n verifyStripeSignature,\n} from '../connectors/webhooks.js'\nimport type { WebhookEnvelope, WebhookHeaders, WebhookProvider, SignatureVerification } from './router.js'\nimport { createHash, createHmac, timingSafeEqual } from 'node:crypto'\nimport type { InboundEmailPayload } from '../conversation-events/index.js'\n\nexport type { InboundEmailPayload } from '../conversation-events/index.js'\n\n/** Stripe webhook provider. Signature header `Stripe-Signature`. */\nexport const stripeWebhookProvider: WebhookProvider = {\n id: 'stripe',\n verifySignature({ rawBody, headers, secret }): SignatureVerification {\n const sig = firstHeader(headers, 'stripe-signature')\n if (!sig) return { valid: false, reason: 'missing_stripe_signature' }\n return verifyStripeSignature(rawBody, sig, secret)\n ? { valid: true }\n : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody)\n if (!evt || typeof evt !== 'object') return []\n const e = evt as { id?: unknown; type?: unknown }\n return [\n {\n provider: 'stripe',\n eventType: typeof e.type === 'string' ? e.type : 'stripe.unknown',\n providerEventId: typeof e.id === 'string' ? e.id : undefined,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n },\n ]\n },\n eventCatalog: {\n // Stripe emits the raw event `type` (`charge.succeeded`) — no namespace, and\n // an OPEN, versioned vocabulary (~250 types), so these are authoring hints,\n // not a gate.\n namespace: null,\n closed: false,\n events: [\n { id: 'checkout.session.completed' },\n { id: 'checkout.session.expired' },\n { id: 'customer.subscription.created' },\n { id: 'customer.subscription.updated' },\n { id: 'customer.subscription.deleted' },\n { id: 'invoice.paid' },\n { id: 'invoice.payment_failed' },\n { id: 'payment_intent.succeeded' },\n { id: 'payment_intent.payment_failed' },\n { id: 'charge.succeeded' },\n { id: 'charge.refunded' },\n ],\n },\n}\n\n/** Slack Events API provider. Handles the `url_verification` handshake\n * by emitting a synthetic event the consumer's `deliver()` can echo. */\nexport const slackWebhookProvider: WebhookProvider = {\n id: 'slack',\n verifySignature({ rawBody, headers, secret }): SignatureVerification {\n const sig = firstHeader(headers, 'x-slack-signature')\n const ts = firstHeader(headers, 'x-slack-request-timestamp')\n if (!sig || !ts) return { valid: false, reason: 'missing_slack_signature_or_timestamp' }\n return verifySlackSignature(rawBody, sig, ts, secret)\n ? { valid: true }\n : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody) as { type?: string; event_id?: string; event?: { type?: string } } | null\n if (!evt || typeof evt !== 'object') return []\n if (evt.type === 'url_verification') {\n return [{\n provider: 'slack',\n eventType: 'slack.url_verification',\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n }\n const eventType = `slack.${evt.event?.type ?? evt.type ?? 'unknown'}`\n return [{\n provider: 'slack',\n eventType,\n providerEventId: typeof evt.event_id === 'string' ? evt.event_id : undefined,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // Slack namespaces every event `slack.<events-api-type>`, so a prefix-less\n // event is provably dead. The Events API vocabulary is open (Slack adds\n // types), so `events` are hints, not a gate. `slack.url_verification` (the\n // config handshake) is intentionally excluded — it carries no workflow\n // meaning and is answered before dispatch.\n namespace: 'slack.',\n closed: false,\n events: [\n { id: 'slack.message' },\n { id: 'slack.app_mention' },\n { id: 'slack.reaction_added' },\n { id: 'slack.reaction_removed' },\n { id: 'slack.channel_created' },\n { id: 'slack.member_joined_channel' },\n { id: 'slack.team_join' },\n { id: 'slack.app_home_opened' },\n { id: 'slack.file_shared' },\n ],\n },\n}\n\n/** DocuSeal webhook provider. Signature header `X-Docuseal-Signature`. */\nexport const docusealWebhookProvider: WebhookProvider = {\n id: 'docuseal',\n verifySignature({ rawBody, headers, secret }): SignatureVerification {\n const sig = firstHeader(headers, 'x-docuseal-signature')\n if (!sig) return { valid: false, reason: 'missing_docuseal_signature' }\n const expected = createHmac('sha256', secret).update(rawBody).digest('hex')\n const a = Buffer.from(sig.toLowerCase(), 'utf-8')\n const b = Buffer.from(expected, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody) as { event_type?: string; event_id?: string } | null\n if (!evt || typeof evt !== 'object') return []\n return [{\n provider: 'docuseal',\n eventType: `docuseal.${evt.event_type ?? 'unknown'}`,\n providerEventId: typeof evt.event_id === 'string' ? evt.event_id : undefined,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // DocuSeal namespaces every event `docuseal.<event_type>`. The documented\n // set is small but not derivable from `parse`, so it stays open (namespace\n // is the authoritative gate) with the documented types as hints.\n namespace: 'docuseal.',\n closed: false,\n events: [\n { id: 'docuseal.form.viewed' },\n { id: 'docuseal.form.started' },\n { id: 'docuseal.form.completed' },\n { id: 'docuseal.form.declined' },\n { id: 'docuseal.submission.created' },\n { id: 'docuseal.submission.completed' },\n { id: 'docuseal.submission.expired' },\n { id: 'docuseal.submission.archived' },\n ],\n },\n}\n\n/** Tangle inbound-email provider. Our own Cloudflare Email Routing worker parses\n * the MIME, JSON-serializes it, timestamped-HMAC signs it with the\n * per-connection secret, and POSTs it here — there is no upstream mail-vendor\n * signature, we are both signer and verifier. One inbound message → one\n * `email.received` envelope; `payload.to` carries the owner-resolution address. */\nexport const emailWebhookProvider: WebhookProvider = {\n id: 'email',\n verifySignature({ rawBody, headers, secret }): SignatureVerification {\n const sig = firstHeader(headers, 'x-tangle-email-signature')\n if (!sig) return { valid: false, reason: 'missing_email_signature' }\n const ts = firstHeader(headers, 'x-tangle-email-timestamp')\n if (!ts) return { valid: false, reason: 'missing_email_timestamp' }\n return verifyEmailSignature(rawBody, sig, ts, secret)\n ? { valid: true }\n : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const msg = safeJson(rawBody) as Partial<InboundEmailPayload> | null\n if (!msg || typeof msg !== 'object') return []\n // `from` + `to` are load-bearing (owner resolution keys off `to`); a body\n // missing either is a malformed edge post — ack as a no-op rather than\n // dispatch an unroutable event.\n if (typeof msg.from !== 'string' || typeof msg.to !== 'string') return []\n return [{\n provider: 'email',\n eventType: 'email.received',\n providerEventId: typeof msg.messageId === 'string' ? msg.messageId : undefined,\n receivedAt: now ?? Date.now(),\n payload: msg as InboundEmailPayload,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // We own the edge, so the inbound surface is exactly one closed event.\n namespace: 'email.',\n closed: true,\n events: [{ id: 'email.received' }],\n },\n}\n\n/** Gmail push provider. Cloud Pub/Sub posts a JWT-signed envelope; the\n * *payload* is base64 JSON describing the changed history range. The\n * signature scheme here is the Pub/Sub JWT auth header — when supplied,\n * consumers SHOULD verify the JWT against Google's well-known\n * certificates. We accept the simpler \"Bearer <pubsub-shared-secret>\"\n * variant by default (matching `verifyHmacSignature`). */\nexport const gmailWebhookProvider: WebhookProvider = {\n id: 'gmail',\n verifySignature({ headers, secret }): SignatureVerification {\n const auth = firstHeader(headers, 'authorization')\n if (!auth) return { valid: false, reason: 'missing_authorization' }\n // Accept either \"Bearer <secret>\" or \"Token <secret>\" formats. This\n // is the simple per-tenant shared-secret path; JWT verification is\n // left to the consumer's `deliver()` when they need full Google JWT\n // chain validation.\n const m = /^(?:Bearer|Token)\\s+(.+)$/i.exec(auth)\n if (!m) return { valid: false, reason: 'invalid_authorization_format' }\n const a = Buffer.from(m[1]!, 'utf-8')\n const b = Buffer.from(secret, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const envelope = safeJson(rawBody) as { message?: { data?: string; messageId?: string; publishTime?: string } } | null\n if (!envelope?.message?.data) return []\n let payload: unknown\n try {\n payload = JSON.parse(Buffer.from(envelope.message.data, 'base64').toString('utf-8'))\n } catch {\n return []\n }\n const inner = payload as { historyId?: number | string; emailAddress?: string }\n return [{\n provider: 'gmail',\n eventType: 'gmail.history_changed',\n providerEventId: envelope.message.messageId,\n receivedAt: now ?? Date.now(),\n payload: { ...inner, publishTime: envelope.message.publishTime },\n headers: normalizeHeaders(headers),\n }]\n },\n}\n\n/** Google Drive push provider. Drive does NOT sign the body — it uses\n * the per-channel token (`X-Goog-Channel-Token`) as the shared secret.\n * The router compares it constant-time against the resolved secret. */\nexport const gdriveWebhookProvider: WebhookProvider = {\n id: 'gdrive',\n verifySignature({ headers, secret }): SignatureVerification {\n const token = firstHeader(headers, 'x-goog-channel-token')\n if (!token) return { valid: false, reason: 'missing_channel_token' }\n const a = Buffer.from(token, 'utf-8')\n const b = Buffer.from(secret, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ headers, now }): WebhookEnvelope[] {\n const resourceId = firstHeader(headers, 'x-goog-resource-id')\n const resourceState = firstHeader(headers, 'x-goog-resource-state') ?? 'unknown'\n const channelId = firstHeader(headers, 'x-goog-channel-id')\n const messageNumber = firstHeader(headers, 'x-goog-message-number')\n if (resourceState === 'sync') {\n return [{\n provider: 'gdrive',\n eventType: 'gdrive.channel.sync',\n providerEventId: messageNumber ? `${channelId}-${messageNumber}` : undefined,\n receivedAt: now ?? Date.now(),\n payload: { channelId, resourceId, resourceState },\n headers: normalizeHeaders(headers),\n }]\n }\n return [{\n provider: 'gdrive',\n eventType: `gdrive.resource.${resourceState}`,\n providerEventId: messageNumber ? `${channelId}-${messageNumber}` : undefined,\n receivedAt: now ?? Date.now(),\n payload: { channelId, resourceId, resourceState },\n headers: normalizeHeaders(headers),\n }]\n },\n}\n\n/** The Telegram update keys, in resolution order — the first present key names\n * the update kind (`telegram.message`, `telegram.callback_query`, …). */\nconst TELEGRAM_UPDATE_KEYS = [\n 'message',\n 'edited_message',\n 'channel_post',\n 'edited_channel_post',\n 'business_connection',\n 'business_message',\n 'edited_business_message',\n 'deleted_business_messages',\n 'message_reaction',\n 'message_reaction_count',\n 'inline_query',\n 'chosen_inline_result',\n 'callback_query',\n 'shipping_query',\n 'pre_checkout_query',\n 'purchased_paid_media',\n 'poll',\n 'poll_answer',\n 'my_chat_member',\n 'chat_member',\n 'chat_join_request',\n 'chat_boost',\n 'removed_chat_boost',\n] as const\n\n/** Telegram Bot API webhook provider. Telegram does NOT sign the body — it\n * authenticates by echoing the `secret_token` set at `setWebhook` time in the\n * `X-Telegram-Bot-Api-Secret-Token` header. We compare it constant-time to the\n * per-connection secret. `update_id` is the idempotency anchor. */\nexport const telegramWebhookProvider: WebhookProvider = {\n id: 'telegram',\n verifySignature({ headers, secret }): SignatureVerification {\n const token = firstHeader(headers, 'x-telegram-bot-api-secret-token')\n if (!token) return { valid: false, reason: 'missing_telegram_secret_token' }\n const a = Buffer.from(token, 'utf-8')\n const b = Buffer.from(secret, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_secret_token' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_secret_token' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody) as ({ update_id?: number } & Record<string, unknown>) | null\n if (!evt || typeof evt !== 'object') return []\n const kind = TELEGRAM_UPDATE_KEYS.find((k) => k in evt) ?? 'unknown'\n return [{\n provider: 'telegram',\n eventType: `telegram.${kind}`,\n providerEventId: typeof evt.update_id === 'number' ? String(evt.update_id) : undefined,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // Derived from the SAME TELEGRAM_UPDATE_KEYS `parse` matches on, so the\n // catalog is exhaustive and cannot drift — hence `closed`. (`telegram.unknown`,\n // parse's fallback for an update with no recognized key, is intentionally\n // excluded: it is not a triggerable event.)\n namespace: 'telegram.',\n closed: true,\n events: TELEGRAM_UPDATE_KEYS.map((k) => ({ id: `telegram.${k}` })),\n },\n}\n\n/** Dropbox Sign (HelloSign) webhook provider. There is NO signature header:\n * the body carries `event.event_hash = HMAC_SHA256(apiKey, event_time +\n * event_type)` (hex), so the `secret` here is the account's API key (the\n * caller resolves it from the connection credential). The body is JSON, or a\n * `json=`/multipart `name=\"json\"` form field on older apps. */\nexport const hellosignWebhookProvider: WebhookProvider = {\n id: 'hellosign',\n // Dropbox Sign acknowledges a delivery only when the response body is exactly\n // 'Hello API Event Received'; any other body makes it retry the event.\n successResponse: { body: 'Hello API Event Received', headers: { 'content-type': 'text/plain' } },\n verifySignature({ rawBody, secret }): SignatureVerification {\n const body = parseHelloSignBody(rawBody)\n const event = body?.event\n if (\n !event ||\n typeof event.event_time !== 'string' ||\n typeof event.event_type !== 'string' ||\n typeof event.event_hash !== 'string'\n ) {\n return { valid: false, reason: 'missing_event_fields' }\n }\n const expected = createHmac('sha256', secret)\n .update(`${event.event_time}${event.event_type}`)\n .digest('hex')\n const a = Buffer.from(event.event_hash.toLowerCase(), 'utf-8')\n const b = Buffer.from(expected.toLowerCase(), 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const body = parseHelloSignBody(rawBody)\n const event = body?.event\n if (!event) return []\n return [{\n provider: 'hellosign',\n eventType: `hellosign.${event.event_type ?? 'unknown'}`,\n // Prefer Dropbox Sign's canonical `event.event_id` (stable across\n // redeliveries, correlates with the provider). Fall back to a digest of\n // the parsed body when it's absent: `event_hash` = HMAC(apiKey,\n // event_time + event_type), so two distinct same-type events in the same\n // second share it — the body digest stays distinct across differing\n // events and identical across redeliveries of one event.\n providerEventId:\n typeof event.event_id === 'string' && event.event_id.length > 0\n ? event.event_id\n : createHash('sha256').update(JSON.stringify(body)).digest('hex'),\n receivedAt: now ?? Date.now(),\n payload: body,\n headers: normalizeHeaders(headers),\n }]\n },\n eventCatalog: {\n // Dropbox Sign namespaces every event `hellosign.<event_type>`. Documented\n // set as hints; namespace is the authoritative gate. `callback_test` (the\n // app-config ping) is intentionally excluded — it is not a workflow event.\n namespace: 'hellosign.',\n closed: false,\n events: [\n { id: 'hellosign.signature_request_sent' },\n { id: 'hellosign.signature_request_viewed' },\n { id: 'hellosign.signature_request_signed' },\n { id: 'hellosign.signature_request_all_signed' },\n { id: 'hellosign.signature_request_declined' },\n { id: 'hellosign.signature_request_reassigned' },\n { id: 'hellosign.signature_request_remind' },\n { id: 'hellosign.signature_request_canceled' },\n { id: 'hellosign.signature_request_expired' },\n ],\n },\n}\n\n/** Keys Clay HTTP-API-action payloads commonly carry that can anchor\n * idempotency, in resolution order. Clay bodies are operator-defined, so we\n * fall back to a digest of the raw body when none is present. */\nconst CLAY_EVENT_ID_KEYS = ['id', 'rowId', 'recordId', 'clayRowId', 'eventId'] as const\n\n/** Clay webhook provider — receives rows Clay delivers via its outbound \"HTTP\n * API\" action. Clay does NOT sign its requests and adds no proprietary\n * headers (the `x-clay-signature: sha256=...` header seen in some third-party\n * code is unverified inference, not in Clay's docs). Authentication is\n * therefore a pre-shared secret the operator adds as a header on the Clay\n * action; we compare it constant-time against the per-connection secret.\n * Header: `x-clay-webhook-secret`. The body is whatever columns the operator\n * mapped (free-form JSON with no canonical event id), so idempotency anchors\n * on a common id field when present, else a sha256 of the raw body. */\nexport const clayWebhookProvider: WebhookProvider = {\n id: 'clay',\n verifySignature({ headers, secret }): SignatureVerification {\n const token = firstHeader(headers, 'x-clay-webhook-secret')\n if (!token) return { valid: false, reason: 'missing_clay_webhook_secret' }\n const a = Buffer.from(token, 'utf-8')\n const b = Buffer.from(secret, 'utf-8')\n if (a.length !== b.length) return { valid: false, reason: 'invalid_signature' }\n return timingSafeEqual(a, b) ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n parse({ rawBody, headers, now }): WebhookEnvelope[] {\n const evt = safeJson(rawBody)\n if (!evt || typeof evt !== 'object') return []\n const record = evt as Record<string, unknown>\n const idKey = CLAY_EVENT_ID_KEYS.find(\n (k) => typeof record[k] === 'string' || typeof record[k] === 'number',\n )\n const providerEventId = idKey\n ? String(record[idKey])\n : createHash('sha256').update(rawBody).digest('hex')\n const eventType =\n typeof record.event === 'string'\n ? `clay.${record.event}`\n : typeof record.type === 'string'\n ? `clay.${record.type}`\n : 'clay.row'\n return [{\n provider: 'clay',\n eventType,\n providerEventId,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n },\n}\n\ninterface HelloSignInboundBody {\n event?: {\n event_time?: string\n event_type?: string\n event_hash?: string\n event_id?: string\n }\n}\n\n/** Dropbox Sign posts JSON, a form-urlencoded `json=` field, or a\n * multipart `name=\"json\"` part depending on app vintage. Mirrors the\n * connector adapter's body extraction. */\nfunction parseHelloSignBody(rawBody: string): HelloSignInboundBody | null {\n try {\n const json = JSON.parse(rawBody) as HelloSignInboundBody\n if (json && typeof json === 'object') return json\n } catch {\n // fall through to form-data extraction\n }\n // application/x-www-form-urlencoded `json=` field. URLSearchParams decodes\n // `+` as a space (decodeURIComponent leaves it literal) and resolves\n // percent-escapes, so space-bearing string fields aren't corrupted.\n const formJson = new URLSearchParams(rawBody).get('json')\n if (formJson) {\n try {\n return JSON.parse(formJson) as HelloSignInboundBody\n } catch {\n return null\n }\n }\n // multipart/form-data with a `name=\"json\"` part. Extract linearly (indexOf +\n // fixed-shape separator probes, no unbounded lazy regex) so a hostile body\n // can't drive quadratic backtracking on this public ingress.\n return extractMultipartJsonField(rawBody)\n}\n\n/** Pull the `json` part out of a multipart/form-data body without an\n * unbounded backtracking regex. Returns null if the part isn't present or\n * isn't valid JSON. The separator probes (`\\r?\\n\\r?\\n`, `\\r?\\n--`) are\n * fixed-shape (no `*`/`+`), so each runs in a single linear scan. */\nfunction extractMultipartJsonField(rawBody: string): HelloSignInboundBody | null {\n const nameIdx = rawBody.indexOf('name=\"json\"')\n if (nameIdx === -1) return null\n const afterName = rawBody.slice(nameIdx)\n const sep = /\\r?\\n\\r?\\n/.exec(afterName)\n if (!sep) return null\n const partBody = afterName.slice(sep.index + sep[0].length)\n const end = /\\r?\\n--/.exec(partBody)\n if (!end) return null\n try {\n return JSON.parse(partBody.slice(0, end.index)) as HelloSignInboundBody\n } catch {\n return null\n }\n}\n\n/** Generic HMAC provider — for the long-tail webhook source where the\n * caller has standardised on a single sha256-of-body scheme. Header\n * `X-Signature` by default; override at provider-build time if needed. */\nexport function genericHmacWebhookProvider(options: {\n id: string\n signatureHeader?: string\n algorithm?: 'sha256' | 'sha1' | 'sha512'\n signaturePrefix?: string\n /** Parser to convert the raw body into envelopes. Defaults to\n * \"one event with eventType=<provider>.event and payload=JSON\". */\n parse?: WebhookProvider['parse']\n}): WebhookProvider {\n const header = options.signatureHeader ?? 'x-signature'\n return {\n id: options.id,\n verifySignature({ rawBody, headers, secret }) {\n const sig = firstHeader(headers, header)\n if (!sig) return { valid: false, reason: `missing_${header}` }\n return verifyHmacSignature(rawBody, sig, secret, {\n algorithm: options.algorithm ?? 'sha256',\n signaturePrefix: options.signaturePrefix,\n })\n ? { valid: true }\n : { valid: false, reason: 'invalid_signature' }\n },\n parse:\n options.parse ??\n (({ rawBody, headers, now }) => {\n const evt = safeJson(rawBody) ?? rawBody\n return [{\n provider: options.id,\n eventType: `${options.id}.event`,\n receivedAt: now ?? Date.now(),\n payload: evt,\n headers: normalizeHeaders(headers),\n }]\n }),\n }\n}\n\nfunction safeJson(s: string): unknown {\n try {\n return JSON.parse(s)\n } catch {\n return null\n }\n}\n\nfunction normalizeHeaders(headers: WebhookHeaders): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(headers)) {\n if (v === undefined) continue\n const value = Array.isArray(v) ? v[0] : v\n if (typeof value === 'string') out[k.toLowerCase()] = value\n }\n return out\n}\n"],"mappings":";;;;;;;;;;AAiLO,IAAM,gBAAN,MAAoB;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,MAA4B;AACtC,SAAK,YAAY,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;AAC7D,SAAK,UAAU,KAAK;AACpB,SAAK,gBAAgB,KAAK;AAC1B,SAAK,cAAc,KAAK;AACxB,SAAK,mBAAmB,KAAK,oBAAoB,IAAI,KAAK,KAAK,KAAK;AACpE,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,QAAQ,KAAK,OAAO,KAAK;AAAA,EAChC;AAAA;AAAA;AAAA,EAIA,MAAM,OAAO,SAA+D;AAC1E,UAAM,WAAW,KAAK,UAAU,IAAI,QAAQ,UAAU;AACtD,QAAI,CAAC,UAAU;AACb,aAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,OAAO,oBAAoB,UAAU,QAAQ,WAAW,EAAE;AAAA,IAC1F;AACA,UAAM,SAAS,MAAM,KAAK,cAAc,SAAS,IAAI,QAAQ,OAAO;AACpE,QAAI,CAAC,QAAQ;AACX,aAAO,EAAE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