@cocreate/api 1.34.0 → 2.1.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
@@ -33,6 +33,7 @@ let crud = null;
33
33
 
34
34
  const API = {
35
35
  send,
36
+ http,
36
37
  webhook,
37
38
  getApiConfig
38
39
  };
@@ -44,6 +45,8 @@ const API = {
44
45
  * @param {Object} Server - Core server instance containing CRUD and, later, a socket manager on workers.
45
46
  * @param {Object} Server.crud - Database CRUD service operator.
46
47
  * @returns {Promise<Object>} Exported API interface.
48
+ * @public
49
+ * @environment server
47
50
  */
48
51
  export async function init(Server) {
49
52
  server = Server;
@@ -59,6 +62,8 @@ export async function init(Server) {
59
62
  * @param {string} orgId - Multi-tenant organization identifier.
60
63
  * @param {string} host - Host domain identifier.
61
64
  * @returns {Proxy|undefined} Proxied target service with auto-injected tenant parameters, or undefined if target is falsy.
65
+ * @private
66
+ * @environment server
62
67
  */
63
68
  function createTenantProxy(target, orgId, host) {
64
69
  if (!target) return undefined;
@@ -96,6 +101,8 @@ function createTenantProxy(target, orgId, host) {
96
101
  * @param {string} context.organization_id - Target multi-tenant organization ID.
97
102
  * @param {string} context.host - Target host domain.
98
103
  * @returns {Object} Secure AST execution sandbox object containing firewalled utilities.
104
+ * @private
105
+ * @environment server
99
106
  */
100
107
  function createSandbox(context) {
101
108
  const isPlatformOrg = server?.organization_id && (context.organization_id === server.organization_id);
@@ -129,6 +136,11 @@ function createSandbox(context) {
129
136
  host: context.host,
130
137
 
131
138
  api: {
139
+ /**
140
+ *
141
+ * @public
142
+ * @environment server
143
+ */
132
144
  send: (apiData) => send(apiData, context)
133
145
  }
134
146
  };
@@ -178,6 +190,8 @@ function createSandbox(context) {
178
190
  * @param {Object|null} [parentContext=null] - Outer sandbox execution context when nested.
179
191
  * @returns {Promise<Object>} The mutated execution envelope, with response content assigned to `data.data`.
180
192
  * @throws {Error} If required directives are missing, provider configuration is invalid, or HTTP dispatch fails.
193
+ * @public
194
+ * @environment server
181
195
  */
182
196
  export async function send(data, parentContext = null) {
183
197
  try {
@@ -353,6 +367,85 @@ export async function send(data, parentContext = null) {
353
367
  }
354
368
  }
355
369
 
370
+ /**
371
+ * Handles inbound API HTTP requests, resolves host scope and authorizes before execution.
372
+ * @param {object} req - Native HTTP request.
373
+ * @param {object} res - Native HTTP response.
374
+ * @param {object} [parsedInput] - Body already read by the manager HTTP entrance.
375
+ * @param {Function} [execute] - Trusted dispatcher invoked only after request authorization.
376
+ * @returns {Promise<object|undefined>} Successful execution result, otherwise undefined.
377
+ * @public
378
+ * @environment server
379
+ */
380
+ export async function http(req, res, parsedInput, execute = request => server.api.send(request)) {
381
+ const reply = (status, body) => {
382
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
383
+ res.end(JSON.stringify(body));
384
+ };
385
+ if (req.method !== 'POST') {
386
+ res.setHeader('Allow', 'POST');
387
+ return reply(405, { error: 'Use POST for this operation.' });
388
+ }
389
+ if (req.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json') {
390
+ return reply(415, { error: 'An application/json body is required.' });
391
+ }
392
+ let input = parsedInput;
393
+ try {
394
+ if (input === undefined) {
395
+ const chunks = [];
396
+ let size = 0;
397
+ for await (const chunk of req) {
398
+ const buffer = Buffer.from(chunk);
399
+ size += buffer.length;
400
+ if (size > 1024 * 1024) return reply(413, { error: 'Request body exceeds 1 MiB.' });
401
+ chunks.push(buffer);
402
+ }
403
+ input = JSON.parse(Buffer.concat(chunks).toString('utf8'));
404
+ }
405
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error();
406
+ } catch {
407
+ return reply(400, { error: 'A JSON object is required.' });
408
+ }
409
+
410
+ const bearer = req.headers.authorization?.match(/^Bearer\s+(\S+)$/i)?.[1];
411
+ const apikey = bearer || input.apikey;
412
+ if ((apikey !== undefined && (typeof apikey !== 'string' || !apikey.trim())) ||
413
+ (bearer && input.apikey !== undefined && input.apikey !== bearer)) {
414
+ return reply(401, { error: 'A valid API key is required.' });
415
+ }
416
+
417
+ try {
418
+ const host = new URL(`https://${req.headers.host}`).hostname;
419
+ const organization = await server.crud.getOrganization({ host });
420
+ if (!organization?._id || organization.error) return reply(404, { error: 'Organization not found.' });
421
+ if (typeof input.api !== 'string' || !input.api.trim() ||
422
+ typeof input.endpoint !== 'string' || !input.endpoint.trim() ||
423
+ typeof input.method !== 'string' || !input.method.trim()) {
424
+ return reply(400, { error: 'api, endpoint and method are required.' });
425
+ }
426
+ const envelope = pickHttpFields(input, ['api', 'endpoint', 'method', 'data', 'region', 'headers', 'searchParams', 'timeout']);
427
+ // Scope and identity are server-resolved, never supplied by the caller.
428
+ Object.assign(envelope, { organization_id: organization._id, host, apikey });
429
+ const request = await server.authorize?.request(envelope);
430
+ if (!request) return reply(403, { error: 'Operation is not authorized.' });
431
+ const result = await execute(request);
432
+ const failed = result?.success === false || hasHttpErrors(result?.error);
433
+ reply(failed ? 400 : 200, result);
434
+ return failed ? undefined : result;
435
+ } catch (error) {
436
+ if (error.code === 'AUTHORIZATION_DENIED') return reply(403, { error: error.message });
437
+ return reply(500, { error: 'Unable to process the operation.' });
438
+ }
439
+ }
440
+
441
+ function hasHttpErrors(error) {
442
+ return Array.isArray(error) ? error.length > 0 : Boolean(error);
443
+ }
444
+
445
+ function pickHttpFields(input, fields) {
446
+ return Object.fromEntries(fields.filter(field => Object.hasOwn(input, field)).map(field => [field, input[field]]));
447
+ }
448
+
356
449
  /**
357
450
  * Processes incoming HTTP webhook requests, verifies HMAC/JWT security signatures, and executes pipelines.
358
451
  *
@@ -360,6 +453,8 @@ export async function send(data, parentContext = null) {
360
453
  * @param {Object} req - Native Node.js HTTP incoming request stream.
361
454
  * @param {Object} res - Native Node.js HTTP server response stream.
362
455
  * @returns {Promise<void>}
456
+ * @public
457
+ * @environment server
363
458
  */
364
459
  export async function webhook(req, res) {
365
460
  try {
@@ -453,6 +548,8 @@ export async function webhook(req, res) {
453
548
  * @param {number} [options.timeout=15000] - Timeout threshold in milliseconds before aborting.
454
549
  * @returns {Promise<Response>} Native fetch Response instance.
455
550
  * @throws {Error} Throws HTTP error status or network timeout error.
551
+ * @public
552
+ * @environment server
456
553
  */
457
554
  export async function makeHttpRequest(url, options) {
458
555
  const controller = new AbortController();
@@ -543,6 +640,8 @@ async function parseResponseData(response) {
543
640
  * @param {string} name - API provider identifier (e.g., 'stripe', 'openai', 'twilio').
544
641
  * @returns {Promise<Object>} Standardized API configuration object containing key, url, and headers.
545
642
  * @throws {Error} If organization mapping fails or integration settings do not exist.
643
+ * @public
644
+ * @environment server
546
645
  */
547
646
  export async function getApiConfig(data, name) {
548
647
  let { organization_id: orgId, host } = data || {};
@@ -577,3 +676,16 @@ export async function getApiConfig(data, name) {
577
676
  export default {
578
677
  init
579
678
  };
679
+
680
+ /**
681
+ * Default export contract for this module.
682
+ *
683
+ * @name api-default-export
684
+ * @kind member
685
+ * @default-export
686
+ * @environment server
687
+ * @example
688
+ * ```json
689
+ * "{ init }"
690
+ * ```
691
+ */