@tangle-network/agent-integrations 0.73.0 → 0.74.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/data/bundled-adapter-manifests.json +1 -1
- package/dist/{adapters-D8TvHRA1.js → adapters-CngYgl1W.js} +168 -605
- package/dist/{adapters-D8TvHRA1.js.map → adapters-CngYgl1W.js.map} +1 -1
- package/dist/{bundled-manifest-data-MdURriam.js → bundled-manifest-data-DituXLws.js} +197 -5
- package/dist/{bundled-manifest-data-MdURriam.js.map → bundled-manifest-data-DituXLws.js.map} +1 -1
- package/dist/cloudbeds-BL5EF3xl.js +1195 -0
- package/dist/cloudbeds-BL5EF3xl.js.map +1 -0
- package/dist/connect/index.js +1 -1
- package/dist/connectors/adapters/index.js +3 -2
- package/dist/connectors/index.js +5 -4
- package/dist/consumer.js +1 -1
- package/dist/index-udV3gGjx.d.ts.map +1 -1
- package/dist/index.js +7 -6
- package/dist/internal/bundled-manifest-runtime.js +1 -1
- package/dist/mcp.js +1 -1
- package/dist/middleware/index.js +1 -1
- package/dist/registry.js +1 -1
- package/dist/{specs-BYUQOsSC.js → specs-BeC45S22.js} +2 -2
- package/dist/{specs-BYUQOsSC.js.map → specs-BeC45S22.js.map} +1 -1
- package/dist/specs.js +1 -1
- package/dist/{src-c7Ru9_WT.js → src-B4-qkoxS.js} +4 -4
- package/dist/{src-c7Ru9_WT.js.map → src-B4-qkoxS.js.map} +1 -1
- package/dist/{tangle-id-D2kPF0rX.js → tangle-id-81ShqJ7k.js} +3 -262
- package/dist/tangle-id-81ShqJ7k.js.map +1 -0
- package/dist/types-BSDXGSi5.js +263 -0
- package/dist/types-BSDXGSi5.js.map +1 -0
- package/dist/webhooks/index.d.ts +5 -0
- package/dist/webhooks/index.d.ts.map +1 -1
- package/dist/webhooks/index.js +92 -2
- package/dist/webhooks/index.js.map +1 -1
- package/docs/hospitality-connectors.md +91 -11
- package/package.json +1 -1
- package/dist/tangle-id-D2kPF0rX.js.map +0 -1
- package/dist/webhooks-FsjqRN_0.js +0 -117
- package/dist/webhooks-FsjqRN_0.js.map +0 -1
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
//#region src/connectors/types.ts
|
|
2
|
+
/** Thrown by `executeMutation` when upstream rejects on CAS — caught and
|
|
3
|
+
* rewrapped by MutationGuard. */
|
|
4
|
+
var ResourceContention = class extends Error {
|
|
5
|
+
alternatives;
|
|
6
|
+
currentState;
|
|
7
|
+
name = "ResourceContention";
|
|
8
|
+
constructor(message, alternatives = [], currentState) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.alternatives = alternatives;
|
|
11
|
+
this.currentState = currentState;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/** Thrown when the connector finds the user's grant has been revoked or the
|
|
15
|
+
* access token is no longer valid AND refresh failed — reconnecting fixes it.
|
|
16
|
+
* Surfaces to the UI as "Reconnect required". Carries optional structured
|
|
17
|
+
* `{status, reason, body}` so the platform can confirm a 401/403 really is a
|
|
18
|
+
* credential reason before flipping the connection to reconnect_required. */
|
|
19
|
+
var CredentialsExpired = class extends Error {
|
|
20
|
+
dataSourceId;
|
|
21
|
+
name = "CredentialsExpired";
|
|
22
|
+
status;
|
|
23
|
+
reason;
|
|
24
|
+
body;
|
|
25
|
+
constructor(message, dataSourceId, init) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.dataSourceId = dataSourceId;
|
|
28
|
+
this.status = init?.status;
|
|
29
|
+
this.reason = init?.reason;
|
|
30
|
+
this.body = init?.body;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
/** Thrown when the provider rejects the call for a configuration or permission
|
|
34
|
+
* reason that reconnecting the credential CANNOT fix — the API isn't enabled
|
|
35
|
+
* for the project (`accessNotConfigured`), a required scope is missing
|
|
36
|
+
* (`insufficientPermissions`), or the resource is forbidden
|
|
37
|
+
* (`PERMISSION_DENIED`). Distinct from CredentialsExpired so the platform
|
|
38
|
+
* surfaces "fix the project/scope" instead of sending the user into an
|
|
39
|
+
* unresolvable reconnect loop. */
|
|
40
|
+
var ProviderConfigError = class extends Error {
|
|
41
|
+
dataSourceId;
|
|
42
|
+
name = "ProviderConfigError";
|
|
43
|
+
status;
|
|
44
|
+
reason;
|
|
45
|
+
body;
|
|
46
|
+
constructor(message, dataSourceId, init) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.dataSourceId = dataSourceId;
|
|
49
|
+
this.status = init.status;
|
|
50
|
+
this.reason = init.reason;
|
|
51
|
+
this.body = init.body;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
/** Thrown when the provider throttles the call (quota / rate limit). Gmail and
|
|
55
|
+
* Calendar surface daily/per-user limits as HTTP 403 with a quota `reason`
|
|
56
|
+
* (`rateLimitExceeded`/`dailyLimitExceeded`/`userRateLimitExceeded`), NOT 429
|
|
57
|
+
* — so it is classified by reason, not status, and must never read as a
|
|
58
|
+
* credential failure. The message includes "rate limit" so a platform that
|
|
59
|
+
* only inspects the message still routes it to rate-limited. */
|
|
60
|
+
var ProviderRateLimited = class extends Error {
|
|
61
|
+
dataSourceId;
|
|
62
|
+
name = "ProviderRateLimited";
|
|
63
|
+
status;
|
|
64
|
+
reason;
|
|
65
|
+
body;
|
|
66
|
+
retryAfterMs;
|
|
67
|
+
constructor(message, dataSourceId, init) {
|
|
68
|
+
super(message);
|
|
69
|
+
this.dataSourceId = dataSourceId;
|
|
70
|
+
this.status = init.status;
|
|
71
|
+
this.reason = init.reason;
|
|
72
|
+
this.body = init.body;
|
|
73
|
+
this.retryAfterMs = init.retryAfterMs;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
/** Thrown when the provider settles a call with a non-2xx status that is not
|
|
77
|
+
* a credential, permission or rate-limit failure: a 400 naming a bad field, a
|
|
78
|
+
* 404, a 409, or a 5xx. Carries `{status, reason, body}` so the platform
|
|
79
|
+
* answers a refusal as a refusal (a 4xx with the provider's message) instead
|
|
80
|
+
* of a gateway fault, and keeps the provider's own error code as `reason`. */
|
|
81
|
+
var ProviderRequestError = class extends Error {
|
|
82
|
+
dataSourceId;
|
|
83
|
+
name = "ProviderRequestError";
|
|
84
|
+
status;
|
|
85
|
+
reason;
|
|
86
|
+
body;
|
|
87
|
+
constructor(message, dataSourceId, init) {
|
|
88
|
+
super(message);
|
|
89
|
+
this.dataSourceId = dataSourceId;
|
|
90
|
+
this.status = init.status;
|
|
91
|
+
this.reason = init.reason;
|
|
92
|
+
this.body = init.body;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
/** Thrown before any provider request when a caller's argument breaks the
|
|
96
|
+
* capability's declared contract: a value that fails its `pattern`, or one the
|
|
97
|
+
* provider would refuse with a misleading answer (a commit sha where a branch
|
|
98
|
+
* name belongs reads back as "Branch not found"). `field` names the argument,
|
|
99
|
+
* and the message says what to pass instead. `status` is 400 so a platform
|
|
100
|
+
* classifier answers it as a settled refusal: the same arguments fail again. */
|
|
101
|
+
var InvalidCapabilityArgument = class extends Error {
|
|
102
|
+
field;
|
|
103
|
+
name = "InvalidCapabilityArgument";
|
|
104
|
+
status = 400;
|
|
105
|
+
reason = "invalid_argument";
|
|
106
|
+
constructor(message, field) {
|
|
107
|
+
super(message);
|
|
108
|
+
this.field = field;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
/** Validate the static connector manifest before a provider registers it.
|
|
112
|
+
* This catches the expensive mistakes early: duplicate capability names,
|
|
113
|
+
* mutation capabilities without CAS, authoritative fire-and-forget writes,
|
|
114
|
+
* and invalid rate-limit specs. */
|
|
115
|
+
function validateConnectorManifest(manifest) {
|
|
116
|
+
const issues = [];
|
|
117
|
+
if (!manifest.kind.trim()) issues.push({
|
|
118
|
+
path: "kind",
|
|
119
|
+
message: "kind is required"
|
|
120
|
+
});
|
|
121
|
+
if (!manifest.displayName.trim()) issues.push({
|
|
122
|
+
path: "displayName",
|
|
123
|
+
message: "displayName is required"
|
|
124
|
+
});
|
|
125
|
+
const consistencyModels = /* @__PURE__ */ new Set([
|
|
126
|
+
"authoritative",
|
|
127
|
+
"cache",
|
|
128
|
+
"advisory"
|
|
129
|
+
]);
|
|
130
|
+
if (!consistencyModels.has(manifest.defaultConsistencyModel)) issues.push({
|
|
131
|
+
path: "defaultConsistencyModel",
|
|
132
|
+
message: "unsupported consistency model"
|
|
133
|
+
});
|
|
134
|
+
validateAuthSpec(manifest.auth, issues);
|
|
135
|
+
const seen = /* @__PURE__ */ new Set();
|
|
136
|
+
for (const [index, capability] of manifest.capabilities.entries()) {
|
|
137
|
+
const path = `capabilities[${index}]`;
|
|
138
|
+
if (!capability.name.trim()) issues.push({
|
|
139
|
+
path: `${path}.name`,
|
|
140
|
+
message: "capability name is required"
|
|
141
|
+
});
|
|
142
|
+
if (seen.has(capability.name)) issues.push({
|
|
143
|
+
path: `${path}.name`,
|
|
144
|
+
message: `duplicate capability name: ${capability.name}`
|
|
145
|
+
});
|
|
146
|
+
seen.add(capability.name);
|
|
147
|
+
if (capability.consistencyModel !== void 0 && !consistencyModels.has(capability.consistencyModel)) issues.push({
|
|
148
|
+
path: `${path}.consistencyModel`,
|
|
149
|
+
message: "unsupported consistency model"
|
|
150
|
+
});
|
|
151
|
+
if (capability.class === "mutation") {
|
|
152
|
+
if (!capability.cas) issues.push({
|
|
153
|
+
path: `${path}.cas`,
|
|
154
|
+
message: "mutation capability must declare a CAS strategy"
|
|
155
|
+
});
|
|
156
|
+
if ((capability.consistencyModel ?? manifest.defaultConsistencyModel) === "authoritative" && capability.cas === "none") issues.push({
|
|
157
|
+
path: `${path}.cas`,
|
|
158
|
+
message: "authoritative mutations cannot use cas=\"none\""
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (manifest.rateLimit) {
|
|
163
|
+
if (!Number.isFinite(manifest.rateLimit.requests) || manifest.rateLimit.requests <= 0) issues.push({
|
|
164
|
+
path: "rateLimit.requests",
|
|
165
|
+
message: "rateLimit.requests must be positive"
|
|
166
|
+
});
|
|
167
|
+
if (!Number.isFinite(manifest.rateLimit.windowMs) || manifest.rateLimit.windowMs <= 0) issues.push({
|
|
168
|
+
path: "rateLimit.windowMs",
|
|
169
|
+
message: "rateLimit.windowMs must be positive"
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
ok: issues.length === 0,
|
|
174
|
+
issues
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function validateAuthSpec(auth, issues) {
|
|
178
|
+
if (auth.kind === "oauth2") {
|
|
179
|
+
validateOAuth2AuthSpec(auth, issues, "auth");
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (auth.kind !== "one_of") return;
|
|
183
|
+
if (auth.options.length < 2) issues.push({
|
|
184
|
+
path: "auth.options",
|
|
185
|
+
message: "one_of auth must declare at least two options"
|
|
186
|
+
});
|
|
187
|
+
if (!new Set(auth.options.map((option) => option.kind)).has(auth.preferred)) issues.push({
|
|
188
|
+
path: "auth.preferred",
|
|
189
|
+
message: "one_of preferred auth must match an option kind"
|
|
190
|
+
});
|
|
191
|
+
for (const [index, option] of auth.options.entries()) if (option.kind === "oauth2") validateOAuth2AuthSpec(option, issues, `auth.options[${index}]`);
|
|
192
|
+
}
|
|
193
|
+
function validateOAuth2AuthSpec(auth, issues, path) {
|
|
194
|
+
if ((auth.grantType ?? "authorization_code") === "authorization_code" && !auth.authorizationUrl?.trim()) issues.push({
|
|
195
|
+
path: `${path}.authorizationUrl`,
|
|
196
|
+
message: "authorization_code grant requires authorizationUrl"
|
|
197
|
+
});
|
|
198
|
+
if (auth.pkce !== void 0 && auth.pkce !== "required" && auth.pkce !== "supported" && auth.pkce !== "unsupported") issues.push({
|
|
199
|
+
path: `${path}.pkce`,
|
|
200
|
+
message: "pkce must be required, supported, or unsupported"
|
|
201
|
+
});
|
|
202
|
+
for (const [key, spec] of Object.entries(auth.urlTemplateMetadata ?? {})) {
|
|
203
|
+
if (spec.kind !== "base-url" && spec.kind !== "path-segment") {
|
|
204
|
+
issues.push({
|
|
205
|
+
path: `${path}.urlTemplateMetadata.${key}.kind`,
|
|
206
|
+
message: "OAuth URL metadata kind must be base-url or path-segment"
|
|
207
|
+
});
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const placeholder = `{${key}}`;
|
|
211
|
+
if (!auth.authorizationUrl?.includes(placeholder) && !auth.tokenUrl.includes(placeholder)) issues.push({
|
|
212
|
+
path: `${path}.urlTemplateMetadata.${key}`,
|
|
213
|
+
message: `OAuth URL metadata is unused; add ${placeholder} to an OAuth endpoint`
|
|
214
|
+
});
|
|
215
|
+
if (spec.kind === "base-url") {
|
|
216
|
+
if (!spec.requirePublicHttps && !spec.allowedBaseUrls?.length && !spec.allowedBaseUrlSuffixes?.length) issues.push({
|
|
217
|
+
path: `${path}.urlTemplateMetadata.${key}`,
|
|
218
|
+
message: "OAuth base URL metadata requires an allowlist or public HTTPS policy"
|
|
219
|
+
});
|
|
220
|
+
for (const suffix of spec.allowedBaseUrlSuffixes ?? []) if (!/^\.[a-z0-9.-]+$/i.test(suffix)) issues.push({
|
|
221
|
+
path: `${path}.urlTemplateMetadata.${key}.allowedBaseUrlSuffixes`,
|
|
222
|
+
message: "OAuth base URL hostname suffixes must start with a dot"
|
|
223
|
+
});
|
|
224
|
+
} else for (const endpoint of [auth.authorizationUrl, auth.tokenUrl]) if (endpoint?.includes(placeholder) && !isOAuthPathSegmentPlaceholder(endpoint, placeholder)) issues.push({
|
|
225
|
+
path: `${path}.urlTemplateMetadata.${key}`,
|
|
226
|
+
message: `OAuth path metadata ${placeholder} must occupy a complete URL path segment`
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
if (auth.tokenClientAuthMethod !== void 0 && auth.tokenClientAuthMethod !== "none" && auth.tokenClientAuthMethod !== "client_secret_post" && auth.tokenClientAuthMethod !== "client_secret_basic") issues.push({
|
|
230
|
+
path: `${path}.tokenClientAuthMethod`,
|
|
231
|
+
message: "tokenClientAuthMethod must be none, client_secret_post, or client_secret_basic"
|
|
232
|
+
});
|
|
233
|
+
if ((auth.tokenClientAuthMethod ?? "client_secret_post") !== "none" && !auth.clientSecretEnv?.trim()) issues.push({
|
|
234
|
+
path: `${path}.clientSecretEnv`,
|
|
235
|
+
message: "confidential OAuth clients require clientSecretEnv"
|
|
236
|
+
});
|
|
237
|
+
for (const header of Object.keys(auth.tokenRequestHeaders ?? {})) if (header.toLowerCase() === "authorization" || header.toLowerCase() === "content-type") issues.push({
|
|
238
|
+
path: `${path}.tokenRequestHeaders.${header}`,
|
|
239
|
+
message: "tokenRequestHeaders cannot override Authorization or Content-Type"
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
function isOAuthPathSegmentPlaceholder(template, placeholder) {
|
|
243
|
+
const schemeIndex = template.indexOf("://");
|
|
244
|
+
const rootEnd = schemeIndex >= 0 ? schemeIndex + 3 : template.startsWith("{") ? template.indexOf("}") + 1 : 0;
|
|
245
|
+
const pathStart = template.indexOf("/", rootEnd);
|
|
246
|
+
const queryStart = template.search(/[?#]/);
|
|
247
|
+
let cursor = 0;
|
|
248
|
+
while (true) {
|
|
249
|
+
const index = template.indexOf(placeholder, cursor);
|
|
250
|
+
if (index < 0) return true;
|
|
251
|
+
const end = index + placeholder.length;
|
|
252
|
+
if (pathStart < 0 || index < pathStart || queryStart >= 0 && index >= queryStart || template[index - 1] !== "/" || end < template.length && template[end] !== "/" && template[end] !== "?" && template[end] !== "#") return false;
|
|
253
|
+
cursor = end;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
function assertValidConnectorManifest(manifest) {
|
|
257
|
+
const result = validateConnectorManifest(manifest);
|
|
258
|
+
if (!result.ok) throw new Error(`Invalid connector manifest ${manifest.kind || "<unknown>"}: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);
|
|
259
|
+
}
|
|
260
|
+
//#endregion
|
|
261
|
+
export { ProviderRequestError as a, validateConnectorManifest as c, ProviderRateLimited as i, InvalidCapabilityArgument as n, ResourceContention as o, ProviderConfigError as r, assertValidConnectorManifest as s, CredentialsExpired as t };
|
|
262
|
+
|
|
263
|
+
//# sourceMappingURL=types-BSDXGSi5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-BSDXGSi5.js","names":[],"sources":["../src/connectors/types.ts"],"sourcesContent":["/**\n * Connector primitives — the contract a concrete first-party integration\n * (Google Calendar, HubSpot, Stripe, ...) implements. Lower level than the\n * hub-side `IntegrationProvider` interface from `../index.ts`: a single\n * `IntegrationProvider` typically wraps several connectors (e.g., a\n * \"first-party\" provider that lists all your shipped connectors as a\n * single catalog).\n *\n * Layering:\n *\n * IntegrationHub — vendor-neutral facade (../index.ts)\n * ↓\n * IntegrationProvider — one per gateway or first-party provider\n * ↓\n * ConnectorAdapter (this file) — one per integration (Google Calendar, ...)\n * ↓\n * upstream HTTP API — vendor SDK / fetch / OAuth\n *\n * Three load-bearing decisions encoded here:\n *\n * 1. Capabilities are typed (`read` vs `mutation`). Every mutation MUST\n * declare a CAS strategy. Conflict resolution is the SDK's job, not the\n * connector's. `validateConnectorManifest()` rejects unsafe manifests\n * before a connector is registered.\n *\n * 2. ConsistencyModel pins what the rest of the system can assume:\n * authoritative → the source IS the truth (Calendar, payments)\n * cache → we mirror with TTL and may serve stale (price list)\n * advisory → informational only (FAQ doc)\n * Agent planners can (and should) refuse to promise outcomes based on\n * `cache`/`advisory` data without a live `authoritative` confirmation.\n *\n * 3. Capabilities surface to the calling agent's tool registry by\n * transformation, not by hand-wiring. Adding a connector automatically\n * expands the agent's toolbelt for that specific user without touching\n * the prompt or runner.\n */\n\n/** Minimal JSON-schema shape used for capability arg validation. We\n * intentionally don't pull `@types/json-schema` — most consumers already\n * declare parameters as `Record<string, unknown>` and the\n * shape is whatever the LLM SDK's structured-output expects. Keep the\n * contract loose at the boundary; tighten via runtime zod where needed. */\nexport type CapabilityParameterSchema = Record<string, unknown>\n\n/** What the rest of the system is allowed to assume about freshness. */\nexport type ConsistencyModel = 'authoritative' | 'cache' | 'advisory'\n\n/** Capability classes. `read` is safe to retry; `mutation` must go through\n * MutationGuard (CAS + idempotency). `subscribe` is reserved for future\n * push-driven sources (webhook callbacks) and is not yet wired. */\nexport type CapabilityClass = 'read' | 'mutation' | 'subscribe'\n\n/** Compare-and-swap strategy a mutation uses to detect conflicts. */\nexport type CASStrategy =\n /** Upstream returns an etag/sequence on read, accepts If-Match on write\n * (Google Calendar, GitHub, GDocs revision_id). The connector returns\n * 412 / Precondition Failed on conflict; the SDK maps to ResourceContention. */\n | 'etag-if-match'\n /** Upstream guarantees exactly-once-per-key (Stripe, idempotent webhooks).\n * The SDK passes the idempotency key through; no etag check. */\n | 'native-idempotency'\n /** No upstream concurrency control. Connector MUST do read-then-write\n * and verify nothing changed in-between (best-effort). Suitable only\n * for low-contention single-user resources; rejected for any\n * consistencyModel='authoritative' write that may race. */\n | 'optimistic-read-verify'\n /** Source is not contended (e.g. logging, telemetry). Mutations are\n * fire-and-forget. Marks the capability as not eligible for\n * authoritative writes. */\n | 'none'\n\nexport interface CapabilityRead {\n name: string\n class: 'read'\n description: string\n /** JSON-schema for the tool args the agent passes when invoking. */\n parameters: CapabilityParameterSchema\n /** Override the connector default when this action has a different consistency guarantee. */\n consistencyModel?: ConsistencyModel\n /** Optional: declare which scopes (per the connector manifest) this\n * capability requires. The capability is hidden from the agent's\n * tool registry if the user's grant didn't include them. */\n requiredScopes?: string[]\n}\n\nexport interface CapabilityMutation {\n name: string\n class: 'mutation'\n description: string\n parameters: CapabilityParameterSchema\n /** Override the connector default when this action has a different consistency guarantee. */\n consistencyModel?: ConsistencyModel\n /** Mandatory: how does the connector guarantee at-most-once + conflict-detect? */\n cas: CASStrategy\n /** True for capabilities that affect resources outside the calling user\n * (e.g. booking against a shared calendar, charging a card). The agent's\n * planner treats these specially: requires explicit caller confirmation\n * before the call. */\n externalEffect: boolean\n requiredScopes?: string[]\n}\n\nexport type Capability = CapabilityRead | CapabilityMutation\n\n/** OAuth2 scope catalog the user has granted us, plus arbitrary metadata\n * the connector pinned at connect-time (calendar id, sheet id, webhook\n * url, …). `metadata` MUST NOT contain secrets — those go in the\n * encrypted credentials envelope. */\nexport interface DataSourceMetadata {\n scopes: string[]\n [key: string]: unknown\n}\n\n/** A connected, authenticated, ready-to-call data source for a project.\n * Persistence shape mirrors the product's connection/source row but normalized — the\n * encrypted credentials envelope is decrypted at hand-out time and held\n * in memory only for the duration of the call. */\nexport interface ResolvedDataSource {\n id: string\n projectId: string\n publishedAgentId: string | null\n kind: string\n label: string\n consistencyModel: ConsistencyModel\n scopes: string[]\n metadata: Record<string, unknown>\n /** Unwrapped credentials handed to the connector at call-time. Never\n * persisted in this shape; never logged. */\n credentials: ConnectorCredentials\n status: 'active' | 'revoked' | 'error'\n}\n\n/** Discriminated union of credential shapes. Connectors that need new\n * shapes extend this union — `kind` is sealed via the tagged pattern so\n * TypeScript catches an exhaustiveness gap at compile time. */\nexport type ConnectorCredentials =\n | { kind: 'oauth2'; accessToken: string; refreshToken?: string; expiresAt?: number }\n | { kind: 'api-key'; apiKey: string }\n | { kind: 'custom'; values: Record<string, unknown> }\n | { kind: 'hmac'; secret: string }\n | { kind: 'none' }\n\n/** Result of a read capability invocation. */\nexport interface CapabilityReadResult {\n /** Free-form payload — the connector's data shape. The agent receives\n * this as the tool result; planners consume it via JSON-shape contract\n * declared in the capability's `parameters` (output schema). */\n data: unknown\n /** Optional etag/sequence the caller can reuse for a subsequent CAS\n * mutation. */\n etag?: string\n /** When this read happened (UTC ms since epoch). */\n fetchedAt: number\n}\n\n/** Result of a mutation capability invocation. Either committed (with the\n * resulting etag/sequence so the caller can chain mutations), or\n * contended (the upstream rejected with a state mismatch — the agent\n * should re-read and retry, or surface alternatives to the caller). */\nexport type CapabilityMutationResult =\n | {\n status: 'committed'\n data: unknown\n etagAfter?: string\n committedAt: number\n /** True iff this commit was returned from the idempotency store\n * rather than executed against upstream. The caller can use this\n * to suppress confirmation messages on retry. */\n idempotentReplay: boolean\n }\n | {\n status: 'conflict'\n /** Best-effort alternative options the upstream surfaced (e.g.,\n * next-available calendar slots after a booking conflict). */\n alternatives: unknown[]\n /** The current authoritative state, if the connector could re-read\n * cheaply. */\n currentState?: unknown\n message: string\n }\n | {\n status: 'rate-limited'\n /** Wall-clock ms the caller should wait before retrying. The SDK\n * computes this from the bucket's refill schedule so the agent\n * doesn't have to guess. */\n retryAfterMs: number\n message: string\n }\n\n/** Inputs the SDK passes into the connector's executeRead / executeMutation. */\nexport interface ConnectorInvocation {\n source: ResolvedDataSource\n capabilityName: string\n args: Record<string, unknown>\n /** Idempotency key the caller (or the SDK's defaulting policy) supplied.\n * Always present at the connector boundary — the SDK manufactures one\n * if the agent didn't pass one. */\n idempotencyKey: string\n /** Optional caller-supplied etag the connector should send as If-Match. */\n expectedEtag?: string\n /** Product/session id (if any) for forensic logging. */\n callSessionId?: string\n /** Fired by the adapter when it rotates the credentials mid-call (e.g. an\n * OAuth access token refreshed on expiry). The host re-encrypts +\n * persists the rotated envelope so the next expiry does not force a\n * reconnect. Adapters MUST invoke this with the FULL rotated envelope,\n * not a partial — the previous refresh token is preserved by the caller's\n * refresh logic, not inferred here. */\n onCredentialsRotated?: (\n credentials: ConnectorCredentials,\n ) => Promise<void> | void\n}\n\n/** A single inbound event extracted from a push payload. The webhook\n * receiver persists one `InboundEvent` row per entry the connector returns. */\nexport interface InboundEvent {\n eventType: string\n providerEventId?: string\n payload: Record<string, unknown>\n}\n\n/** Adapter response from an inbound-webhook dispatch. The receiver persists\n * every `events[]` entry, then either honors the connector's `response`\n * override (Slack `url_verification` echo, provider-specific 2xx body) or\n * defaults to `{status: 200, body: {received: true, count: events.length}}`. */\nexport interface EventHandlerResult {\n events: InboundEvent[]\n /** Optional: how to respond to the provider. Stripe wants 200 within\n * 30s; Slack wants the challenge param echoed. */\n response?: { status: number; body: unknown; headers?: Record<string, string> }\n}\n\n/**\n * Connector adapter — one per integration kind. Stateless. The SDK holds\n * the persistence + crypto + mutation-guard concerns; the adapter only\n * knows how to talk to its upstream.\n */\nexport interface ConnectorAdapter {\n /** Manifest entry the registry uses to render UI + validate args. */\n manifest: ConnectorManifest\n /**\n * True when this adapter only receives provider events and must not appear\n * in public connector or action discovery. Hosts can still register it\n * explicitly for their inbound route, which preserves its stable kind id.\n */\n inboundOnly?: boolean\n /** Read invocation. Required when manifest.capabilities contains reads.\n * Should return whatever shape the capability declared\n * in its parameters output schema. */\n executeRead?(inv: ConnectorInvocation): Promise<CapabilityReadResult>\n /** Mutation invocation. Required when manifest.capabilities contains mutations.\n * Throws ResourceContention on a CAS miss; throws\n * any other Error for upstream failures. The MutationGuard wraps this\n * with idempotency-key short-circuit + audit logging — adapters do\n * NOT manage their own dedup. */\n executeMutation?(inv: ConnectorInvocation): Promise<CapabilityMutationResult>\n /** Inbound webhook signature verifier. Called BEFORE handleInboundEvent.\n * MUST use constant-time comparison (`crypto.timingSafeEqual`) for any\n * HMAC check. The receiver returns 401 on `valid=false` without invoking\n * handleInboundEvent. Optional: connectors that don't accept push events\n * omit this method and the receiver returns 405 for the kind. */\n verifySignature?(input: {\n rawBody: string\n headers: Record<string, string | string[] | undefined>\n source: ResolvedDataSource\n }): { valid: boolean; reason?: string }\n /** Inbound webhook dispatch. Called AFTER verifySignature passes. The\n * adapter parses the provider payload and emits zero-or-more\n * `InboundEvent` rows; the receiver persists them as one row each (modulo\n * the (dataSourceId, providerEventId) dedup unique). The optional\n * `response` overrides the receiver's default 200 (Slack `url_verification`\n * needs to echo the challenge in the body to pass Slack's app-config check). */\n handleInboundEvent?(input: {\n source: ResolvedDataSource\n rawBody: string\n headers: Record<string, string | string[] | undefined>\n }): Promise<EventHandlerResult>\n /** OAuth callback handler — exchanges the auth code for tokens, returns\n * the credentials envelope + scopes + metadata. Only present for\n * oauth2-style adapters. */\n exchangeOAuth?(input: {\n code: string\n state: string\n /** Required unless this connector declares PKCE as unsupported. */\n codeVerifier?: string\n redirectUri: string\n }): Promise<{\n credentials: ConnectorCredentials\n scopes: string[]\n metadata: Record<string, unknown>\n }>\n /** Refresh access token. Only required for oauth2 adapters with\n * short-lived access tokens. */\n refreshToken?(input: ConnectorCredentials): Promise<ConnectorCredentials>\n /** Health check — invoked when the user clicks \"Test connection\" in the\n * UI. Should perform the cheapest possible read that proves the grant\n * is still valid. Returns `{ok: false, reason}` rather than throwing\n * for the common case (token expired, scope missing). */\n test(\n source: ResolvedDataSource,\n /** Optional persistence sink for credentials rotated by the health check. */\n onCredentialsRotated?: (\n credentials: ConnectorCredentials,\n ) => Promise<void> | void,\n ): Promise<{ ok: true } | { ok: false; reason: string }>\n}\n\n/** Static manifest a connector module exports. Drives the UI catalog,\n * scope display, capability discovery for the agent's tool registry. */\nexport interface ConnectorManifest {\n /** Stable kind id used as the foreign key in DataSource.kind. */\n kind: string\n /** Human label shown in the UI catalog. */\n displayName: string\n /** One-paragraph description shown next to the connect button. */\n description: string\n /** Auth shape this connector requires. */\n auth: AuthSpec\n /** Capability catalog — the agent's tool registry derives ToolDefinition\n * entries from this list at request time. */\n capabilities: Capability[]\n /** ConsistencyModel default for this kind — overridable per capability and\n * per DataSource when an action or instance has a different guarantee. */\n defaultConsistencyModel: ConsistencyModel\n /** Connector category for UI grouping. */\n category:\n | 'calendar'\n | 'spreadsheet'\n | 'crm'\n | 'doc'\n | 'webhook'\n | 'storage'\n | 'comms'\n | 'commerce'\n | 'database'\n | 'sales-intelligence'\n | 'market-intelligence'\n | 'hr'\n | 'other'\n /** Optional icon URL or named icon. */\n icon?: string\n /** Optional per-kind rate-limit budget. The SDK enforces it inside\n * `executeGuardedMutation` and the read path of `/invoke`. Omit to\n * leave the connector unrestricted. */\n rateLimit?: RateLimitSpec\n}\n\n/** Token-bucket budget the SDK enforces against the connector's upstream.\n * We meter on OUR side rather than letting the upstream reject so a\n * chatty agent can't burn quota that's shared across customers (almost\n * every OAuth client is). */\nexport interface RateLimitSpec {\n /** Max requests per window. */\n requests: number\n /** Window in ms. */\n windowMs: number\n /** Whether to apply across all DataSources sharing the same OAuth\n * client (true; default), or per-DataSource (false). The former\n * matches how upstreams meter (per-app), so almost always pick true. */\n scope?: 'oauth-client' | 'data-source'\n}\n\n/** Source mapping for `OAuth2AuthSpec.tokenMetadata`. A bare string names the\n * token-response field to capture (capture-if-present). The object form marks\n * the field `required` so a missing/empty value fails the token exchange loud\n * rather than silently capturing nothing. */\nexport type TokenMetadataSource = string | { field: string; required?: boolean }\n\n/** How an OAuth token endpoint authenticates this client.\n *\n * Public clients use `none` and send only the client id. OAuth providers\n * otherwise default to `client_secret_post`, which sends both values in the\n * form body. `client_secret_basic` sends an HTTP Basic header instead. */\nexport type OAuth2TokenClientAuthMethod =\n | 'none'\n | 'client_secret_post'\n | 'client_secret_basic'\n\nexport type OAuth2UrlTemplateMetadataSpec =\n | {\n /** A complete HTTPS provider base URL, substituted for a URL template\n * placeholder such as `{accountUrl}`. */\n kind: 'base-url'\n /** Exact provider roots accepted for finite regional endpoint sets. */\n allowedBaseUrls?: readonly string[]\n /** HTTPS hostname suffixes accepted for tenant-specific provider roots. */\n allowedBaseUrlSuffixes?: readonly string[]\n /** Permit a caller-selected public HTTPS root for self-hosted providers. */\n requirePublicHttps?: boolean\n }\n | {\n /** One RFC 3986 unreserved path segment. The resolver encodes it and\n * rejects separators, dot segments, query data, and fragments. */\n kind: 'path-segment'\n }\n\ntype OAuth2AuthSpec = {\n kind: 'oauth2'\n /** OAuth2 grant type. Defaults to `'authorization_code'` (the interactive\n * 3-legged flow). Set `'client_credentials'` for machine-to-machine\n * providers (e.g. Paychex) that issue tokens directly from client\n * id/secret with no user-facing authorization step — `authorizationUrl`\n * is then omitted. */\n grantType?: 'authorization_code' | 'client_credentials'\n /** Authorization endpoint URL. Required for the `authorization_code`\n * grant; omitted for `client_credentials` (there is no authorize step). */\n authorizationUrl?: string\n /** Token endpoint URL. */\n tokenUrl: string\n /** Scopes requested in the authorization grant. The user UI shows\n * these so the customer knows what's being shared. */\n scopes: string[]\n /** Separator used when serializing multiple scopes into the authorization\n * URL. OAuth defaults to spaces; Zoho requires comma-delimited scopes. */\n scopeSeparator?: ' ' | ','\n /** Provider PKCE posture. Defaults to the host flow policy when omitted. */\n pkce?: 'required' | 'supported' | 'unsupported'\n /** Query parameter that receives the OAuth client id on the authorization\n * URL. Defaults to `client_id`; TikTok calls this value `client_key`. */\n authorizationClientIdParam?: string\n /** Whether the connector supports incremental authorization (Google\n * does; many don't). */\n incremental?: boolean\n /** Env-var name holding the OAuth client_id. */\n clientIdEnv: string\n /** Env-var name holding the OAuth client_secret. Omit only for public\n * clients whose tokenClientAuthMethod is `none`. */\n clientSecretEnv?: string\n /** Form parameter that receives the client id during token exchange.\n * Defaults to `client_id`; TikTok calls this value `client_key`. */\n tokenClientIdParam?: string\n /** Form parameter that receives the client secret during token exchange.\n * Defaults to `client_secret`. */\n tokenClientSecretParam?: string\n /** OAuth client authentication for the authorization-code token exchange.\n * Defaults to `client_secret_post` for backward compatibility. */\n tokenClientAuthMethod?: OAuth2TokenClientAuthMethod\n /** Optional extra params attached to the authorization URL (e.g.,\n * Google's `access_type=offline&prompt=consent` to obtain refresh\n * tokens). */\n extraAuthParams?: Record<string, string>\n /** Rules for metadata placeholders that represent provider roots or path\n * segments. Placeholders without a rule remain single DNS labels. */\n urlTemplateMetadata?: Readonly<Record<string, OAuth2UrlTemplateMetadataSpec>>\n /** Non-secret headers sent to the token endpoint. Use this for provider\n * identification headers such as Reddit's required User-Agent. The runtime\n * always owns Authorization and Content-Type. */\n tokenRequestHeaders?: Record<string, string>\n /** Whether to send the `scope` query param on the authorization URL.\n * Defaults to true. Set false for providers that reject a per-request\n * scope and pin scopes app-side (e.g. HelloSign/Dropbox Sign). */\n sendScopeParam?: boolean\n /** Declarative capture of provider-specific fields from the OAuth token\n * response into the connection's `metadata`, keyed by the connection-metadata\n * key to write → the token-response field to read. The counterpart to\n * `baseUrl.metadataKey`: providers like Gong return a per-customer host\n * (`api_base_url_for_customer`) at token exchange that every later call must\n * target, but the standard token parser keeps only the canonical OAuth\n * fields and drops the rest. Declaring the mapping here makes `completeAuth`\n * persist the value into `metadata` so `baseUrl` resolution finds it. Mark a\n * field `required` to fail the exchange loud when it is absent (surfacing the\n * break at connect, not first call). Optional and backward-compatible —\n * connectors that omit it are unaffected. */\n tokenMetadata?: Record<string, TokenMetadataSource>\n}\ntype ApiKeyAuthSpec = {\n kind: 'api-key'\n /** UI hint shown when collecting the key. */\n hint: string\n}\ntype SingleAuthSpec = OAuth2AuthSpec | ApiKeyAuthSpec | { kind: 'hmac' } | { kind: 'none' }\n\nexport type AuthSpec =\n | SingleAuthSpec\n | {\n kind: 'one_of'\n /** Preferred auth kind for setup UI and OAuth-connect flows. */\n preferred: 'oauth2' | 'api-key'\n /** Explicit supported auth modes. Do not infer fallback modes. */\n options: readonly [SingleAuthSpec, SingleAuthSpec, ...SingleAuthSpec[]]\n }\n\n/** Thrown by `executeMutation` when upstream rejects on CAS — caught and\n * rewrapped by MutationGuard. */\nexport class ResourceContention extends Error {\n override readonly name = 'ResourceContention'\n constructor(\n message: string,\n public readonly alternatives: unknown[] = [],\n public readonly currentState?: unknown,\n ) {\n super(message)\n }\n}\n\n/** Structured HTTP failure detail attached to the typed provider errors below.\n * The platform classifier reads `status`/`reason` off the thrown instance to\n * route a 403 by WHY it failed (credential vs config/permission vs quota)\n * instead of regexing a flattened message. */\nexport interface ProviderHttpErrorInit {\n /** Upstream HTTP status (e.g. 401, 403, 429). */\n status: number\n /** Provider-specific machine reason (e.g. Google's `accessNotConfigured`,\n * `dailyLimitExceeded`, `invalid_grant`) — the actionable signal. */\n reason?: string\n /** Parsed upstream error body, kept for diagnostics/audit. */\n body?: unknown\n}\n\n/** Thrown when the connector finds the user's grant has been revoked or the\n * access token is no longer valid AND refresh failed — reconnecting fixes it.\n * Surfaces to the UI as \"Reconnect required\". Carries optional structured\n * `{status, reason, body}` so the platform can confirm a 401/403 really is a\n * credential reason before flipping the connection to reconnect_required. */\nexport class CredentialsExpired extends Error {\n override readonly name = 'CredentialsExpired'\n readonly status?: number\n readonly reason?: string\n readonly body?: unknown\n constructor(\n message: string,\n public readonly dataSourceId: string,\n init?: ProviderHttpErrorInit,\n ) {\n super(message)\n this.status = init?.status\n this.reason = init?.reason\n this.body = init?.body\n }\n}\n\n/** Thrown when the provider rejects the call for a configuration or permission\n * reason that reconnecting the credential CANNOT fix — the API isn't enabled\n * for the project (`accessNotConfigured`), a required scope is missing\n * (`insufficientPermissions`), or the resource is forbidden\n * (`PERMISSION_DENIED`). Distinct from CredentialsExpired so the platform\n * surfaces \"fix the project/scope\" instead of sending the user into an\n * unresolvable reconnect loop. */\nexport class ProviderConfigError extends Error {\n override readonly name = 'ProviderConfigError'\n readonly status: number\n readonly reason?: string\n readonly body?: unknown\n constructor(\n message: string,\n public readonly dataSourceId: string,\n init: ProviderHttpErrorInit,\n ) {\n super(message)\n this.status = init.status\n this.reason = init.reason\n this.body = init.body\n }\n}\n\nexport interface ProviderRateLimitedInit extends ProviderHttpErrorInit {\n /** Wall-clock ms the caller should wait before retrying — resolved from the\n * provider's `Retry-After` when one was sent. */\n retryAfterMs?: number\n}\n\n/** Thrown when the provider throttles the call (quota / rate limit). Gmail and\n * Calendar surface daily/per-user limits as HTTP 403 with a quota `reason`\n * (`rateLimitExceeded`/`dailyLimitExceeded`/`userRateLimitExceeded`), NOT 429\n * — so it is classified by reason, not status, and must never read as a\n * credential failure. The message includes \"rate limit\" so a platform that\n * only inspects the message still routes it to rate-limited. */\nexport class ProviderRateLimited extends Error {\n override readonly name = 'ProviderRateLimited'\n readonly status: number\n readonly reason?: string\n readonly body?: unknown\n readonly retryAfterMs?: number\n constructor(\n message: string,\n public readonly dataSourceId: string,\n init: ProviderRateLimitedInit,\n ) {\n super(message)\n this.status = init.status\n this.reason = init.reason\n this.body = init.body\n this.retryAfterMs = init.retryAfterMs\n }\n}\n\n/** Thrown when the provider settles a call with a non-2xx status that is not\n * a credential, permission or rate-limit failure: a 400 naming a bad field, a\n * 404, a 409, or a 5xx. Carries `{status, reason, body}` so the platform\n * answers a refusal as a refusal (a 4xx with the provider's message) instead\n * of a gateway fault, and keeps the provider's own error code as `reason`. */\nexport class ProviderRequestError extends Error {\n override readonly name = 'ProviderRequestError'\n readonly status: number\n readonly reason?: string\n readonly body?: unknown\n constructor(\n message: string,\n public readonly dataSourceId: string,\n init: ProviderHttpErrorInit,\n ) {\n super(message)\n this.status = init.status\n this.reason = init.reason\n this.body = init.body\n }\n}\n\n/** Thrown before any provider request when a caller's argument breaks the\n * capability's declared contract: a value that fails its `pattern`, or one the\n * provider would refuse with a misleading answer (a commit sha where a branch\n * name belongs reads back as \"Branch not found\"). `field` names the argument,\n * and the message says what to pass instead. `status` is 400 so a platform\n * classifier answers it as a settled refusal: the same arguments fail again. */\nexport class InvalidCapabilityArgument extends Error {\n override readonly name = 'InvalidCapabilityArgument'\n readonly status = 400\n readonly reason = 'invalid_argument'\n constructor(\n message: string,\n public readonly field: string,\n ) {\n super(message)\n }\n}\n\nexport interface ConnectorManifestValidationIssue {\n path: string\n message: string\n}\n\nexport interface ConnectorManifestValidationResult {\n ok: boolean\n issues: ConnectorManifestValidationIssue[]\n}\n\n/** Validate the static connector manifest before a provider registers it.\n * This catches the expensive mistakes early: duplicate capability names,\n * mutation capabilities without CAS, authoritative fire-and-forget writes,\n * and invalid rate-limit specs. */\nexport function validateConnectorManifest(manifest: ConnectorManifest): ConnectorManifestValidationResult {\n const issues: ConnectorManifestValidationIssue[] = []\n if (!manifest.kind.trim()) issues.push({ path: 'kind', message: 'kind is required' })\n if (!manifest.displayName.trim()) issues.push({ path: 'displayName', message: 'displayName is required' })\n const consistencyModels = new Set<ConsistencyModel>(['authoritative', 'cache', 'advisory'])\n if (!consistencyModels.has(manifest.defaultConsistencyModel)) {\n issues.push({ path: 'defaultConsistencyModel', message: 'unsupported consistency model' })\n }\n validateAuthSpec(manifest.auth, issues)\n const seen = new Set<string>()\n for (const [index, capability] of manifest.capabilities.entries()) {\n const path = `capabilities[${index}]`\n if (!capability.name.trim()) issues.push({ path: `${path}.name`, message: 'capability name is required' })\n if (seen.has(capability.name)) issues.push({ path: `${path}.name`, message: `duplicate capability name: ${capability.name}` })\n seen.add(capability.name)\n if (capability.consistencyModel !== undefined && !consistencyModels.has(capability.consistencyModel)) {\n issues.push({ path: `${path}.consistencyModel`, message: 'unsupported consistency model' })\n }\n if (capability.class === 'mutation') {\n if (!capability.cas) issues.push({ path: `${path}.cas`, message: 'mutation capability must declare a CAS strategy' })\n if ((capability.consistencyModel ?? manifest.defaultConsistencyModel) === 'authoritative' && capability.cas === 'none') {\n issues.push({ path: `${path}.cas`, message: 'authoritative mutations cannot use cas=\"none\"' })\n }\n }\n }\n if (manifest.rateLimit) {\n if (!Number.isFinite(manifest.rateLimit.requests) || manifest.rateLimit.requests <= 0) {\n issues.push({ path: 'rateLimit.requests', message: 'rateLimit.requests must be positive' })\n }\n if (!Number.isFinite(manifest.rateLimit.windowMs) || manifest.rateLimit.windowMs <= 0) {\n issues.push({ path: 'rateLimit.windowMs', message: 'rateLimit.windowMs must be positive' })\n }\n }\n return { ok: issues.length === 0, issues }\n}\n\nfunction validateAuthSpec(auth: AuthSpec, issues: ConnectorManifestValidationIssue[]): void {\n if (auth.kind === 'oauth2') {\n validateOAuth2AuthSpec(auth, issues, 'auth')\n return\n }\n if (auth.kind !== 'one_of') return\n if (auth.options.length < 2) {\n issues.push({ path: 'auth.options', message: 'one_of auth must declare at least two options' })\n }\n const optionKinds = new Set(auth.options.map((option) => option.kind))\n if (!optionKinds.has(auth.preferred)) {\n issues.push({ path: 'auth.preferred', message: 'one_of preferred auth must match an option kind' })\n }\n for (const [index, option] of auth.options.entries()) {\n if (option.kind === 'oauth2') {\n validateOAuth2AuthSpec(option, issues, `auth.options[${index}]`)\n }\n }\n}\n\nfunction validateOAuth2AuthSpec(\n auth: OAuth2AuthSpec,\n issues: ConnectorManifestValidationIssue[],\n path: string,\n): void {\n if ((auth.grantType ?? 'authorization_code') === 'authorization_code' && !auth.authorizationUrl?.trim()) {\n issues.push({ path: `${path}.authorizationUrl`, message: 'authorization_code grant requires authorizationUrl' })\n }\n if (\n auth.pkce !== undefined &&\n auth.pkce !== 'required' &&\n auth.pkce !== 'supported' &&\n auth.pkce !== 'unsupported'\n ) {\n issues.push({\n path: `${path}.pkce`,\n message: 'pkce must be required, supported, or unsupported',\n })\n }\n for (const [key, spec] of Object.entries(auth.urlTemplateMetadata ?? {})) {\n if (spec.kind !== 'base-url' && spec.kind !== 'path-segment') {\n issues.push({\n path: `${path}.urlTemplateMetadata.${key}.kind`,\n message: 'OAuth URL metadata kind must be base-url or path-segment',\n })\n continue\n }\n const placeholder = `{${key}}`\n if (!auth.authorizationUrl?.includes(placeholder) && !auth.tokenUrl.includes(placeholder)) {\n issues.push({\n path: `${path}.urlTemplateMetadata.${key}`,\n message: `OAuth URL metadata is unused; add ${placeholder} to an OAuth endpoint`,\n })\n }\n if (spec.kind === 'base-url') {\n if (\n !spec.requirePublicHttps &&\n !spec.allowedBaseUrls?.length &&\n !spec.allowedBaseUrlSuffixes?.length\n ) {\n issues.push({\n path: `${path}.urlTemplateMetadata.${key}`,\n message: 'OAuth base URL metadata requires an allowlist or public HTTPS policy',\n })\n }\n for (const suffix of spec.allowedBaseUrlSuffixes ?? []) {\n if (!/^\\.[a-z0-9.-]+$/i.test(suffix)) {\n issues.push({\n path: `${path}.urlTemplateMetadata.${key}.allowedBaseUrlSuffixes`,\n message: 'OAuth base URL hostname suffixes must start with a dot',\n })\n }\n }\n } else {\n for (const endpoint of [auth.authorizationUrl, auth.tokenUrl]) {\n if (\n endpoint?.includes(placeholder) &&\n !isOAuthPathSegmentPlaceholder(endpoint, placeholder)\n ) {\n issues.push({\n path: `${path}.urlTemplateMetadata.${key}`,\n message: `OAuth path metadata ${placeholder} must occupy a complete URL path segment`,\n })\n }\n }\n }\n }\n if (\n auth.tokenClientAuthMethod !== undefined &&\n auth.tokenClientAuthMethod !== 'none' &&\n auth.tokenClientAuthMethod !== 'client_secret_post' &&\n auth.tokenClientAuthMethod !== 'client_secret_basic'\n ) {\n issues.push({\n path: `${path}.tokenClientAuthMethod`,\n message: 'tokenClientAuthMethod must be none, client_secret_post, or client_secret_basic',\n })\n }\n if (\n (auth.tokenClientAuthMethod ?? 'client_secret_post') !== 'none' &&\n !auth.clientSecretEnv?.trim()\n ) {\n issues.push({\n path: `${path}.clientSecretEnv`,\n message: 'confidential OAuth clients require clientSecretEnv',\n })\n }\n for (const header of Object.keys(auth.tokenRequestHeaders ?? {})) {\n if (header.toLowerCase() === 'authorization' || header.toLowerCase() === 'content-type') {\n issues.push({\n path: `${path}.tokenRequestHeaders.${header}`,\n message: 'tokenRequestHeaders cannot override Authorization or Content-Type',\n })\n }\n }\n}\n\nfunction isOAuthPathSegmentPlaceholder(template: string, placeholder: string): boolean {\n const schemeIndex = template.indexOf('://')\n const rootEnd = schemeIndex >= 0\n ? schemeIndex + 3\n : template.startsWith('{')\n ? template.indexOf('}') + 1\n : 0\n const pathStart = template.indexOf('/', rootEnd)\n const queryStart = template.search(/[?#]/)\n let cursor = 0\n while (true) {\n const index = template.indexOf(placeholder, cursor)\n if (index < 0) return true\n const end = index + placeholder.length\n if (\n pathStart < 0 ||\n index < pathStart ||\n (queryStart >= 0 && index >= queryStart) ||\n template[index - 1] !== '/' ||\n (end < template.length && template[end] !== '/' && template[end] !== '?' && template[end] !== '#')\n ) {\n return false\n }\n cursor = end\n }\n}\n\nexport function assertValidConnectorManifest(manifest: ConnectorManifest): void {\n const result = validateConnectorManifest(manifest)\n if (!result.ok) {\n throw new Error(`Invalid connector manifest ${manifest.kind || '<unknown>'}: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)\n }\n}\n"],"mappings":";;;AAqeA,IAAa,qBAAb,cAAwC,MAAM;CAI1B;CACA;CAJlB,OAAyB;CACzB,YACE,SACA,eAA0C,CAAC,GAC3C,cACA;EACA,MAAM,OAAO;EAHG,KAAA,eAAA;EACA,KAAA,eAAA;CAGlB;AACF;;;;;;AAqBA,IAAa,qBAAb,cAAwC,MAAM;C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S,8BAA8B,UAAkB,aAA8B;CACrF,MAAM,cAAc,SAAS,QAAQ,KAAK;CAC1C,MAAM,UAAU,eAAe,IAC3B,cAAc,IACd,SAAS,WAAW,GAAG,IACrB,SAAS,QAAQ,GAAG,IAAI,IACxB;CACN,MAAM,YAAY,SAAS,QAAQ,KAAK,OAAO;CAC/C,MAAM,aAAa,SAAS,OAAO,MAAM;CACzC,IAAI,SAAS;CACb,OAAO,MAAM;EACX,MAAM,QAAQ,SAAS,QAAQ,aAAa,MAAM;EAClD,IAAI,QAAQ,GAAG,OAAO;EACtB,MAAM,MAAM,QAAQ,YAAY;EAChC,IACE,YAAY,KACZ,QAAQ,aACP,cAAc,KAAK,SAAS,cAC7B,SAAS,QAAQ,OAAO,OACvB,MAAM,SAAS,UAAU,SAAS,SAAS,OAAO,SAAS,SAAS,OAAO,SAAS,SAAS,KAE9F,OAAO;EAET,SAAS;CACX;AACF;AAEA,SAAgB,6BAA6B,UAAmC;CAC9E,MAAM,SAAS,0BAA0B,QAAQ;CACjD,IAAI,CAAC,OAAO,IACV,MAAM,IAAI,MAAM,8BAA8B,SAAS,QAAQ,YAAY,IAAI,OAAO,OAAO,KAAK,UAAU,GAAG,MAAM,KAAK,IAAI,MAAM,SAAS,CAAC,CAAC,KAAK,IAAI,GAAG;AAE/J"}
|
package/dist/webhooks/index.d.ts
CHANGED
|
@@ -111,5 +111,10 @@ export declare function createWhatsappWebhookProvider(options: {
|
|
|
111
111
|
phoneNumberId: string;
|
|
112
112
|
}): WebhookProvider;
|
|
113
113
|
//#endregion
|
|
114
|
+
//#region src/webhooks/cloudbeds.d.ts
|
|
115
|
+
/** Header name to pass as `authHeaderName` to `webhooks.subscribe`. */
|
|
116
|
+
export declare const CLOUDBEDS_WEBHOOK_AUTH_HEADER = "x-tangle-webhook-token";
|
|
117
|
+
export declare const cloudbedsWebhookProvider: WebhookProvider;
|
|
118
|
+
//#endregion
|
|
114
119
|
export { FileSystemWebhookIdempotencyStore, InMemoryWebhookIdempotencyStore, type InboundEmailPayload, SignatureVerification, TriggerEventCatalog, TriggerEventDescriptor, WebhookEnvelope, WebhookHeaders, WebhookIdempotencyStore, WebhookProvider, WebhookRouter, WebhookRouterOptions, WebhookRouterRequest, WebhookRouterResponse };
|
|
115
120
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/webhooks/providers.ts","../../src/webhooks/twilio.ts","../../src/webhooks/messaging.ts","../../src/webhooks/whatsapp.ts"],"mappings":";;;;qBA2Ba,uBAAuB;;;;;;;;;;;;wBAyDpB,uBAAuB;EAAoB;;qBAO9C,sBAAsB;qBAgEtB,sBAAsB;qBAwDtB,yBAAyB;;;;;;qBA+CzB,sBAAsB;;;;;;;qBAyCtB,sBAAsB;;;;qBAwCtB,uBAAuB;;;;;qBAoEvB,yBAAyB;;;;;;qBAuCzB,0BAA0B;;;;;;;;;;qBAgF1B,qBAAqB;;;;wBAgGlB,2BAA2B;EACzC;EACA;EACA;EACA;;;EAGA,QAAQ;IACN;;;;wBClnBY,4BAA4B;EAC1C;EACA;EACA;EACA;IACE;;wBA+BY,+BAA+B;EAC7C;EACA;EACA;IACE;;;;wBCzBY,oBAAoB,iBAAiB,SAAS,gBAAgB,gBAAgB;;wBAyB9E,kBAAkB,iBAAiB,SAAS,gBAAgB,gBAAgB;;wBAK5E,oBAAoB,iBAAiB,SAAS,gBAAgB,gBAAgB;qBAoBjF,uBAAuB;qBAUvB,qBAAqB;qBAarB,2BAA2B;qBAc3B,6BAA6B;qBAY7B,uBAAuB;;qBAoBvB,yBAAyB;;;YCvI1B;;;wBAMI,8BAA8B;EAC5C,YAAY;EACZ;EACA;IACE"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/webhooks/providers.ts","../../src/webhooks/twilio.ts","../../src/webhooks/messaging.ts","../../src/webhooks/whatsapp.ts","../../src/webhooks/cloudbeds.ts"],"mappings":";;;;qBA2Ba,uBAAuB;;;;;;;;;;;;wBAyDpB,uBAAuB;EAAoB;;qBAO9C,sBAAsB;qBAgEtB,sBAAsB;qBAwDtB,yBAAyB;;;;;;qBA+CzB,sBAAsB;;;;;;;qBAyCtB,sBAAsB;;;;qBAwCtB,uBAAuB;;;;;qBAoEvB,yBAAyB;;;;;;qBAuCzB,0BAA0B;;;;;;;;;;qBAgF1B,qBAAqB;;;;wBAgGlB,2BAA2B;EACzC;EACA;EACA;EACA;;;EAGA,QAAQ;IACN;;;;wBClnBY,4BAA4B;EAC1C;EACA;EACA;EACA;IACE;;wBA+BY,+BAA+B;EAC7C;EACA;EACA;IACE;;;;wBCzBY,oBAAoB,iBAAiB,SAAS,gBAAgB,gBAAgB;;wBAyB9E,kBAAkB,iBAAiB,SAAS,gBAAgB,gBAAgB;;wBAK5E,oBAAoB,iBAAiB,SAAS,gBAAgB,gBAAgB;qBAoBjF,uBAAuB;qBAUvB,qBAAqB;qBAarB,2BAA2B;qBAc3B,6BAA6B;qBAY7B,uBAAuB;;qBAoBvB,yBAAyB;;;YCvI1B;;;wBAMI,8BAA8B;EAC5C,YAAY;EACZ;EACA;IACE;;;;qBCQS;qBAoBA,0BAA0B"}
|
package/dist/webhooks/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { FileSystemAtomicIdempotencyStore, InMemoryAtomicIdempotencyStore, resolveAtomicIdempotencyStore } from "../idempotency.js";
|
|
2
|
-
import {
|
|
2
|
+
import { c as verifySlackSignature, i as firstHeader, l as verifyStripeSignature, o as verifyEmailSignature, s as verifyHmacSignature, t as CLOUDBEDS_WEBHOOK_EVENTS } from "../cloudbeds-BL5EF3xl.js";
|
|
3
3
|
import { authenticateTwilioForm } from "../twilio/index.js";
|
|
4
4
|
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
5
5
|
//#region src/webhooks/router.ts
|
|
@@ -1199,6 +1199,96 @@ function createWhatsappWebhookProvider(options) {
|
|
|
1199
1199
|
};
|
|
1200
1200
|
}
|
|
1201
1201
|
//#endregion
|
|
1202
|
-
|
|
1202
|
+
//#region src/webhooks/cloudbeds.ts
|
|
1203
|
+
/**
|
|
1204
|
+
* Cloudbeds PMS webhook provider.
|
|
1205
|
+
*
|
|
1206
|
+
* Cloudbeds does not sign webhook bodies. `postWebhook` accepts an
|
|
1207
|
+
* `authHeaderName`/`authHeaderValue` pair, sends that header on every delivery,
|
|
1208
|
+
* never returns the value from `getWebhooks`, and rotates it on re-post
|
|
1209
|
+
* (pms-v1.3 PostWebhookRequest). Subscribe with `authHeaderName` set to
|
|
1210
|
+
* `CLOUDBEDS_WEBHOOK_AUTH_HEADER` and a per-connection secret as the value; the
|
|
1211
|
+
* verifier compares that header with the secret in constant time.
|
|
1212
|
+
*
|
|
1213
|
+
* The header proves the delivery came from a subscription holding the secret,
|
|
1214
|
+
* but it does not bind the body. Every envelope is a hint: consumers re-read the
|
|
1215
|
+
* reservation through `reservations.get` before acting on it.
|
|
1216
|
+
*/
|
|
1217
|
+
/** Header name to pass as `authHeaderName` to `webhooks.subscribe`. */
|
|
1218
|
+
const CLOUDBEDS_WEBHOOK_AUTH_HEADER = "x-tangle-webhook-token";
|
|
1219
|
+
const EVENTS = new Set(CLOUDBEDS_WEBHOOK_EVENTS.map(({ object, action }) => `${object}/${action}`));
|
|
1220
|
+
const NUMERIC_ID = /^[1-9]\d{0,19}$/;
|
|
1221
|
+
const RESERVATION_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
1222
|
+
function idText(value, pattern) {
|
|
1223
|
+
const text = typeof value === "number" && Number.isSafeInteger(value) ? String(value) : value;
|
|
1224
|
+
return typeof text === "string" && pattern.test(text) ? text : null;
|
|
1225
|
+
}
|
|
1226
|
+
function headersOf(headers) {
|
|
1227
|
+
const out = {};
|
|
1228
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
1229
|
+
if (value === void 0 || key.toLowerCase() === "x-tangle-webhook-token") continue;
|
|
1230
|
+
out[key.toLowerCase()] = Array.isArray(value) ? value.join(", ") : value;
|
|
1231
|
+
}
|
|
1232
|
+
return out;
|
|
1233
|
+
}
|
|
1234
|
+
const cloudbedsWebhookProvider = {
|
|
1235
|
+
id: "cloudbeds",
|
|
1236
|
+
verifySignature({ headers, secret }) {
|
|
1237
|
+
const token = firstHeader(headers, CLOUDBEDS_WEBHOOK_AUTH_HEADER);
|
|
1238
|
+
if (!token) return {
|
|
1239
|
+
valid: false,
|
|
1240
|
+
reason: "missing_cloudbeds_webhook_token"
|
|
1241
|
+
};
|
|
1242
|
+
if (!secret) return {
|
|
1243
|
+
valid: false,
|
|
1244
|
+
reason: "missing_secret"
|
|
1245
|
+
};
|
|
1246
|
+
const actual = Buffer.from(token, "utf-8");
|
|
1247
|
+
const expected = Buffer.from(secret, "utf-8");
|
|
1248
|
+
if (actual.length !== expected.length) return {
|
|
1249
|
+
valid: false,
|
|
1250
|
+
reason: "invalid_webhook_token"
|
|
1251
|
+
};
|
|
1252
|
+
return timingSafeEqual(actual, expected) ? { valid: true } : {
|
|
1253
|
+
valid: false,
|
|
1254
|
+
reason: "invalid_webhook_token"
|
|
1255
|
+
};
|
|
1256
|
+
},
|
|
1257
|
+
parse({ rawBody, headers, now }) {
|
|
1258
|
+
let body;
|
|
1259
|
+
try {
|
|
1260
|
+
body = JSON.parse(rawBody);
|
|
1261
|
+
} catch {
|
|
1262
|
+
throw new Error("cloudbeds webhook body is not JSON");
|
|
1263
|
+
}
|
|
1264
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("cloudbeds webhook body is not an object");
|
|
1265
|
+
const evt = body;
|
|
1266
|
+
if (typeof evt.event !== "string" || !EVENTS.has(evt.event)) return [];
|
|
1267
|
+
const propertyId = idText(evt.propertyID, NUMERIC_ID) ?? idText(evt.propertyID_str, NUMERIC_ID) ?? idText(evt.propertyId, NUMERIC_ID) ?? idText(evt.propertyId_str, NUMERIC_ID);
|
|
1268
|
+
const reservationId = idText(evt.reservationID, RESERVATION_ID) ?? idText(evt.reservationId, RESERVATION_ID);
|
|
1269
|
+
if (!propertyId || !reservationId) throw new Error("cloudbeds webhook is missing propertyId or reservationId");
|
|
1270
|
+
const timestamp = typeof evt.timestamp === "number" || typeof evt.timestamp === "string" ? String(evt.timestamp) : "";
|
|
1271
|
+
const [object, action] = evt.event.split("/");
|
|
1272
|
+
return [{
|
|
1273
|
+
provider: "cloudbeds",
|
|
1274
|
+
eventType: `cloudbeds.${object}.${action}`,
|
|
1275
|
+
providerEventId: createHash("sha256").update(`${evt.event}|${propertyId}|${reservationId}|${timestamp}`).digest("hex"),
|
|
1276
|
+
receivedAt: now ?? Date.now(),
|
|
1277
|
+
payload: {
|
|
1278
|
+
...evt,
|
|
1279
|
+
propertyId,
|
|
1280
|
+
reservationId
|
|
1281
|
+
},
|
|
1282
|
+
headers: headersOf(headers)
|
|
1283
|
+
}];
|
|
1284
|
+
},
|
|
1285
|
+
eventCatalog: {
|
|
1286
|
+
namespace: "cloudbeds.",
|
|
1287
|
+
closed: true,
|
|
1288
|
+
events: CLOUDBEDS_WEBHOOK_EVENTS.map(({ object, action }) => ({ id: `cloudbeds.${object}.${action}` }))
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
//#endregion
|
|
1292
|
+
export { CLOUDBEDS_WEBHOOK_AUTH_HEADER, FileSystemWebhookIdempotencyStore, InMemoryWebhookIdempotencyStore, WebhookRouter, clayWebhookProvider, clerkWebhookProvider, cloudbedsWebhookProvider, contiguityWebhookProvider, createTwilioSmsWebhookProvider, createTwilioWebhookProvider, createWhatsappWebhookProvider, docusealWebhookProvider, emailWebhookProvider, gdriveWebhookProvider, genericHmacWebhookProvider, gmailWebhookProvider, hellosignWebhookProvider, inkboxWebhookProvider, linqWebhookProvider, linqWhatsappWebhookProvider, resendWebhookProvider, sendblueWebhookProvider, slackHandshakeResponse, slackWebhookProvider, stripeWebhookProvider, telegramWebhookProvider, verifyInkboxWebhook, verifyLinqWebhook, verifyResendWebhook };
|
|
1203
1293
|
|
|
1204
1294
|
//# sourceMappingURL=index.js.map
|