@tangle-network/agent-integrations 0.75.4 → 0.76.1

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.
Files changed (96) hide show
  1. package/README.md +10 -14
  2. package/data/bundled-adapter-manifests.json +1 -1
  3. package/dist/{adapters-CrN3lR4d.js → adapters-Bx-UTWRg.js} +55 -8
  4. package/dist/{adapters-CrN3lR4d.js.map → adapters-Bx-UTWRg.js.map} +1 -1
  5. package/dist/{bundled-manifest-data-C7dav10o.js → bundled-manifest-data-BgTJ7dmp.js} +33 -1
  6. package/dist/{bundled-manifest-data-C7dav10o.js.map → bundled-manifest-data-BgTJ7dmp.js.map} +1 -1
  7. package/dist/{bundled-manifest-runtime-G6p2i9W-.d.ts → bundled-manifest-runtime-EpjLQKA9.d.ts} +7 -3
  8. package/dist/bundled-manifest-runtime-EpjLQKA9.d.ts.map +1 -0
  9. package/dist/{catalog-DmAjfp4i.d.ts → catalog-z4zNeXVL.d.ts} +3 -3
  10. package/dist/{catalog-DmAjfp4i.d.ts.map → catalog-z4zNeXVL.d.ts.map} +1 -1
  11. package/dist/catalog.d.ts +1 -1
  12. package/dist/{cloudbeds-BL5EF3xl.js → cloudbeds-CGSoT275.js} +17 -2
  13. package/dist/cloudbeds-CGSoT275.js.map +1 -0
  14. package/dist/connect/index.d.ts +1 -1
  15. package/dist/connect/index.js +1 -1
  16. package/dist/connectors/adapters/index.d.ts +2 -2
  17. package/dist/connectors/adapters/index.js +3 -3
  18. package/dist/connectors/index.d.ts +7 -7
  19. package/dist/connectors/index.js +8 -7
  20. package/dist/connectors/oauth.d.ts +2 -2
  21. package/dist/connectors/oauth.js +7 -205
  22. package/dist/connectors/oauth.js.map +1 -1
  23. package/dist/{consumer-BafUQUla.d.ts → consumer-YE5ibTlI.d.ts} +18 -9
  24. package/dist/consumer-YE5ibTlI.d.ts.map +1 -0
  25. package/dist/consumer.d.ts +1 -1
  26. package/dist/consumer.js +1 -1
  27. package/dist/{core-types-DfCMwTYt.d.ts → core-types-0BenSoZJ.d.ts} +17 -3
  28. package/dist/core-types-0BenSoZJ.d.ts.map +1 -0
  29. package/dist/{coverage-catalog-oQiZ8yot.d.ts → coverage-catalog-5LheuThC.d.ts} +2 -2
  30. package/dist/{coverage-catalog-oQiZ8yot.d.ts.map → coverage-catalog-5LheuThC.d.ts.map} +1 -1
  31. package/dist/coverage-catalog.d.ts +1 -1
  32. package/dist/{hub-D13zPQGr.js → hub-Cl8phyJ9.js} +316 -149
  33. package/dist/hub-Cl8phyJ9.js.map +1 -0
  34. package/dist/{hub-fmmnwC2s.d.ts → hub-DkiKVWJX.d.ts} +5 -3
  35. package/dist/hub-DkiKVWJX.d.ts.map +1 -0
  36. package/dist/hub.d.ts +1 -1
  37. package/dist/hub.js +1 -1
  38. package/dist/{index-DbwNiedC.d.ts → index-BFK-G6g1.d.ts} +2 -2
  39. package/dist/{index-DbwNiedC.d.ts.map → index-BFK-G6g1.d.ts.map} +1 -1
  40. package/dist/{index-CHD_8Gn2.d.ts → index-BNzWrQM0.d.ts} +3 -3
  41. package/dist/{index-CHD_8Gn2.d.ts.map → index-BNzWrQM0.d.ts.map} +1 -1
  42. package/dist/{index-B-VH5b3E.d.ts → index-CkCYzn8f.d.ts} +2 -2
  43. package/dist/{index-B-VH5b3E.d.ts.map → index-CkCYzn8f.d.ts.map} +1 -1
  44. package/dist/{index-BKTHRkGz.d.ts → index-WwSnaq5E.d.ts} +11 -2
  45. package/dist/{index-BKTHRkGz.d.ts.map → index-WwSnaq5E.d.ts.map} +1 -1
  46. package/dist/{index-CW1fmxQi.d.ts → index-poLalSQ6.d.ts} +3 -3
  47. package/dist/{index-CW1fmxQi.d.ts.map → index-poLalSQ6.d.ts.map} +1 -1
  48. package/dist/index.d.ts +18 -18
  49. package/dist/index.js +11 -10
  50. package/dist/internal/bundled-manifest-runtime.d.ts +1 -1
  51. package/dist/internal/bundled-manifest-runtime.js +30 -2
  52. package/dist/internal/bundled-manifest-runtime.js.map +1 -1
  53. package/dist/mcp.d.ts +2 -2
  54. package/dist/mcp.js +2 -2
  55. package/dist/middleware/index.d.ts +1 -1
  56. package/dist/middleware/index.js +1 -1
  57. package/dist/{oauth-tzsnaJIb.d.ts → oauth-DoUCpYU_.d.ts} +85 -64
  58. package/dist/oauth-DoUCpYU_.d.ts.map +1 -0
  59. package/dist/oauth-protocol-CFrGJlSz.js +195 -0
  60. package/dist/oauth-protocol-CFrGJlSz.js.map +1 -0
  61. package/dist/{policy-C9frNJFH.d.ts → policy-C8jynxf9.d.ts} +2 -2
  62. package/dist/{policy-C9frNJFH.d.ts.map → policy-C8jynxf9.d.ts.map} +1 -1
  63. package/dist/{registry-CE1iu5zX.d.ts → registry-0xWMSBUu.d.ts} +3 -3
  64. package/dist/{registry-CE1iu5zX.d.ts.map → registry-0xWMSBUu.d.ts.map} +1 -1
  65. package/dist/{registry-core-DtFI-9kF.d.ts → registry-core-B1ApiG47.d.ts} +2 -2
  66. package/dist/{registry-core-DtFI-9kF.d.ts.map → registry-core-B1ApiG47.d.ts.map} +1 -1
  67. package/dist/registry.d.ts +2 -2
  68. package/dist/registry.js +1 -1
  69. package/dist/runtime.d.ts +1 -1
  70. package/dist/sandbox.d.ts +1 -1
  71. package/dist/{specs-Dp7I8aL5.js → specs-02Un982U.js} +2 -2
  72. package/dist/{specs-Dp7I8aL5.js.map → specs-02Un982U.js.map} +1 -1
  73. package/dist/specs.d.ts +1 -1
  74. package/dist/specs.js +1 -1
  75. package/dist/{src-CJBv3wD1.js → src-VFvRn2yV.js} +5 -5
  76. package/dist/{src-CJBv3wD1.js.map → src-VFvRn2yV.js.map} +1 -1
  77. package/dist/{tangle-id-Bq7jkKmE.d.ts → tangle-id-BW5dTiGi.d.ts} +2 -2
  78. package/dist/{tangle-id-Bq7jkKmE.d.ts.map → tangle-id-BW5dTiGi.d.ts.map} +1 -1
  79. package/dist/{tangle-id-81ShqJ7k.js → tangle-id-DUsy7I9_.js} +2 -2
  80. package/dist/{tangle-id-81ShqJ7k.js.map → tangle-id-DUsy7I9_.js.map} +1 -1
  81. package/dist/{types-W418mSuf.d.ts → types-Bq85dJDW.d.ts} +13 -1
  82. package/dist/types-Bq85dJDW.d.ts.map +1 -0
  83. package/dist/{types-BSDXGSi5.js → types-CjrugGcd.js} +13 -7
  84. package/dist/types-CjrugGcd.js.map +1 -0
  85. package/dist/webhooks/index.js +1 -1
  86. package/dist/worker.d.ts +3 -3
  87. package/package.json +1 -1
  88. package/dist/bundled-manifest-runtime-G6p2i9W-.d.ts.map +0 -1
  89. package/dist/cloudbeds-BL5EF3xl.js.map +0 -1
  90. package/dist/consumer-BafUQUla.d.ts.map +0 -1
  91. package/dist/core-types-DfCMwTYt.d.ts.map +0 -1
  92. package/dist/hub-D13zPQGr.js.map +0 -1
  93. package/dist/hub-fmmnwC2s.d.ts.map +0 -1
  94. package/dist/oauth-tzsnaJIb.d.ts.map +0 -1
  95. package/dist/types-BSDXGSi5.js.map +0 -1
  96. package/dist/types-W418mSuf.d.ts.map +0 -1
@@ -1,4 +1,5 @@
1
- import { createOAuthBasicAuthorizationHeader, createOAuthTokenRequestHeaders, oauthClientCredentialRedactionValues, redactOAuthSensitiveText } from "./connectors/oauth.js";
1
+ import { i as ProviderRateLimited, r as ProviderConfigError, t as CredentialsExpired } from "./types-CjrugGcd.js";
2
+ import { a as exchangeAuthorizationCode, c as redactOAuthSensitiveText, r as createOAuthBasicAuthorizationHeader, s as oauthClientCredentialRedactionValues, t as buildOAuthAuthorizationUrl } from "./oauth-protocol-CFrGJlSz.js";
2
3
  import { n as composeIntegrationRegistry } from "./registry-core-BZo69C37.js";
3
4
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
4
5
  //#region src/core-error.ts
@@ -16,129 +17,253 @@ function createConnectorAdapterProvider(options) {
16
17
  const providerId = options.id ?? "first-party";
17
18
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
18
19
  const fetchImpl = options.fetchImpl ?? globalThis.fetch?.bind(globalThis);
19
- const adapters = /* @__PURE__ */ new Map();
20
- for (const adapter of options.adapters) adapters.set(adapter.manifest.kind, adapter);
20
+ const adapters = new Map(options.adapters.filter((adapter) => !adapter.inboundOnly).map((adapter) => [adapter.manifest.kind, adapter]));
21
+ const requireAdapter = (id) => {
22
+ const adapter = adapters.get(id);
23
+ if (!adapter) throw new IntegrationError(`Connector adapter ${id} not found.`, "connector_not_found");
24
+ if (adapter.catalogOnly) throw new IntegrationError(`Connector ${id} is not configured.`, "config_missing");
25
+ return adapter;
26
+ };
27
+ const requireOAuth = (adapter) => {
28
+ const auth = oauthManifestAuth(adapter.manifest.auth);
29
+ if (!auth || (auth.grantType ?? "authorization_code") !== "authorization_code") throw new IntegrationError(`Connector ${adapter.manifest.kind} does not support authorization-code OAuth.`, "auth_not_supported");
30
+ return auth;
31
+ };
32
+ const requireClient = async (connectorId, auth) => {
33
+ const client = await options.resolveOAuthClient?.({ connectorId });
34
+ if (!client?.clientId || auth.tokenClientAuthMethod !== "none" && !client.clientSecret) throw new IntegrationError(`OAuth client credentials unavailable for ${connectorId}.`, "config_missing");
35
+ if (auth.tokenClientAuthMethod && ![
36
+ "none",
37
+ "client_secret_post",
38
+ "client_secret_basic"
39
+ ].includes(auth.tokenClientAuthMethod)) throw new IntegrationError("Unsupported OAuth token client authentication method.", "config_missing");
40
+ return client;
41
+ };
42
+ const commit = async (connection, credentials) => {
43
+ if (!options.persistConnection) throw new IntegrationError("An encrypted credential commit is required.", "config_missing");
44
+ try {
45
+ const stored = await options.persistConnection({
46
+ connection,
47
+ credentials
48
+ });
49
+ if (!stored.id || !stored.secretRef?.id || stored.owner.id !== connection.owner.id || stored.owner.type !== connection.owner.type || stored.providerId !== connection.providerId || stored.connectorId !== connection.connectorId) throw new Error("Invalid credential commit result.");
50
+ return stored;
51
+ } catch (cause) {
52
+ throw new IntegrationError("Credential commit rejected.", cause instanceof IntegrationError ? cause.code : "credential_persistence_failure");
53
+ }
54
+ };
21
55
  return {
22
56
  id: providerId,
23
57
  kind: options.kind ?? "first_party",
24
58
  listConnectors: () => [...adapters.values()].map((adapter) => manifestToConnector(providerId, adapter)),
25
59
  async startAuth(request) {
26
- const adapter = adapters.get(request.connectorId);
27
- if (!adapter) throw new IntegrationError(`Connector adapter ${request.connectorId} not found.`, "connector_not_found");
28
- const auth = oauthManifestAuth(adapter.manifest.auth);
29
- if (!auth) throw new IntegrationError(`Connector ${request.connectorId} does not support OAuth2 authorization (auth kind: ${adapter.manifest.auth.kind}).`, "auth_not_supported");
30
- if ((auth.grantType ?? "authorization_code") !== "authorization_code") throw new IntegrationError(`Connector ${request.connectorId} uses client_credentials and requires a machine connection path.`, "auth_not_supported");
60
+ const adapter = requireAdapter(request.connectorId);
61
+ const auth = requireOAuth(adapter);
62
+ const client = await requireClient(request.connectorId, auth);
63
+ if (!auth.authorizationUrl) throw new IntegrationError("OAuth authorization URL missing.", "config_missing");
64
+ const metadata = resolveOAuthConnectionMetadata(auth, request.metadata, request.connectorId);
65
+ resolveOAuthUrlTemplate(auth.tokenUrl, metadata, request.connectorId, auth.urlTemplateMetadata);
31
66
  const pkce = resolveOAuthPkceMode(auth.pkce, request.connectorId);
32
- const tokenClientAuthMethod = resolveTokenClientAuthMethod(auth.tokenClientAuthMethod, request.connectorId);
33
- if (!options.resolveOAuthClient) throw new IntegrationError(`OAuth client resolver missing on adapter provider; cannot start auth for ${request.connectorId}.`, "config_missing");
34
- const client = await options.resolveOAuthClient({ connectorId: request.connectorId });
35
- if (!client || !client.clientId || tokenClientAuthMethod !== "none" && !client.clientSecret) throw new IntegrationError(`OAuth client credentials unavailable for ${request.connectorId}.`, "config_missing");
36
- if (!auth.authorizationUrl) throw new IntegrationError(`Connector ${request.connectorId} uses the ${auth.grantType ?? "authorization_code"} grant and has no authorization URL to redirect to.`, "auth_not_supported");
37
- const scopes = request.requestedScopes && request.requestedScopes.length > 0 ? request.requestedScopes : auth.scopes;
38
- const url = new URL(resolveOAuthUrlTemplate(auth.authorizationUrl, request.metadata, request.connectorId, auth.urlTemplateMetadata));
39
- url.searchParams.set("response_type", "code");
40
- url.searchParams.set(resolveOAuthParameterName(auth.authorizationClientIdParam, "client_id", request.connectorId), client.clientId);
41
- url.searchParams.set("redirect_uri", request.redirectUri);
42
- if (auth.sendScopeParam !== false && scopes.length > 0) url.searchParams.set("scope", scopes.join(auth.scopeSeparator ?? " "));
43
67
  const state = request.state ?? randomState();
44
- url.searchParams.set("state", state);
45
- if (auth.extraAuthParams) for (const [key, value] of Object.entries(auth.extraAuthParams)) url.searchParams.set(key, value);
46
- if (pkce === "unsupported") {
47
- url.searchParams.delete("code_challenge");
48
- url.searchParams.delete("code_challenge_method");
49
- } else {
50
- url.searchParams.set("code_challenge", requirePkceChallenge(request.codeChallenge, request.connectorId));
51
- url.searchParams.set("code_challenge_method", "S256");
52
- }
68
+ const requestedScopes = request.requestedScopes.length ? request.requestedScopes : auth.scopes;
53
69
  return {
54
70
  providerId,
55
71
  connectorId: request.connectorId,
56
- authUrl: url.toString(),
57
72
  state,
58
- metadata: request.metadata
73
+ requestedScopes,
74
+ authUrl: buildOAuthAuthorizationUrl({
75
+ ...auth,
76
+ ...client,
77
+ state,
78
+ redirectUri: request.redirectUri,
79
+ authorizationUrl: resolveOAuthUrlTemplate(auth.authorizationUrl, metadata, request.connectorId, auth.urlTemplateMetadata),
80
+ scopes: requestedScopes,
81
+ codeChallenge: pkce === "unsupported" ? void 0 : requirePkceChallenge(request.codeChallenge, request.connectorId)
82
+ }),
83
+ metadata
59
84
  };
60
85
  },
61
86
  async completeAuth(request) {
62
- const adapter = adapters.get(request.connectorId);
63
- if (!adapter) throw new IntegrationError(`Connector adapter ${request.connectorId} not found.`, "connector_not_found");
64
- const auth = oauthManifestAuth(adapter.manifest.auth);
65
- if (!auth) throw new IntegrationError(`Connector ${request.connectorId} does not support OAuth2 authorization (auth kind: ${adapter.manifest.auth.kind}).`, "auth_not_supported");
66
- if ((auth.grantType ?? "authorization_code") !== "authorization_code") throw new IntegrationError(`Connector ${request.connectorId} uses client_credentials and requires a machine connection path.`, "auth_not_supported");
67
- const tokenClientAuthMethod = resolveTokenClientAuthMethod(auth.tokenClientAuthMethod, request.connectorId);
68
- const pkce = resolveOAuthPkceMode(auth.pkce, request.connectorId);
69
- if (!request.code) throw new IntegrationError(`Authorization code missing on completeAuth for ${request.connectorId}.`, "config_missing");
70
- if (!options.resolveOAuthClient) throw new IntegrationError(`OAuth client resolver missing on adapter provider; cannot complete auth for ${request.connectorId}.`, "config_missing");
71
- const client = await options.resolveOAuthClient({ connectorId: request.connectorId });
72
- if (!client || !client.clientId || tokenClientAuthMethod !== "none" && !client.clientSecret) throw new IntegrationError(`OAuth client credentials unavailable for ${request.connectorId}.`, "config_missing");
73
- if (!fetchImpl) throw new IntegrationError("No fetch implementation available; inject fetchImpl into createConnectorAdapterProvider.", "config_missing");
74
- const body = new URLSearchParams({
75
- grant_type: "authorization_code",
76
- code: request.code,
77
- redirect_uri: request.redirectUri
87
+ const adapter = requireAdapter(request.connectorId);
88
+ const auth = requireOAuth(adapter);
89
+ if (!request.code) throw new IntegrationError("OAuth authorization code missing.", "config_missing");
90
+ if (!options.persistConnection) throw new IntegrationError("An encrypted credential commit is required.", "config_missing");
91
+ const metadata = resolveOAuthConnectionMetadata(auth, request.metadata, request.connectorId);
92
+ const codeVerifier = resolveOAuthPkceMode(auth.pkce, request.connectorId) === "unsupported" ? void 0 : requirePkceVerifier(request.codeVerifier, request.connectorId);
93
+ resolveOAuthUrlTemplate(auth.tokenUrl, metadata, request.connectorId, auth.urlTemplateMetadata);
94
+ const client = await requireClient(request.connectorId, auth);
95
+ const exchanged = await boundedProviderCall(options.operationTimeoutMs, request.signal, async (signal) => {
96
+ if (adapter.exchangeOAuth) return adapter.exchangeOAuth({
97
+ ...request,
98
+ code: request.code,
99
+ codeVerifier,
100
+ signal
101
+ });
102
+ try {
103
+ const tokens = await exchangeAuthorizationCode({
104
+ ...auth,
105
+ ...client,
106
+ code: request.code,
107
+ codeVerifier,
108
+ redirectUri: request.redirectUri,
109
+ tokenUrl: resolveOAuthUrlTemplate(auth.tokenUrl, metadata, request.connectorId, auth.urlTemplateMetadata),
110
+ fetchImpl,
111
+ signal
112
+ });
113
+ return {
114
+ credentials: {
115
+ kind: "oauth2",
116
+ accessToken: tokens.accessToken,
117
+ refreshToken: tokens.refreshToken,
118
+ expiresAt: tokens.expiresIn && tokens.expiresIn > 0 ? now().getTime() + tokens.expiresIn * 1e3 : void 0
119
+ },
120
+ scopes: tokens.scope?.split(/[\s,]+/).filter(Boolean) ?? [],
121
+ metadata: tokens.metadata ?? {}
122
+ };
123
+ } catch (cause) {
124
+ throw new IntegrationError(cause instanceof Error ? cause.message : "OAuth exchange failed.", "provider_failure");
125
+ }
126
+ }).catch((cause) => {
127
+ const secrets = [
128
+ request.code,
129
+ codeVerifier ?? "",
130
+ ...oauthClientCredentialRedactionValues(client.clientId, client.clientSecret, client.clientSecret ? createOAuthBasicAuthorizationHeader(client.clientId, client.clientSecret) : void 0)
131
+ ];
132
+ throw new IntegrationError(redactOAuthSensitiveText(cause instanceof Error ? cause.message : "OAuth exchange failed.", secrets), "provider_failure");
78
133
  });
79
- const codeVerifier = pkce === "unsupported" ? void 0 : requirePkceVerifier(request.codeVerifier, request.connectorId);
80
- if (codeVerifier) body.set("code_verifier", codeVerifier);
81
- const headers = createOAuthTokenRequestHeaders(auth.tokenRequestHeaders);
82
- if (tokenClientAuthMethod === "none") body.set(resolveOAuthParameterName(auth.tokenClientIdParam, "client_id", request.connectorId), client.clientId);
83
- else if (tokenClientAuthMethod === "client_secret_post") {
84
- body.set(resolveOAuthParameterName(auth.tokenClientIdParam, "client_id", request.connectorId), client.clientId);
85
- body.set(resolveOAuthParameterName(auth.tokenClientSecretParam, "client_secret", request.connectorId), client.clientSecret);
86
- } else headers.authorization = createOAuthBasicAuthorizationHeader(client.clientId, client.clientSecret, base64Encode);
87
- const redactionValues = [
88
- request.code,
89
- ...codeVerifier ? [codeVerifier] : [],
90
- ...oauthClientCredentialRedactionValues(client.clientId, client.clientSecret, headers.authorization)
91
- ];
92
- const tokenUrl = resolveOAuthUrlTemplate(auth.tokenUrl, request.metadata, request.connectorId, auth.urlTemplateMetadata);
93
- let res;
134
+ if (request.signal?.aborted) throw new IntegrationError("OAuth exchange aborted.", "provider_failure");
135
+ const credentials = exchanged.credentials;
136
+ if (credentials.kind !== "oauth2" || !credentials.accessToken) throw new IntegrationError("OAuth exchange returned invalid credentials.", "provider_failure");
137
+ const issued = now().toISOString();
138
+ return commit({
139
+ id: randomConnectionId(),
140
+ owner: request.owner,
141
+ providerId,
142
+ connectorId: request.connectorId,
143
+ status: "active",
144
+ grantedScopes: exchanged.scopes.length ? exchanged.scopes : request.requestedScopes ?? [],
145
+ createdAt: issued,
146
+ updatedAt: issued,
147
+ expiresAt: credentials.expiresAt ? new Date(credentials.expiresAt).toISOString() : void 0,
148
+ metadata: {
149
+ ...metadata,
150
+ ...exchanged.metadata
151
+ }
152
+ }, credentials);
153
+ },
154
+ async testConnection(connection) {
155
+ const adapter = requireAdapter(connection.connectorId);
156
+ let source;
94
157
  try {
95
- res = await fetchImpl(tokenUrl, {
96
- method: "POST",
97
- headers,
98
- body
99
- });
100
- } catch (cause) {
101
- const detail = redactOAuthSensitiveText(cause?.message ?? "unknown", redactionValues);
102
- throw new IntegrationError(`OAuth token exchange transport error for ${request.connectorId}: ${detail}`, "provider_failure");
103
- }
104
- if (!res.ok) {
105
- const text = await res.text().catch(() => "");
106
- const statusText = redactOAuthSensitiveText(res.statusText, redactionValues);
107
- const redactedText = redactOAuthSensitiveText(text, redactionValues);
108
- const detail = `${res.status} ${statusText} — ${redactedText.slice(0, 200)}`;
109
- throw new IntegrationError(`OAuth token exchange failed for ${request.connectorId}: ${detail}`, "provider_failure");
158
+ source = await options.resolveDataSource(connection);
159
+ } catch {
160
+ return "credential_persistence_failure";
110
161
  }
111
- let json;
162
+ let observed = false;
163
+ const credentials = new Proxy(source.credentials, {
164
+ get(target, key, receiver) {
165
+ observed = true;
166
+ return Reflect.get(target, key, receiver);
167
+ },
168
+ has(target, key) {
169
+ observed = true;
170
+ return Reflect.has(target, key);
171
+ },
172
+ ownKeys(target) {
173
+ observed = true;
174
+ return Reflect.ownKeys(target);
175
+ },
176
+ set(target, key, value, receiver) {
177
+ observed = true;
178
+ return Reflect.set(target, key, value, receiver);
179
+ }
180
+ });
181
+ let acceptRotations = true;
182
+ let deadlineExpired = false;
183
+ let rotationFailed = false;
184
+ let persistence = Promise.resolve();
185
+ const persistRotation = (next) => {
186
+ if (!observed || !acceptRotations || deadlineExpired) return Promise.resolve();
187
+ if (!options.onCredentialsRotated) {
188
+ rotationFailed = true;
189
+ return Promise.resolve();
190
+ }
191
+ persistence = persistence.then(async () => {
192
+ if (deadlineExpired) return;
193
+ try {
194
+ await options.onCredentialsRotated({
195
+ connection,
196
+ credentials: next
197
+ });
198
+ } catch {
199
+ rotationFailed = true;
200
+ }
201
+ });
202
+ return persistence;
203
+ };
204
+ let status;
112
205
  try {
113
- json = await res.json();
114
- } catch {
115
- throw new IntegrationError(`OAuth token exchange returned non-JSON body for ${request.connectorId}.`, "provider_failure");
206
+ const result = await boundedProviderCall(options.operationTimeoutMs, void 0, () => adapter.test({
207
+ ...source,
208
+ credentials
209
+ }, persistRotation), () => {
210
+ deadlineExpired = true;
211
+ });
212
+ status = result.ok ? "healthy" : classifyConnectionFailure(result.reason);
213
+ } catch (cause) {
214
+ if (cause instanceof ProviderOperationAborted) return "network";
215
+ status = classifyConnectionFailure(cause);
216
+ } finally {
217
+ acceptRotations = false;
116
218
  }
117
- if (!json.access_token) throw new IntegrationError(`OAuth token exchange returned no access_token for ${request.connectorId}.`, "provider_failure");
118
- const grantedScopes = typeof json.scope === "string" && json.scope.length > 0 ? json.scope.split(/[\s,]+/).filter(Boolean) : [];
119
- const issued = now();
120
- const issuedIso = issued.toISOString();
121
- const expiresAt = typeof json.expires_in === "number" && json.expires_in > 0 ? new Date(issued.getTime() + json.expires_in * 1e3).toISOString() : void 0;
122
- const capturedMetadata = captureTokenMetadata(auth.tokenMetadata, json, request.connectorId);
123
- return {
219
+ await persistence;
220
+ if (!observed) return "unsupported";
221
+ if (rotationFailed) return "credential_persistence_failure";
222
+ return status;
223
+ },
224
+ async connectApiKey(request) {
225
+ if (!request.apiKey || !options.persistConnection) throw new IntegrationError("API key and encrypted credential commit required.", "config_missing");
226
+ const adapter = requireAdapter(request.connectorId);
227
+ if (!(adapter.manifest.auth.kind === "one_of" ? adapter.manifest.auth.options : [adapter.manifest.auth]).some((entry) => entry.kind === "api-key")) throw new IntegrationError("Connector does not support API keys.", "auth_not_supported");
228
+ const metadata = adapter.validateConnectionMetadata ? adapter.validateConnectionMetadata(request.metadata ?? {}) : !request.metadata || !Object.keys(request.metadata).length ? {} : null;
229
+ if (!metadata) throw new IntegrationError("Invalid connection metadata.", "connection_metadata_invalid");
230
+ const issued = now().toISOString();
231
+ const connection = {
124
232
  id: randomConnectionId(),
125
233
  owner: request.owner,
126
234
  providerId,
127
235
  connectorId: request.connectorId,
128
236
  status: "active",
129
- grantedScopes,
130
- createdAt: issuedIso,
131
- updatedAt: issuedIso,
132
- expiresAt,
133
- metadata: {
134
- ...request.metadata,
135
- ...capturedMetadata
136
- }
237
+ grantedScopes: [],
238
+ createdAt: issued,
239
+ updatedAt: issued,
240
+ metadata
137
241
  };
242
+ const credentials = {
243
+ kind: "api-key",
244
+ apiKey: request.apiKey
245
+ };
246
+ const status = await createConnectorAdapterProvider({
247
+ ...options,
248
+ onCredentialsRotated: void 0,
249
+ resolveDataSource: () => ({
250
+ id: connection.id,
251
+ projectId: request.owner.id,
252
+ publishedAgentId: null,
253
+ kind: request.connectorId,
254
+ label: adapter.manifest.displayName,
255
+ consistencyModel: adapter.manifest.defaultConsistencyModel,
256
+ scopes: [],
257
+ metadata,
258
+ credentials,
259
+ status: "active"
260
+ })
261
+ }).testConnection(connection);
262
+ if (status !== "healthy") throw new IntegrationError(`Credential probe failed: ${status}.`, status === "reconnect_required" ? "credential_invalid" : status === "rate_limited" ? "credential_rate_limited" : status === "unsupported" ? "credential_probe_unsupported" : status === "credential_persistence_failure" ? status : "provider_failure");
263
+ return commit(connection, credentials);
138
264
  },
139
265
  async invokeAction(connection, request) {
140
- const adapter = adapters.get(connection.connectorId);
141
- if (!adapter) throw new IntegrationError(`Connector adapter ${connection.connectorId} not found.`, "connector_not_found");
266
+ const adapter = requireAdapter(connection.connectorId);
142
267
  const capability = adapter.manifest.capabilities.find((candidate) => candidate.name === request.action);
143
268
  if (!capability) throw new IntegrationError(`Capability ${request.action} is not defined by ${connection.connectorId}.`, "action_not_found");
144
269
  const source = await options.resolveDataSource(connection);
@@ -213,10 +338,11 @@ function manifestToConnector(providerId, adapter) {
213
338
  metadata: {
214
339
  source: "first-party-adapter",
215
340
  supportTier: "firstPartyExecutable",
216
- executable: true,
341
+ executable: !adapter.catalogOnly,
217
342
  oauthPkce: oauthAuth ? resolveOAuthPkceMode(oauthAuth.pkce, manifest.kind) : void 0,
218
343
  authOptions: manifest.auth.kind === "one_of" ? manifest.auth.options.map((auth) => auth.kind) : [manifest.auth.kind],
219
- preferredAuth: manifest.auth.kind === "one_of" ? manifest.auth.preferred : manifest.auth.kind
344
+ preferredAuth: manifest.auth.kind === "one_of" ? manifest.auth.preferred : manifest.auth.kind,
345
+ oauthConnectionParameters: oauthAuth ? oauthConnectionParameters(oauthAuth) : []
220
346
  }
221
347
  };
222
348
  }
@@ -281,11 +407,6 @@ function oauthManifestAuth(auth) {
281
407
  /** Resolve the manifest value at the last possible point before an OAuth
282
408
  * request. The runtime check matters because adapters can enter through JS or
283
409
  * an `any` cast without first passing the static manifest validator. */
284
- function resolveTokenClientAuthMethod(value, connectorId) {
285
- if (value === void 0 || value === "client_secret_post") return "client_secret_post";
286
- if (value === "none" || value === "client_secret_basic") return value;
287
- throw new IntegrationError(`Connector ${connectorId} has an unsupported OAuth token client authentication method.`, "config_missing");
288
- }
289
410
  function resolveOAuthPkceMode(value, connectorId) {
290
411
  if (value === void 0 || value === "required") return "required";
291
412
  if (value === "supported" || value === "unsupported") return value;
@@ -299,21 +420,6 @@ function requirePkceVerifier(value, connectorId) {
299
420
  if (!value || !/^[A-Za-z0-9._~-]{43,128}$/.test(value)) throw new IntegrationError(`OAuth PKCE verifier missing or invalid for ${connectorId}.`, "config_missing");
300
421
  return value;
301
422
  }
302
- function resolveOAuthParameterName(value, fallback, connectorId) {
303
- const name = value ?? fallback;
304
- if (!/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(name)) throw new IntegrationError(`Connector ${connectorId} declares an invalid OAuth parameter name.`, "config_missing");
305
- return name;
306
- }
307
- /** Encodes UTF-8 credentials without importing Node's Buffer, so the adapter
308
- * provider remains usable in browser and edge runtimes. */
309
- function base64Encode(value) {
310
- const btoa = globalThis.btoa;
311
- if (typeof btoa !== "function") throw new IntegrationError("OAuth client_secret_basic requires a base64 encoder in this runtime.", "config_missing");
312
- const bytes = new TextEncoder().encode(value);
313
- let binary = "";
314
- for (const byte of bytes) binary += String.fromCharCode(byte);
315
- return btoa(binary);
316
- }
317
423
  /** Resolve provider-owned tenant labels embedded in OAuth URLs.
318
424
  *
319
425
  * Shopify and Gorgias put the merchant name in the hostname. Only one DNS
@@ -328,17 +434,17 @@ function resolveOAuthUrlTemplate(template, metadata, connectorId, metadataSpecs)
328
434
  const raw = metadata?.[key];
329
435
  const metadataSpec = metadataSpecs?.[key];
330
436
  if (metadataSpec?.kind === "base-url") {
331
- if (typeof raw !== "string") throw new IntegrationError(`OAuth URL for ${connectorId} requires metadata.${key} as a provider base URL.`, "config_missing");
437
+ if (typeof raw !== "string") throw new IntegrationError(`OAuth URL for ${connectorId} requires metadata.${key} as a provider base URL.`, raw === void 0 ? "connection_parameters_missing" : "connection_parameters_invalid");
332
438
  resolved = resolved.replaceAll(match[0], resolveOAuthMetadataBaseUrl(raw, metadataSpec, connectorId, key));
333
439
  continue;
334
440
  }
335
441
  if (metadataSpec?.kind === "path-segment") {
336
442
  if (!isOAuthPathSegmentPlaceholder(template, match.index ?? -1, match[0])) throw new IntegrationError(`OAuth URL for ${connectorId} declares metadata.${key} outside a complete path segment.`, "config_missing");
337
- if (typeof raw !== "string" || !isOAuthPathSegment(raw.trim())) throw new IntegrationError(`OAuth URL for ${connectorId} requires metadata.${key} as a valid path segment.`, "config_missing");
443
+ if (typeof raw !== "string" || !isOAuthPathSegment(raw.trim())) throw new IntegrationError(`OAuth URL for ${connectorId} requires metadata.${key} as a valid path segment.`, raw === void 0 ? "connection_parameters_missing" : "connection_parameters_invalid");
338
444
  resolved = resolved.replaceAll(match[0], encodeURIComponent(raw.trim()));
339
445
  continue;
340
446
  }
341
- if (typeof raw !== "string" || !isDnsLabel(raw.trim())) throw new IntegrationError(`OAuth URL for ${connectorId} requires metadata.${key} as a valid tenant label.`, "config_missing");
447
+ if (typeof raw !== "string" || !isDnsLabel(raw.trim())) throw new IntegrationError(`OAuth URL for ${connectorId} requires metadata.${key} as a valid tenant label.`, raw === void 0 ? "connection_parameters_missing" : "connection_parameters_invalid");
342
448
  resolved = resolved.replaceAll(match[0], raw.trim().toLowerCase());
343
449
  }
344
450
  let url;
@@ -347,7 +453,7 @@ function resolveOAuthUrlTemplate(template, metadata, connectorId, metadataSpecs)
347
453
  } catch {
348
454
  throw new IntegrationError(`OAuth URL for ${connectorId} is invalid.`, "config_missing");
349
455
  }
350
- if (url.protocol !== "https:" || url.username || url.password) throw new IntegrationError(`OAuth URL for ${connectorId} must be HTTPS without embedded credentials.`, "config_missing");
456
+ if (url.protocol !== "https:" || url.username || url.password || !isPublicDnsHostname(url.hostname)) throw new IntegrationError(`OAuth URL for ${connectorId} must be HTTPS without embedded credentials.`, "config_missing");
351
457
  return url.toString();
352
458
  }
353
459
  function isOAuthPathSegment(value) {
@@ -377,7 +483,7 @@ function resolveOAuthMetadataBaseUrl(value, spec, connectorId, metadataKey) {
377
483
  return url.origin;
378
484
  }
379
485
  function invalidOAuthMetadataBaseUrl(connectorId, metadataKey) {
380
- return new IntegrationError(`OAuth URL for ${connectorId} requires metadata.${metadataKey} as an allowed HTTPS provider root.`, "config_missing");
486
+ return new IntegrationError(`OAuth URL for ${connectorId} requires metadata.${metadataKey} as an allowed HTTPS provider root.`, "connection_parameters_invalid");
381
487
  }
382
488
  function sameOrigin(candidate, actual) {
383
489
  try {
@@ -396,28 +502,6 @@ function isPublicDnsHostname(hostname) {
396
502
  function isDnsLabel(value) {
397
503
  return value.length > 0 && value.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(value);
398
504
  }
399
- /** Project the declared `auth.tokenMetadata` mappings out of an OAuth
400
- * token-response body into connection metadata. Each entry maps a
401
- * connection-metadata key → the token-response field to read (string
402
- * shorthand) or `{ field, required }`. Required fields that are absent/empty
403
- * throw `provider_failure` so the break surfaces at connect; non-required
404
- * fields are captured if present and otherwise skipped. */
405
- function captureTokenMetadata(tokenMetadata, json, connectorId) {
406
- if (!tokenMetadata) return {};
407
- const captured = {};
408
- for (const [metaKey, source] of Object.entries(tokenMetadata)) {
409
- const field = typeof source === "string" ? source : source.field;
410
- const required = typeof source === "string" ? false : source.required === true;
411
- const raw = json[field];
412
- const value = typeof raw === "string" ? raw.trim() : raw;
413
- if (value === void 0 || value === null || value === "") {
414
- if (required) throw new IntegrationError(`OAuth token exchange for ${connectorId} did not return required field "${field}" for metadata.${metaKey}.`, "provider_failure");
415
- continue;
416
- }
417
- captured[metaKey] = String(value);
418
- }
419
- return captured;
420
- }
421
505
  function mapCategory(category) {
422
506
  if (category === "comms") return "chat";
423
507
  if (category === "spreadsheet") return "database";
@@ -455,6 +539,75 @@ function base64UrlEncode$1(bytes) {
455
539
  for (const b of bytes) bin += String.fromCharCode(b);
456
540
  return (typeof btoa === "function" ? btoa(bin) : Buffer.from(bin, "binary").toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
457
541
  }
542
+ var ProviderOperationAborted = class extends Error {};
543
+ /** The losing promise remains observed; only an on-time result reaches a credential commit. */
544
+ async function boundedProviderCall(timeoutMs, parent, start, onAbort) {
545
+ const budget = timeoutMs ?? 1e4;
546
+ if (!Number.isFinite(budget) || budget <= 0) throw new IntegrationError("Invalid provider timeout.", "config_missing");
547
+ const controller = new AbortController();
548
+ let timer;
549
+ let rejectAbort = () => {};
550
+ const abort = () => {
551
+ onAbort?.();
552
+ controller.abort();
553
+ rejectAbort(new ProviderOperationAborted("Provider operation aborted or timed out."));
554
+ };
555
+ try {
556
+ return await Promise.race([new Promise((_, reject) => {
557
+ rejectAbort = reject;
558
+ timer = setTimeout(abort, budget);
559
+ parent?.addEventListener("abort", abort, { once: true });
560
+ if (parent?.aborted) abort();
561
+ }), Promise.resolve().then(() => {
562
+ if (controller.signal.aborted) throw new Error("Provider operation aborted.");
563
+ return start(controller.signal);
564
+ })]);
565
+ } finally {
566
+ clearTimeout(timer);
567
+ parent?.removeEventListener("abort", abort);
568
+ controller.abort();
569
+ }
570
+ }
571
+ function classifyConnectionFailure(raw) {
572
+ if (raw instanceof ProviderRateLimited) return "rate_limited";
573
+ if (raw instanceof CredentialsExpired) return "reconnect_required";
574
+ if (raw instanceof ProviderConfigError) return "provider_failure";
575
+ const message = raw instanceof Error ? raw.message : typeof raw === "string" ? raw : "";
576
+ if (/\b429\b|rate.?limit|too many requests|\bthrottl|(?:quota|daily limit).*(?:exceed|exhaust)/i.test(message)) return "rate_limited";
577
+ if (/rejected credentials|credentials?.*(?:expired|invalid|revoked)|(?:access|refresh|oauth|bearer)?\s*token.*(?:expired|invalid|revoked)|invalid[_\s-]?grant|\bunauthori[sz]ed\b|authentication failed|\bhttp\s*401\b|\(401\)/i.test(message)) return "reconnect_required";
578
+ if (/network|fetch failed|\bECONN[A-Z]+\b|\bENOTFOUND\b|\bEAI_AGAIN\b|\bETIMEDOUT\b|socket hang up|timed?\s*out|abort(?:ed)?/i.test(message)) return "network";
579
+ return "provider_failure";
580
+ }
581
+ function oauthConnectionParameters(auth) {
582
+ return [...new Set([...`${auth.authorizationUrl ?? ""} ${auth.tokenUrl}`.matchAll(/\{([A-Za-z][A-Za-z0-9_]*)\}/g)].map((match) => match[1]))].map((key) => ({
583
+ key,
584
+ required: true,
585
+ kind: auth.urlTemplateMetadata?.[key]?.kind ?? "dns-label",
586
+ ...auth.urlTemplateMetadata?.[key]
587
+ }));
588
+ }
589
+ function resolveOAuthConnectionMetadata(auth, raw, id) {
590
+ const metadata = { ...raw };
591
+ for (const parameter of oauthConnectionParameters(auth)) {
592
+ const spec = auth.urlTemplateMetadata?.[parameter.key];
593
+ if (parameter.kind !== "dns-label") continue;
594
+ let value = metadata[parameter.key];
595
+ if (typeof value === "string" && /^https:\/\//i.test(value.trim())) try {
596
+ const url = new URL(value.trim());
597
+ const template = spec?.kind === "dns-label" ? spec.connectionMetadata?.template : void 0;
598
+ const expected = template ? new URL(template.replaceAll(`{${parameter.key}}`, "oauth-tenant")) : void 0;
599
+ const suffix = expected?.hostname.startsWith("oauth-tenant.") ? expected.hostname.slice(12) : void 0;
600
+ if (!suffix || !url.hostname.endsWith(suffix) || url.username || url.password || url.port || url.pathname !== "/" || url.search || url.hash) throw new Error("Invalid tenant origin");
601
+ value = url.hostname.slice(0, -suffix.length);
602
+ } catch {
603
+ throw new IntegrationError(`Invalid tenant origin ${parameter.key}.`, "connection_parameters_invalid");
604
+ }
605
+ if (typeof value !== "string" || !isDnsLabel(value.trim())) throw new IntegrationError(`Invalid tenant label ${parameter.key}.`, value === void 0 ? "connection_parameters_missing" : "connection_parameters_invalid");
606
+ metadata[parameter.key] = value.trim().toLowerCase();
607
+ if (spec?.kind === "dns-label" && spec.connectionMetadata) metadata[spec.connectionMetadata.key] = resolveOAuthUrlTemplate(spec.connectionMetadata.template, metadata, id, auth.urlTemplateMetadata);
608
+ }
609
+ return metadata;
610
+ }
458
611
  //#endregion
459
612
  //#region src/credentials.ts
460
613
  var CredentialRefreshRevokedError = class extends Error {
@@ -800,11 +953,11 @@ var IntegrationHub = class {
800
953
  providerId,
801
954
  connectorId: request.connectorId,
802
955
  owner: request.owner,
803
- requestedScopes: request.requestedScopes,
956
+ requestedScopes: result.requestedScopes ?? request.requestedScopes,
804
957
  redirectUri: request.redirectUri,
805
958
  codeVerifier: pkcePair?.verifier,
806
959
  expiresAt: this.now().getTime() + this.oauthStateTtlMs,
807
- metadata: request.metadata
960
+ metadata: result.metadata ?? request.metadata
808
961
  };
809
962
  await this.oauthStateStore.put(record);
810
963
  return result;
@@ -827,11 +980,25 @@ var IntegrationHub = class {
827
980
  state: outcome.state.state,
828
981
  redirectUri: outcome.state.redirectUri,
829
982
  codeVerifier: outcome.state.codeVerifier,
983
+ requestedScopes: outcome.state.requestedScopes,
830
984
  metadata: pinnedMetadata
831
985
  });
832
986
  await this.store.put(connection);
833
987
  return connection;
834
988
  }
989
+ async connectApiKey(providerId, request) {
990
+ const provider = this.requireProvider(providerId);
991
+ if (!provider.connectApiKey) throw new IntegrationError("Provider does not support API-key connections.", "auth_not_supported");
992
+ const connection = await provider.connectApiKey(request);
993
+ await this.store.put(connection);
994
+ return connection;
995
+ }
996
+ async testConnection(connectionId) {
997
+ const connection = await this.requireConnection(connectionId);
998
+ this.assertConnectionActive(connection);
999
+ const provider = this.requireProvider(connection.providerId);
1000
+ return provider.testConnection ? provider.testConnection(connection) : "unsupported";
1001
+ }
835
1002
  async upsertConnection(connection) {
836
1003
  await this.store.put(connection);
837
1004
  return connection;
@@ -1001,4 +1168,4 @@ function unique(values) {
1001
1168
  //#endregion
1002
1169
  export { InMemoryIntegrationSecretStore as a, resolveConnectionCredentials as c, createConnectorAdapterCatalogSource as d, createConnectorAdapterProvider as f, InMemoryIntegrationOAuthStateStore as i, revokeConnection as l, IntegrationError as m, signCapability as n, createConnectionCredentialResolver as o, manifestToConnector as p, verifyCapabilityToken as r, createCredentialBackedAdapterProvider as s, IntegrationHub as t, adapterManifestsToConnectors as u };
1003
1170
 
1004
- //# sourceMappingURL=hub-D13zPQGr.js.map
1171
+ //# sourceMappingURL=hub-Cl8phyJ9.js.map