@cocreate/api 1.31.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.js CHANGED
@@ -15,163 +15,154 @@
15
15
  * along with this program. If not, see <https://www.gnu.org/licenses/>.
16
16
  ********************************************************************************/
17
17
 
18
+ /**
19
+ * @file Core API Handler module for dynamic multi-tenant integrations, webhook routing, and AST macro pipeline execution.
20
+ * @module @cocreate/api-handler
21
+ */
22
+
18
23
  import { URL } from 'node:url';
19
- import { getValueFromObject, objectToSearchParams, astAsync, security } from '@cocreate/utils';
24
+ import {
25
+ objectToSearchParams,
26
+ searchParamsToObject,
27
+ astAsync,
28
+ security
29
+ } from '@cocreate/utils';
20
30
 
21
- // Core module references bound dynamically upon initialization
22
31
  let server = null;
23
- let wsManager = null;
24
32
  let crud = null;
25
33
 
26
34
  const API = {
27
- init,
28
- executeApi,
29
- request,
30
- security,
31
- makeHttpRequest,
32
- getApiConfig,
33
- normalizeConfig
35
+ send,
36
+ webhook,
37
+ getApiConfig
34
38
  };
35
39
 
36
40
  /**
37
- * Binds server core services and registers WebSocket event handlers.
38
- * @param {Object} Server - Server core instance containing wsManager and crud
39
- * @returns {Object} Exported API service interface
41
+ * Binds server core services. Socket access is resolved when a request runs.
42
+ *
43
+ * @async
44
+ * @param {Object} Server - Core server instance containing CRUD and, later, a socket manager on workers.
45
+ * @param {Object} Server.crud - Database CRUD service operator.
46
+ * @returns {Promise<Object>} Exported API interface.
47
+ * @public
48
+ * @environment server
40
49
  */
41
50
  export async function init(Server) {
42
51
  server = Server;
43
- wsManager = server.wsManager;
44
52
  crud = server.crud;
45
53
 
46
- wsManager.on("api", (data) => {
47
- executeApi(data);
48
- });
49
-
50
- wsManager.on("endpoint", (data) => {
51
- executeApi(data);
52
- });
53
-
54
54
  return API;
55
55
  }
56
56
 
57
57
  /**
58
- * Normalizes raw API configuration structures into a uniform key/url/headers shape.
59
- * @param {string|Object} apiConfig - Raw configuration object or API key string
60
- * @param {string} name - Provider identifier
61
- * @returns {Object} Standardized configuration container
62
- */
63
- export function normalizeConfig(apiConfig, name) {
64
- let key = null;
65
- let url = null;
66
- let headers = {};
67
-
68
- if (typeof apiConfig === 'string') {
69
- key = apiConfig;
70
- } else if (apiConfig && typeof apiConfig === 'object') {
71
- url = apiConfig.url;
72
- headers = apiConfig.headers || {};
73
-
74
- if (apiConfig.key) {
75
- if (typeof apiConfig.key === 'string') {
76
- key = apiConfig.key;
77
- } else if (typeof apiConfig.key === 'object') {
78
- key = apiConfig.key.apiKey || apiConfig.key.key || JSON.stringify(apiConfig.key);
79
- }
80
- } else if (apiConfig.apiKey) {
81
- key = apiConfig.apiKey;
82
- }
83
-
84
- if (apiConfig.url) url = apiConfig.url;
85
- if (apiConfig.headers) headers = { ...headers, ...apiConfig.headers };
86
- }
87
-
88
- return { key, url, headers };
89
- }
90
-
91
- /**
92
- * Constructs an isolated execution sandbox enforcing multi-tenant isolation via Proxy firewalls.
93
- * @param {Object} context - Execution context containing organization, host, data, and request info
94
- * @returns {Object} Secure sandbox context for AST execution
58
+ * Creates a Proxy firewall wrapper to automatically inject multi-tenant scope parameters (`organization_id` and `host`) into target method invocations.
59
+ *
60
+ * @param {Object} target - Target service instance to proxy (e.g., crud or wsManager).
61
+ * @param {string} orgId - Multi-tenant organization identifier.
62
+ * @param {string} host - Host domain identifier.
63
+ * @returns {Proxy|undefined} Proxied target service with auto-injected tenant parameters, or undefined if target is falsy.
64
+ * @private
65
+ * @environment server
95
66
  */
96
- function createSandbox(context) {
97
- // SECURITY FIREWALL: Proxy database calls to enforce multi-tenant isolation.
98
- const secureCrud = context.crud ? new Proxy(context.crud, {
99
- get(target, prop) {
100
- const original = target[prop];
101
- if (typeof original === 'function') {
102
- return function(...args) {
103
- if (args.length === 0) {
104
- args.push({
105
- organization_id: context.organization_id,
106
- host: context.host
107
- });
108
- } else if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {
109
- args[0].organization_id = context.organization_id;
110
- args[0].host = context.host;
111
- }
112
- return original.apply(target, args);
113
- };
114
- }
115
- return original;
116
- }
117
- }) : undefined;
118
-
119
- // SECURITY FIREWALL: Proxy WebSocket manager calls for multi-tenant isolation.
120
- const secureWsManager = context.wsManager ? new Proxy(context.wsManager, {
121
- get(target, prop) {
122
- const original = target[prop];
67
+ function createTenantProxy(target, orgId, host) {
68
+ if (!target) return undefined;
69
+ return new Proxy(target, {
70
+ get(targetObj, prop) {
71
+ const original = targetObj[prop];
123
72
  if (typeof original === 'function') {
124
- return function(...args) {
73
+ return function (...args) {
125
74
  if (args.length === 0) {
126
- args.push({
127
- organization_id: context.organization_id,
128
- host: context.host
129
- });
130
- } else if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {
131
- args[0].organization_id = context.organization_id;
132
- args[0].host = context.host;
75
+ args.push({ organization_id: orgId, host });
76
+ } else if (typeof args[0] === 'object' && args[0] !== null) {
77
+ args[0].organization_id = orgId;
78
+ args[0].host = host;
133
79
  }
134
- return original.apply(target, args);
80
+ return original.apply(targetObj, args);
135
81
  };
136
82
  }
137
83
  return original;
138
84
  }
139
- }) : undefined;
85
+ });
86
+ }
140
87
 
141
- // Only expose full server instance to platform admin organization
142
- const isPlatformOrg = server && server.organization_id && (context.organization_id === server.organization_id);
88
+ /**
89
+ * Constructs an isolated execution sandbox enforcing multi-tenant isolation via proxy firewalls for AST operations.
90
+ *
91
+ * @param {Object} context - Raw execution context.
92
+ * @param {Object} [context.payload] - Execution payload data object.
93
+ * @param {Object} [context.event] - Webhook or inbound trigger event data.
94
+ * @param {Object} [context.request] - Incoming HTTP request object.
95
+ * @param {Object} [context.response] - Outgoing HTTP response object.
96
+ * @param {Object} [context.crud] - Database service interface instance.
97
+ * @param {Object} [context.wsManager] - WebSocket manager instance.
98
+ * @param {string} [context.key] - Provider key/credential string.
99
+ * @param {Object} [context.config] - Full provider API configuration object.
100
+ * @param {string} context.organization_id - Target multi-tenant organization ID.
101
+ * @param {string} context.host - Target host domain.
102
+ * @returns {Object} Secure AST execution sandbox object containing firewalled utilities.
103
+ * @private
104
+ * @environment server
105
+ */
106
+ function createSandbox(context) {
107
+ const isPlatformOrg = server?.organization_id && (context.organization_id === server.organization_id);
108
+ const secureCrud = createTenantProxy(context.crud, context.organization_id, context.host);
109
+ const secureWs = createTenantProxy(context.wsManager, context.organization_id, context.host);
143
110
 
144
111
  const sandbox = {
145
- // Core Isolated Dynamic AST Scopes
146
- data: context.data,
112
+ // Provider fields are configuration variables. For example, a
113
+ // provider record containing `token` exposes `$token` to its AST
114
+ // expressions. Trusted runtime bindings below remain authoritative.
115
+ ...(context.config || {}),
116
+ payload: context.payload,
117
+ data: context.data || context.payload,
147
118
  event: context.event,
148
- actions: context.actions,
149
119
  request: context.request,
150
- rawBody: context.rawBody,
120
+ response: context.response,
121
+ header: context.request?.headers || context.header || {},
122
+ searchParams: context.searchParams,
123
+ objectToSearchParams,
124
+ searchParamsToObject,
125
+ Buffer,
151
126
 
152
- // Safe Proxied System Objects
153
127
  crud: secureCrud,
154
- socket: secureWsManager,
155
- wsManager: secureWsManager,
156
-
157
- // Security Utility Instance
128
+ socket: secureWs,
129
+ wsManager: secureWs,
158
130
  security,
159
131
 
160
- // Host Context Identifiers
161
132
  key: context.key,
162
133
  config: context.config,
163
134
  organization_id: context.organization_id,
164
135
  host: context.host,
165
136
 
166
- // Custom operators rewritten as sandbox properties
167
137
  api: {
168
- send: async (apiData) => {
169
- return await executeApi(apiData, context);
170
- }
138
+ /**
139
+ *
140
+ * @public
141
+ * @environment server
142
+ */
143
+ send: (apiData) => send(apiData, context)
171
144
  }
172
145
  };
173
146
 
174
- // Safely inject elevated server core only when authenticated context is root platform
147
+ // Preserve privileged runtime bindings even when an evaluated record has
148
+ // ordinary fields with the same names (for example api: "stripe"). The AST
149
+ // resolver prefers the dollar-prefixed binding for operators such as
150
+ // $api.send, while output fields may continue using their natural names.
151
+ Object.assign(sandbox, {
152
+ $payload: sandbox.payload,
153
+ $data: sandbox.data,
154
+ $event: sandbox.event,
155
+ $request: sandbox.request,
156
+ $response: sandbox.response,
157
+ $header: sandbox.header,
158
+ $crud: sandbox.crud,
159
+ $socket: sandbox.socket,
160
+ $wsManager: sandbox.wsManager,
161
+ $security: sandbox.security,
162
+ $config: sandbox.config,
163
+ $api: sandbox.api
164
+ });
165
+
175
166
  if (isPlatformOrg) {
176
167
  sandbox.server = server;
177
168
  }
@@ -180,145 +171,188 @@ function createSandbox(context) {
180
171
  }
181
172
 
182
173
  /**
183
- * Resolves endpoint definitions, executes AST macros, or dispatches HTTP requests.
184
- * @param {Object} data - API execution payload containing directives
185
- * @param {Object} [parentContext=null] - Optional outer sandbox execution context
186
- * @returns {Promise<any>} Execution response payload
174
+ * Resolves endpoint definitions, executes AST macro actions, or dispatches outgoing HTTP requests.
175
+ *
176
+ * @async
177
+ * @param {Object} data - Execution directive payload.
178
+ * @param {string} [data.url] - Optional pre-formatted target HTTP endpoint URL (Direct Execution Path).
179
+ * @param {string} [data.api] - API configuration name (e.g., 'stripe-test').
180
+ * @param {string} [data.method] - HTTP method (e.g., 'post'). A matched endpoint configuration may override it.
181
+ * @param {string} [data.endpoint] - Stored endpoint name (e.g., 'create-customer') or direct API path (e.g., '/v1/customers').
182
+ * @param {*} [data.data] - Request content passed to the external API.
183
+ * @param {Object} [data.searchParams] - Query parameters appended to the request URL.
184
+ * @param {Object} [data.headers] - Custom HTTP header directives.
185
+ * @param {number} [data.timeout=15000] - Request timeout in milliseconds.
186
+ * @param {Object} [data.socket] - WebSocket client reference for real-time response emit.
187
+ * @param {string} [data.organization_id] - Multi-tenant organization identifier.
188
+ * @param {string} [data.host] - Target host domain.
189
+ * @param {Object|null} [parentContext=null] - Outer sandbox execution context when nested.
190
+ * @returns {Promise<Object>} The mutated execution envelope, with response content assigned to `data.data`.
191
+ * @throws {Error} If required directives are missing, provider configuration is invalid, or HTTP dispatch fails.
192
+ * @public
193
+ * @environment server
187
194
  */
188
- export async function executeApi(data, parentContext = null) {
195
+ export async function send(data, parentContext = null) {
189
196
  try {
197
+ const wsManager = server?.wsManager;
190
198
  const orgId = parentContext?.organization_id || data.socket?.organization_id || data.organization_id;
191
199
  const host = parentContext?.host || data.socket?.host || data.host;
192
200
 
193
- // PATH A: Native Execution of a Pre-prepared HTTP Request Object
194
- if (data.url && data.method) {
195
- const timeout = data.timeout || 15000;
196
- const options = {
197
- method: data.method.toUpperCase(),
198
- headers: data.headers || {},
199
- timeout
200
- };
201
-
202
- if (data.body) {
203
- options.body = typeof data.body === 'object' ? JSON.stringify(data.body) : data.body;
204
- }
205
-
206
- const response = await makeHttpRequest(data.url, options);
207
- const responsePayload = await response.json();
208
-
209
- if (data.socket && wsManager) {
210
- data.response = responsePayload;
211
- wsManager.send(data);
212
- }
213
- return responsePayload;
214
- }
215
-
216
- // PATH B: Standard Dynamic Configuration Resolve & Execute
217
- if (!data.method || !data.endpoint) {
218
- throw new Error("API execution request is missing 'method' or 'endpoint' directives.");
201
+ const apiName = data.api?.trim() || "";
202
+ const endpoint = data.endpoint?.trim() || "";
203
+ const payloadUrl = typeof data.url === "string"
204
+ ? data.url.trim()
205
+ : data.url || "";
206
+ const apiConfig = apiName
207
+ ? await getApiConfig({ organization_id: orgId, host }, apiName)
208
+ : {};
209
+
210
+ if (!endpoint && !payloadUrl && !apiConfig.endpoint && !apiConfig.url) {
211
+ throw new Error("API execution request requires either 'endpoint' or 'url'.");
219
212
  }
220
213
 
221
- const providerName = data.method.split(/[./]/)[0];
222
- const httpMethod = data.endpoint.split(" ")[0].toUpperCase();
214
+ let endpointConfig = {};
223
215
 
224
- const endpointQuery = {
225
- method: 'object.read',
226
- array: 'endpoints',
227
- organization_id: orgId,
228
- host: host,
229
- $filter: {
230
- query: { endpoint: data.endpoint, organization_id: orgId },
231
- limit: 1
216
+ // Every endpoint value can identify a reusable endpoint configuration.
217
+ // When no matching name exists, the value itself becomes the API path.
218
+ if (endpoint && apiConfig._id) {
219
+ const endpointFilter = {
220
+ api_id: apiConfig._id,
221
+ name: endpoint,
222
+ enabled: true
223
+ };
224
+ if (data.method?.trim()) {
225
+ endpointFilter.method = data.method.trim().toLowerCase();
232
226
  }
233
- };
234
- const endpointResponse = await crud.send(endpointQuery);
235
- const endpointConfig = endpointResponse?.object?.[0] || {};
236
227
 
237
- const rawApiConfig = await getApiConfig({ organization_id: orgId, host }, providerName);
238
- if (!rawApiConfig) {
239
- throw new Error(`Connection setting not registered for provider: '${providerName}'.`);
228
+ const endpointQuery = {
229
+ method: 'object.read',
230
+ array: 'endpoints',
231
+ organization_id: orgId,
232
+ host,
233
+ filter: {
234
+ query: endpointFilter,
235
+ limit: 1
236
+ }
237
+ };
238
+
239
+ const endpointResponse = await crud.send(endpointQuery);
240
+ endpointConfig = endpointResponse?.object?.[0] || {};
240
241
  }
241
- const apiConfig = normalizeConfig(rawApiConfig, providerName);
242
242
 
243
- const apiContext = parentContext || {
244
- data: data,
245
- event: {},
246
- actions: [],
243
+ const apiContext = {
244
+ ...(parentContext || {}),
245
+ payload: data,
246
+ event: parentContext?.event || {},
247
247
  organization_id: orgId,
248
- host: host,
249
- crud,
250
- wsManager,
248
+ host,
249
+ crud: parentContext?.crud || crud,
250
+ wsManager: parentContext?.wsManager || wsManager,
251
251
  key: apiConfig.key,
252
252
  config: apiConfig
253
253
  };
254
254
 
255
- const actions = endpointConfig.actions || endpointConfig.action;
256
- if (actions) {
257
- if (Array.isArray(actions)) {
258
- for (let i = 0; i < actions.length; i++) {
259
- const result = await astAsync({ executeAST: actions[i], sandbox: createSandbox(apiContext) });
260
- apiContext.actions.push(result);
261
- }
262
- const finalMacroResult = apiContext.actions[apiContext.actions.length - 1];
263
- if (finalMacroResult !== undefined) {
264
- data[providerName] = finalMacroResult;
265
- }
266
- } else {
267
- const result = await astAsync({ executeAST: actions, sandbox: createSandbox(apiContext) });
268
- apiContext.actions.push(result);
269
- if (result !== undefined) {
270
- data[providerName] = result;
271
- }
272
- }
255
+ // Requests layer from general to specific: payload, API configuration,
256
+ // then the matched endpoint as the authoritative macro override.
257
+ const requestData = endpointConfig.data ?? apiConfig.data ?? data.data;
258
+ const {
259
+ headers: providerHeaders,
260
+ data: providerData,
261
+ endpoint: providerEndpoint,
262
+ url: providerUrl,
263
+ method: providerMethod,
264
+ ...providerVariables
265
+ } = apiConfig;
266
+ let request = {
267
+ // Provider-native variables must exist in the execution envelope
268
+ // before endpoint and header AST expressions are evaluated.
269
+ ...providerVariables,
270
+ ...data,
271
+ ...endpointConfig,
272
+ method: endpointConfig.method?.trim() || apiConfig.method?.trim() || data.method?.trim(),
273
+ endpoint: endpointConfig.endpoint || apiConfig.endpoint || endpoint,
274
+ // URL configurations may be AST objects. Preserve them until the
275
+ // request is evaluated, then normalize the resolved string below.
276
+ url: endpointConfig.url || apiConfig.url || payloadUrl,
277
+ headers: {
278
+ ...(data.headers || {}),
279
+ ...(providerHeaders || {}),
280
+ ...(endpointConfig.headers || {})
281
+ },
282
+ timeout: endpointConfig.timeout ?? apiConfig.timeout ?? data.timeout ?? 15000,
283
+ searchParams: endpointConfig.searchParams ?? apiConfig.searchParams ?? data.searchParams
284
+ };
273
285
 
286
+ // Request data may depend on named actions, so append it after the
287
+ // endpoint definition to preserve sequential AST evaluation.
288
+ delete request.data;
289
+ request.data = requestData;
290
+
291
+ request = await astAsync({
292
+ executeAST: request,
293
+ // `$data` is the caller's original API envelope. Endpoint records
294
+ // map from it while provider fields remain top-level variables.
295
+ sandbox: createSandbox(apiContext)
296
+ });
297
+
298
+ if (request.resolved) {
299
+ data.data = request.data
274
300
  if (data.socket && wsManager) {
275
301
  wsManager.send(data);
276
302
  }
277
- return;
303
+ return data;
278
304
  }
279
305
 
280
- if (!apiConfig.url) {
281
- throw new Error(`Configuration missing 'url' base for provider '${providerName}'.`);
306
+ let url = request.url?.trim();
307
+ if (!url) {
308
+ throw new Error(`Configuration missing 'url' for API '${apiName || "direct"}'.`);
282
309
  }
283
310
 
284
- let url = apiConfig.url.endsWith("/") ? apiConfig.url.slice(0, -1) : apiConfig.url;
285
- let endpointPath = endpointConfig.path || data.endpoint.split(" ")[1];
286
- url += endpointPath.startsWith("/") ? endpointPath : `/${endpointPath}`;
287
-
288
- if (data[providerName] && data[providerName].$searchParams) {
289
- url += objectToSearchParams(data[providerName].$searchParams);
290
- delete data[providerName].$searchParams;
311
+ if (request.endpoint) {
312
+ url = url.endsWith("/") ? url.slice(0, -1) : url;
313
+ url += request.endpoint.startsWith("/") ? request.endpoint : `/${request.endpoint}`;
291
314
  }
292
315
 
293
- let headers = { ...(apiConfig.headers || {}), ...(endpointConfig.headers || {}) };
294
- headers = await astAsync({ executeAST: headers, sandbox: createSandbox(apiContext) });
316
+ const searchParams = objectToSearchParams(request.searchParams);
317
+ url += searchParams && url.includes("?") ? `&${searchParams.slice(1)}` : searchParams;
295
318
 
296
- const timeout = 15000;
297
- let options = { method: httpMethod, headers, timeout };
319
+ const resolvedHttpMethod = request.method?.trim().toUpperCase();
320
+ if (!resolvedHttpMethod) {
321
+ throw new Error(`Configuration missing 'method' for API '${apiName || "direct"}'.`);
322
+ }
323
+ const options = {
324
+ method: resolvedHttpMethod,
325
+ headers: request.headers,
326
+ timeout: request.timeout
327
+ };
298
328
 
299
- if (!["GET", "HEAD"].includes(httpMethod) && data[providerName]) {
300
- const bodyPayload = await astAsync({ executeAST: data[providerName], sandbox: createSandbox(apiContext) });
301
-
302
- if (typeof bodyPayload === 'object' && bodyPayload !== null) {
303
- options.body = JSON.stringify(bodyPayload);
304
- if (!headers["Content-Type"]) {
329
+ if (!["GET", "HEAD"].includes(resolvedHttpMethod) && request.data !== undefined) {
330
+ if (typeof request.data === 'object' && request.data !== null) {
331
+ options.body = request.encoding === "form"
332
+ ? objectToSearchParams(request.data, false)
333
+ : JSON.stringify(request.data);
334
+ if (!options.headers["Content-Type"] && !options.headers["content-type"]) {
305
335
  options.headers["Content-Type"] = "application/json; charset=utf-8";
306
336
  }
307
337
  } else {
308
- options.body = String(bodyPayload);
338
+ options.body = String(request.data);
309
339
  }
310
340
  }
311
341
 
312
342
  const response = await makeHttpRequest(url, options);
313
- const responsePayload = await response.json();
314
- data[providerName] = responsePayload;
343
+ data.data = await parseResponseData(response);
315
344
 
316
345
  if (data.socket && wsManager) {
317
346
  wsManager.send(data);
318
347
  }
319
- return responsePayload;
348
+ return data;
320
349
  } catch (error) {
321
- data.error = error.message;
350
+ const wsManager = server?.wsManager;
351
+ if (!Array.isArray(data.error)) {
352
+ data.error = data.error ? [data.error] : [];
353
+ }
354
+ data.error.push(error.message);
355
+
322
356
  if (error.response) {
323
357
  data.status = error.response.status;
324
358
  data.statusText = error.response.statusText;
@@ -326,25 +360,32 @@ export async function executeApi(data, parentContext = null) {
326
360
  }
327
361
  if (data.socket && wsManager) {
328
362
  wsManager.send(data);
363
+ return data;
329
364
  }
330
365
  throw error;
331
366
  }
332
367
  }
333
368
 
334
369
  /**
335
- * Processes incoming HTTP webhook requests, validates security signatures, and executes pipelines.
336
- * @param {Object} req - HTTP request object
337
- * @param {Object} res - HTTP response object
370
+ * Processes incoming HTTP webhook requests, verifies HMAC/JWT security signatures, and executes pipelines.
371
+ *
372
+ * @async
373
+ * @param {Object} req - Native Node.js HTTP incoming request stream.
374
+ * @param {Object} res - Native Node.js HTTP server response stream.
375
+ * @returns {Promise<void>}
376
+ * @public
377
+ * @environment server
338
378
  */
339
- export async function request(req, res) {
379
+ export async function webhook(req, res) {
340
380
  try {
381
+ const wsManager = server?.wsManager;
341
382
  const urlObject = new URL(`http://${req.headers.host}${req.url}`);
342
383
  const hostname = urlObject.hostname;
343
384
 
344
385
  let organization;
345
386
  try {
346
387
  organization = await crud.getOrganization({ host: hostname });
347
- } catch (error) {
388
+ } catch {
348
389
  res.writeHead(404, { "Content-Type": "application/json" });
349
390
  return res.end(JSON.stringify({ error: "Organization mapping not found" }));
350
391
  }
@@ -356,14 +397,12 @@ export async function request(req, res) {
356
397
  array: 'webhooks',
357
398
  organization_id: organization._id,
358
399
  host: hostname,
359
- $filter: {
360
- query: {
361
- path: webhookPath,
362
- organization_id: organization._id
363
- },
400
+ filter: {
401
+ query: { path: webhookPath, enabled: true },
364
402
  limit: 1
365
403
  }
366
404
  };
405
+
367
406
  const webhookResponse = await crud.send(webhookQuery);
368
407
  const webhookConfig = webhookResponse?.object?.[0];
369
408
 
@@ -372,89 +411,44 @@ export async function request(req, res) {
372
411
  return res.end(JSON.stringify({ error: `Webhook configuration for path '${webhookPath}' not found.` }));
373
412
  }
374
413
 
375
- let rawBody = "";
376
- await new Promise((resolve, reject) => {
377
- req.on("data", (chunk) => { rawBody += chunk.toString(); });
378
- req.on("end", resolve);
379
- req.on("error", reject);
380
- });
381
-
382
- const queryParams = Object.fromEntries(urlObject.searchParams.entries());
383
-
384
- let parsedEvent = {};
385
- if (rawBody) {
386
- try {
387
- parsedEvent = JSON.parse(rawBody);
388
- } catch {
389
- parsedEvent = { rawBody };
390
- }
414
+ let apiConfig = {};
415
+ if (webhookConfig.api_id) {
416
+ const apiResponse = await crud.send({
417
+ method: 'object.read',
418
+ array: 'apis',
419
+ organization_id: organization._id,
420
+ host: hostname,
421
+ filter: {
422
+ query: { _id: webhookConfig.api_id, enabled: true },
423
+ limit: 1
424
+ }
425
+ });
426
+ apiConfig = apiResponse?.object?.[0] || {};
391
427
  }
392
428
 
393
429
  const context = {
394
- data: {},
395
- event: parsedEvent,
396
- actions: [],
397
430
  request: req,
398
431
  response: res,
399
- rawBody: rawBody,
432
+ searchParams: searchParamsToObject(urlObject.searchParams),
400
433
  host: hostname,
401
- organization: organization,
434
+ organization,
402
435
  organization_id: organization._id,
403
- crud: crud,
404
- wsManager: wsManager
436
+ crud,
437
+ wsManager,
438
+ key: apiConfig.key,
439
+ config: apiConfig
405
440
  };
406
441
 
407
- context.request.query = queryParams;
408
-
409
- if (webhookConfig.authenticate) {
410
- const auth = webhookConfig.authenticate;
411
- if (auth.method === "webhooks.constructEvent" && Array.isArray(auth.parameters)) {
412
- const resolvedParams = await astAsync({ executeAST: [...auth.parameters], sandbox: createSandbox(context) });
413
- const payload = resolvedParams[0];
414
- const signature = resolvedParams[1];
415
- const secret = resolvedParams[2];
416
-
417
- const computedSignature = security.createWebhookSignature(payload, secret, { format: 'github' });
418
- const expectedSignature = String(signature);
419
-
420
- if (!security.timingSafeEqual(computedSignature, expectedSignature)) {
421
- res.writeHead(401, { "Content-Type": "application/json" });
422
- return res.end(JSON.stringify({ error: "Unauthorized access: signature verification failed." }));
423
- }
424
- }
425
- }
426
-
427
- let executeOperations = null;
428
- const actionConfig = webhookConfig.action;
429
-
430
- if (actionConfig) {
431
- if (typeof actionConfig === 'string') {
432
- const actionName = await astAsync({ executeAST: actionConfig, sandbox: createSandbox(context) });
433
- if (actionName && webhookConfig.actions?.[actionName]) {
434
- executeOperations = webhookConfig.actions[actionName];
435
- }
436
- } else {
437
- executeOperations = actionConfig;
438
- }
439
- }
440
-
441
- if (executeOperations) {
442
- if (Array.isArray(executeOperations)) {
443
- for (let i = 0; i < executeOperations.length; i++) {
444
- const stepResult = await astAsync({ executeAST: executeOperations[i], sandbox: createSandbox(context) });
445
- context.actions.push(stepResult);
446
- }
447
- } else if (typeof executeOperations === 'object' && executeOperations !== null) {
448
- const stepResult = await astAsync({ executeAST: [executeOperations], sandbox: createSandbox(context) });
449
- context.actions.push(stepResult);
450
- }
451
- }
442
+ const result = await astAsync({
443
+ executeAST: webhookConfig,
444
+ sandbox: createSandbox(context)
445
+ });
452
446
 
453
447
  if (res && !res.writableEnded) {
454
448
  res.writeHead(200, { "Content-Type": "application/json" });
455
- res.end(JSON.stringify({
456
- message: "Webhook processed successfully",
457
- payload: context.actions[context.actions.length - 1] || {}
449
+ res.end(JSON.stringify({
450
+ message: "Webhook processed successfully",
451
+ payload: result
458
452
  }));
459
453
  }
460
454
  } catch (error) {
@@ -465,62 +459,116 @@ export async function request(req, res) {
465
459
  }
466
460
  }
467
461
 
468
- // Re-export security library instance
469
- export { security };
470
-
471
462
  /**
472
- * Low-level HTTP dispatch utility wrapping global fetch with AbortController timeout handling.
473
- * @param {string} url - Target URL endpoint
474
- * @param {Object} options - Fetch options (method, headers, body, signal, timeout)
475
- * @returns {Promise<Response>} Native fetch response instance
463
+ * Low-level HTTP dispatch utility wrapping native `fetch` with AbortController timeout handling.
464
+ *
465
+ * @async
466
+ * @param {string} url - Absolute target URL endpoint.
467
+ * @param {Object} [options={}] - Fetch request options (method, headers, body, signal).
468
+ * @param {number} [options.timeout=15000] - Timeout threshold in milliseconds before aborting.
469
+ * @returns {Promise<Response>} Native fetch Response instance.
470
+ * @throws {Error} Throws HTTP error status or network timeout error.
471
+ * @public
472
+ * @environment server
476
473
  */
477
474
  export async function makeHttpRequest(url, options) {
478
- let controller, timeoutId;
479
- if (global.AbortController) {
480
- controller = new global.AbortController();
481
- timeoutId = setTimeout(() => controller.abort(), options.timeout || 15000);
482
- options.signal = controller.signal;
483
- }
484
-
485
- const fetchFn = global.fetch;
486
- if (typeof fetchFn !== "function") {
487
- throw new Error("System runtime environment is missing a valid HTTP fetch implementation.");
488
- }
475
+ const controller = new AbortController();
476
+ const timeoutId = setTimeout(() => controller.abort(), options.timeout || 15000);
477
+ options.signal = controller.signal;
489
478
 
490
479
  try {
491
- const response = await fetchFn(url, options);
492
- if (timeoutId) clearTimeout(timeoutId);
480
+ const response = await fetch(url, options);
481
+ clearTimeout(timeoutId);
493
482
 
494
483
  if (!response.ok) {
495
484
  const text = await response.text();
496
- const error = new Error(`HTTP error! Status: ${response.status} ${response.statusText}`);
485
+ const providerError = parseXmlError(text);
486
+ const detail = providerError?.message;
487
+ const code = providerError?.code;
488
+ const error = new Error(
489
+ detail
490
+ ? `${code ? `${code}: ` : ""}${detail}`
491
+ : `HTTP error! Status: ${response.status} ${response.statusText}`
492
+ );
497
493
  error.response = {
498
494
  status: response.status,
499
495
  statusText: response.statusText,
500
- data: text
496
+ data: text,
497
+ error: providerError
501
498
  };
502
499
  throw error;
503
500
  }
504
501
  return response;
505
502
  } catch (error) {
506
- if (timeoutId) clearTimeout(timeoutId);
503
+ clearTimeout(timeoutId);
507
504
  throw error;
508
505
  }
509
506
  }
510
507
 
508
+ function decodeXmlText(value) {
509
+ if (value === undefined) return undefined;
510
+ return value
511
+ .replace(/&#x([\da-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
512
+ .replace(/&#(\d+);/g, (_, decimal) => String.fromCodePoint(parseInt(decimal, 10)))
513
+ .replace(/&lt;/g, "<")
514
+ .replace(/&gt;/g, ">")
515
+ .replace(/&quot;/g, '"')
516
+ .replace(/&apos;/g, "'")
517
+ .replace(/&amp;/g, "&");
518
+ }
519
+
520
+ function getXmlTagValue(xml, tagName) {
521
+ if (!xml || typeof xml !== "string") return undefined;
522
+ const match = xml.match(
523
+ new RegExp(`<${tagName}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${tagName}>`, "i")
524
+ );
525
+ return match ? decodeXmlText(match[1].trim()) : undefined;
526
+ }
527
+
528
+ function parseXmlError(text) {
529
+ if (!text || typeof text !== "string" || !text.trimStart().startsWith("<")) {
530
+ return undefined;
531
+ }
532
+
533
+ const code = getXmlTagValue(text, "Code");
534
+ const message = getXmlTagValue(text, "Message");
535
+ const requestId = getXmlTagValue(text, "RequestId") ||
536
+ getXmlTagValue(text, "RequestID");
537
+
538
+ if (!code && !message && !requestId) return undefined;
539
+ return { code, message, requestId };
540
+ }
541
+
542
+ async function parseResponseData(response) {
543
+ const text = await response.text();
544
+ if (!text) return null;
545
+
546
+ try {
547
+ return JSON.parse(text);
548
+ } catch {
549
+ return text;
550
+ }
551
+ }
552
+
511
553
  /**
512
- * Queries database storage for provider connection credentials and API configuration.
513
- * @param {Object} data - Context query parameters (organization_id, host)
514
- * @param {string} name - API provider name
515
- * @returns {Promise<Object>} API provider configuration object
554
+ * Queries database storage for provider connection credentials and API configuration settings.
555
+ *
556
+ * @async
557
+ * @param {Object} data - Context object containing search criteria.
558
+ * @param {string} [data.organization_id] - Target organization ID (resolves via hostname if absent).
559
+ * @param {string} [data.host] - Target host domain.
560
+ * @param {string} name - API provider identifier (e.g., 'stripe', 'openai', 'twilio').
561
+ * @returns {Promise<Object>} Standardized API configuration object containing key, url, and headers.
562
+ * @throws {Error} If organization mapping fails or integration settings do not exist.
563
+ * @public
564
+ * @environment server
516
565
  */
517
566
  export async function getApiConfig(data, name) {
518
- let orgId = data.organization_id;
519
- let host = data.host;
520
-
567
+ let { organization_id: orgId, host } = data || {};
568
+
521
569
  if (!orgId) {
522
570
  const organization = await crud.getOrganization(data);
523
- if (organization.error) throw new Error(organization.error);
571
+ if (organization?.error) throw new Error(organization.error);
524
572
  orgId = organization._id;
525
573
  }
526
574
 
@@ -528,18 +576,36 @@ export async function getApiConfig(data, name) {
528
576
  method: 'object.read',
529
577
  array: 'apis',
530
578
  organization_id: orgId,
531
- host: host,
532
- $filter: {
533
- query: { name: name, organization_id: orgId },
579
+ host,
580
+ filter: {
581
+ query: { name, enabled: true },
534
582
  limit: 1
535
583
  }
536
584
  };
537
-
585
+
538
586
  const response = await crud.send(query);
539
587
  const apiConfig = response?.object?.[0];
540
588
 
541
- if (!apiConfig) throw new Error(`Integration settings are missing for provider: '${name}'`);
589
+ if (!apiConfig) {
590
+ throw new Error(`Integration settings are missing for provider: '${name}'`);
591
+ }
592
+
542
593
  return apiConfig;
543
594
  }
544
595
 
545
- export default API;
596
+ export default {
597
+ init
598
+ };
599
+
600
+ /**
601
+ * Default export contract for this module.
602
+ *
603
+ * @name api-default-export
604
+ * @kind member
605
+ * @default-export
606
+ * @environment server
607
+ * @example
608
+ * ```json
609
+ * "{ init }"
610
+ * ```
611
+ */